From 8c3d9f8c396c1e6fd15db6c79d5f77e37c2ba893 Mon Sep 17 00:00:00 2001 From: Matt Duffin Date: Sun, 5 Jul 2015 14:49:00 +0100 Subject: [PATCH 01/98] Added word wrapping For those of us on small monitors or who just dislike horizontal scrollbars, this adds an 'Enable word wrap' option to the Display settings, which causes the decompilation view to wrap if enabled. --- ILSpy/Options/DisplaySettings.cs | 17 ++++++++++++++++- ILSpy/Options/DisplaySettingsPanel.xaml | 1 + ILSpy/Options/DisplaySettingsPanel.xaml.cs | 2 ++ ILSpy/TextView/DecompilerTextView.cs | 5 +++-- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/ILSpy/Options/DisplaySettings.cs b/ILSpy/Options/DisplaySettings.cs index eddefb313..8f73b095c 100644 --- a/ILSpy/Options/DisplaySettings.cs +++ b/ILSpy/Options/DisplaySettings.cs @@ -96,12 +96,27 @@ namespace ICSharpCode.ILSpy.Options } } - public void CopyValues(DisplaySettings s) + bool enableWordWrap; + + public bool EnableWordWrap + { + get { return enableWordWrap; } + set + { + if (enableWordWrap != value) { + enableWordWrap = value; + OnPropertyChanged("EnableWordWrap"); + } + } + } + + public void CopyValues(DisplaySettings s) { this.SelectedFont = s.selectedFont; this.SelectedFontSize = s.selectedFontSize; this.ShowLineNumbers = s.showLineNumbers; this.ShowMetadataTokens = s.showMetadataTokens; + this.EnableWordWrap = s.enableWordWrap; } } } diff --git a/ILSpy/Options/DisplaySettingsPanel.xaml b/ILSpy/Options/DisplaySettingsPanel.xaml index aa9c329d0..d14bb0dd7 100644 --- a/ILSpy/Options/DisplaySettingsPanel.xaml +++ b/ILSpy/Options/DisplaySettingsPanel.xaml @@ -61,6 +61,7 @@ Show line numbers Show metadata tokens + Enable word wrap diff --git a/ILSpy/Options/DisplaySettingsPanel.xaml.cs b/ILSpy/Options/DisplaySettingsPanel.xaml.cs index 8cdfce312..6ad4d8a58 100644 --- a/ILSpy/Options/DisplaySettingsPanel.xaml.cs +++ b/ILSpy/Options/DisplaySettingsPanel.xaml.cs @@ -101,6 +101,7 @@ namespace ICSharpCode.ILSpy.Options s.SelectedFontSize = (double?)e.Attribute("FontSize") ?? 10.0 * 4 / 3; s.ShowLineNumbers = (bool?)e.Attribute("ShowLineNumbers") ?? false; s.ShowMetadataTokens = (bool?) e.Attribute("ShowMetadataTokens") ?? false; + s.EnableWordWrap = (bool?)e.Attribute("EnableWordWrap") ?? false; return s; } @@ -116,6 +117,7 @@ namespace ICSharpCode.ILSpy.Options section.SetAttributeValue("FontSize", s.SelectedFontSize); section.SetAttributeValue("ShowLineNumbers", s.ShowLineNumbers); section.SetAttributeValue("ShowMetadataTokens", s.ShowMetadataTokens); + section.SetAttributeValue("EnableWordWrap", s.EnableWordWrap); XElement existingElement = root.Element("DisplaySettings"); if (existingElement != null) diff --git a/ILSpy/TextView/DecompilerTextView.cs b/ILSpy/TextView/DecompilerTextView.cs index 2b6e7bba0..b99b752bf 100644 --- a/ILSpy/TextView/DecompilerTextView.cs +++ b/ILSpy/TextView/DecompilerTextView.cs @@ -97,8 +97,9 @@ namespace ICSharpCode.ILSpy.TextView textEditor.TextArea.TextView.MouseDown += TextViewMouseDown; textEditor.SetBinding(Control.FontFamilyProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("SelectedFont") }); textEditor.SetBinding(Control.FontSizeProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("SelectedFontSize") }); - - textMarkerService = new TextMarkerService(textEditor.TextArea.TextView); + textEditor.SetBinding(TextEditor.WordWrapProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("EnableWordWrap") }); + + textMarkerService = new TextMarkerService(textEditor.TextArea.TextView); textEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); textEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); textEditor.ShowLineNumbers = true; From a1160535101544b86ce01e61bdbea5a4a5f4c755 Mon Sep 17 00:00:00 2001 From: LordJZ Date: Mon, 6 Jul 2015 20:17:17 +0300 Subject: [PATCH 02/98] Fixed #619 custom attributes on enum members --- ICSharpCode.Decompiler/Ast/AstBuilder.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/ICSharpCode.Decompiler/Ast/AstBuilder.cs b/ICSharpCode.Decompiler/Ast/AstBuilder.cs index 779e4ecf2..b62307296 100644 --- a/ICSharpCode.Decompiler/Ast/AstBuilder.cs +++ b/ICSharpCode.Decompiler/Ast/AstBuilder.cs @@ -331,6 +331,7 @@ namespace ICSharpCode.Decompiler.Ast } } else { EnumMemberDeclaration enumMember = new EnumMemberDeclaration(); + ConvertCustomAttributes(enumMember, field); enumMember.AddAnnotation(field); enumMember.Name = CleanName(field.Name); long memberValue = (long)CSharpPrimitiveCast.Cast(TypeCode.Int64, field.Constant, false); From 75dfa785d71c97c140f7911e2243c21614b2be54 Mon Sep 17 00:00:00 2001 From: Daniel Grunwald Date: Sun, 12 Jul 2015 18:11:26 +0200 Subject: [PATCH 03/98] Fix #600: variable called int should be displayed as @int --- ICSharpCode.Decompiler/Ast/TextTokenWriter.cs | 4 ++++ .../OutputVisitor/CSharpOutputVisitor.cs | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/ICSharpCode.Decompiler/Ast/TextTokenWriter.cs b/ICSharpCode.Decompiler/Ast/TextTokenWriter.cs index bd5c71698..2cfff7d96 100644 --- a/ICSharpCode.Decompiler/Ast/TextTokenWriter.cs +++ b/ICSharpCode.Decompiler/Ast/TextTokenWriter.cs @@ -53,6 +53,10 @@ namespace ICSharpCode.Decompiler.Ast public override void WriteIdentifier(Identifier identifier) { + if (identifier.IsVerbatim || CSharpOutputVisitor.IsKeyword(identifier.Name, identifier)) { + output.Write('@'); + } + var definition = GetCurrentDefinition(); if (definition != null) { output.WriteDefinition(identifier.Name, definition, false); diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs index 4fc5ed9f7..dad86b3da 100644 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs +++ b/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs @@ -1158,7 +1158,7 @@ namespace ICSharpCode.NRefactory.CSharp StartNode(attributeSection); WriteToken(Roles.LBracket); if (!string.IsNullOrEmpty(attributeSection.AttributeTarget)) { - WriteIdentifier(attributeSection.AttributeTargetToken); + WriteKeyword(attributeSection.AttributeTarget, Roles.Identifier); WriteToken(Roles.Colon); Space(); } From b018a188aeda6841841bf6df60fcf5acf30d92c4 Mon Sep 17 00:00:00 2001 From: Daniel Grunwald Date: Sun, 12 Jul 2015 18:37:31 +0200 Subject: [PATCH 04/98] Fix #607: return value attributes missing in IL view --- .../Disassembler/ReflectionDisassembler.cs | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs index 1a7d1a4f7..fcdb2b926 100644 --- a/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs +++ b/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs @@ -33,7 +33,7 @@ namespace ICSharpCode.Decompiler.Disassembler /// public sealed class ReflectionDisassembler { - ITextOutput output; + readonly ITextOutput output; CancellationToken cancellationToken; bool isInType; // whether we are currently disassembling a whole type (-> defaultCollapsed for foldings) MethodBodyDisassembler methodBodyDisassembler; @@ -213,8 +213,9 @@ namespace ICSharpCode.Decompiler.Disassembler output.WriteLine(); } } + WriteParameterAttributes(0, method.MethodReturnType, method.MethodReturnType); foreach (var p in method.Parameters) { - WriteParameterAttributes(p); + WriteParameterAttributes(p.Index + 1, p, p); } WriteSecurityDeclarations(method); @@ -613,22 +614,17 @@ namespace ICSharpCode.Decompiler.Disassembler } } - bool HasParameterAttributes(ParameterDefinition p) + void WriteParameterAttributes(int index, IConstantProvider cp, ICustomAttributeProvider cap) { - return p.HasConstant || p.HasCustomAttributes; - } - - void WriteParameterAttributes(ParameterDefinition p) - { - if (!HasParameterAttributes(p)) + if (!cp.HasConstant && !cap.HasCustomAttributes) return; - output.Write(".param [{0}]", p.Index + 1); - if (p.HasConstant) { + output.Write(".param [{0}]", index); + if (cp.HasConstant) { output.Write(" = "); - WriteConstant(p.Constant); + WriteConstant(cp.Constant); } output.WriteLine(); - WriteAttributes(p.CustomAttributes); + WriteAttributes(cap.CustomAttributes); } void WriteConstant(object constant) From d584349eecdf7f4aa921478b03429aa322511b21 Mon Sep 17 00:00:00 2001 From: Daniel Grunwald Date: Sun, 12 Jul 2015 20:39:35 +0200 Subject: [PATCH 05/98] Set version number to 2.3.1. --- ILSpy/Properties/AssemblyInfo.template.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ILSpy/Properties/AssemblyInfo.template.cs b/ILSpy/Properties/AssemblyInfo.template.cs index 852772ae1..c4be7cef5 100644 --- a/ILSpy/Properties/AssemblyInfo.template.cs +++ b/ILSpy/Properties/AssemblyInfo.template.cs @@ -36,7 +36,7 @@ internal static class RevisionClass { public const string Major = "2"; public const string Minor = "3"; - public const string Build = "0"; + public const string Build = "1"; public const string Revision = "$INSERTREVISION$"; public const string VersionName = null; From 2726336b3a56d343457b453d9be76b793ea2ebc0 Mon Sep 17 00:00:00 2001 From: Christoph Wille Date: Mon, 13 Jul 2015 06:25:41 +0200 Subject: [PATCH 06/98] Update addin version, update decompiler package version --- ILSpy.AddIn/source.extension.vsixmanifest | 2 +- packages/ICSharpCode.Decompiler.nuspec | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ILSpy.AddIn/source.extension.vsixmanifest b/ILSpy.AddIn/source.extension.vsixmanifest index 7be4f368e..637407569 100644 --- a/ILSpy.AddIn/source.extension.vsixmanifest +++ b/ILSpy.AddIn/source.extension.vsixmanifest @@ -3,7 +3,7 @@ ILSpy IC#Code - 1.2 + 1.3 Integrates the ILSpy decompiler into Visual Studio. ILSpy-Large.ico license.txt diff --git a/packages/ICSharpCode.Decompiler.nuspec b/packages/ICSharpCode.Decompiler.nuspec index 8f8552b65..e5201fed0 100644 --- a/packages/ICSharpCode.Decompiler.nuspec +++ b/packages/ICSharpCode.Decompiler.nuspec @@ -2,7 +2,7 @@ ICSharpCode.Decompiler - 2.3.0 + 2.3.1 ILSpy Decompiler Engine Daniel Grunwald, David Srbecky, Ed Harvey, Siegfried Pammer Daniel Grunwald, SharpDevelop From e2ec7e85602c483079579a74fe3c707b0dab6281 Mon Sep 17 00:00:00 2001 From: neolithos Date: Thu, 3 Sep 2015 17:42:02 +0200 Subject: [PATCH 07/98] Changed SearchStrategies: Added - for not contain = for equal + for contain --- ILSpy/SearchStrategies.cs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/ILSpy/SearchStrategies.cs b/ILSpy/SearchStrategies.cs index c75125293..0f57dccad 100644 --- a/ILSpy/SearchStrategies.cs +++ b/ILSpy/SearchStrategies.cs @@ -37,8 +37,31 @@ namespace ICSharpCode.ILSpy for (int i = 0; i < searchTerm.Length; ++i) { // How to handle overlapping matches? - if (text.IndexOf(searchTerm[i], StringComparison.OrdinalIgnoreCase) < 0) - return false; + var term = searchTerm[i]; + switch (term[0]) + { + case '+': // must contain + term = term.Substring(1); + goto default; + case '-': // should not contain + if (term.Length > 1 && text.IndexOf(term.Substring(1), StringComparison.OrdinalIgnoreCase) >= 0) + return false; + break; + case '=': // exact match + { + var equalCompareLength = text.IndexOf('`'); + if (equalCompareLength == -1) + equalCompareLength = text.Length; + + if (term.Length > 1 && String.Compare(term, 1, text, 0, equalCompareLength, StringComparison.OrdinalIgnoreCase) != 0) + return false; + } + break; + default: + if (text.IndexOf(term, StringComparison.OrdinalIgnoreCase) < 0) + return false; + break; + } } return true; } From 8e29aea8b5403d3827088c6c8713454668834300 Mon Sep 17 00:00:00 2001 From: neolithos Date: Thu, 3 Sep 2015 18:42:56 +0200 Subject: [PATCH 08/98] Fix: Equal compare --- ILSpy/SearchStrategies.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ILSpy/SearchStrategies.cs b/ILSpy/SearchStrategies.cs index 0f57dccad..302f261db 100644 --- a/ILSpy/SearchStrategies.cs +++ b/ILSpy/SearchStrategies.cs @@ -53,7 +53,7 @@ namespace ICSharpCode.ILSpy if (equalCompareLength == -1) equalCompareLength = text.Length; - if (term.Length > 1 && String.Compare(term, 1, text, 0, equalCompareLength, StringComparison.OrdinalIgnoreCase) != 0) + if (term.Length > 1 && String.Compare(term, 1, text, 0, Math.Max(term.Length, equalCompareLength), StringComparison.OrdinalIgnoreCase) != 0) return false; } break; From 24054895bc5c594c31aea099080645f2dddeb354 Mon Sep 17 00:00:00 2001 From: Crazycatz00 Date: Wed, 11 Nov 2015 04:58:10 -0500 Subject: [PATCH 09/98] Use portable settings file if it exists --- ILSpy/ILSpySettings.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ILSpy/ILSpySettings.cs b/ILSpy/ILSpySettings.cs index 915947071..0d5c968cf 100644 --- a/ILSpy/ILSpySettings.cs +++ b/ILSpy/ILSpySettings.cs @@ -115,6 +115,9 @@ namespace ICSharpCode.ILSpy static string GetConfigFile() { + string localPath = Path.Combine(Path.GetDirectoryName(typeof(MainWindow).Assembly.Location), "ILSpy.xml"); + if (File.Exists(localPath)) + return localPath; return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ICSharpCode\\ILSpy.xml"); } From 3fa8ec0e54e7de764ff49425a8b64c2f6be98d4d Mon Sep 17 00:00:00 2001 From: hardcase Date: Fri, 11 Dec 2015 17:34:19 +0300 Subject: [PATCH 10/98] Fix #635. Decompile static methods in interfaces. --- ICSharpCode.Decompiler/Ast/AstBuilder.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/ICSharpCode.Decompiler/Ast/AstBuilder.cs b/ICSharpCode.Decompiler/Ast/AstBuilder.cs index b62307296..43e278c47 100644 --- a/ICSharpCode.Decompiler/Ast/AstBuilder.cs +++ b/ICSharpCode.Decompiler/Ast/AstBuilder.cs @@ -771,6 +771,7 @@ namespace ICSharpCode.Decompiler.Ast astMethod.Name = CleanName(methodDef.Name); astMethod.TypeParameters.AddRange(MakeTypeParameters(methodDef.GenericParameters)); astMethod.Parameters.AddRange(MakeParameters(methodDef)); + bool createMethodBody = false; // constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly if (!methodDef.IsVirtual || (methodDef.IsNewSlot && !methodDef.IsPrivate)) astMethod.Constraints.AddRange(MakeConstraints(methodDef.GenericParameters)); if (!methodDef.DeclaringType.IsInterface) { @@ -781,6 +782,13 @@ namespace ICSharpCode.Decompiler.Ast if (methodDef.IsVirtual == methodDef.IsNewSlot) SetNewModifier(astMethod); } + createMethodBody = true; + } else if (methodDef.IsStatic) { + // decompile static method in interface + astMethod.Modifiers = ConvertModifiers(methodDef); + createMethodBody = true; + } + if (createMethodBody) { astMethod.Body = CreateMethodBody(methodDef, astMethod.Parameters); if (context.CurrentMethodIsAsync) { astMethod.Modifiers |= Modifiers.Async; From 4a54d40da43549908cda88b5814c531ff97c31a3 Mon Sep 17 00:00:00 2001 From: Daniel Grunwald Date: Fri, 11 Dec 2015 22:48:58 +0100 Subject: [PATCH 11/98] Add appveyor.yml to master branch, too --- appveyor.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 appveyor.yml diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 000000000..2870d918a --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,11 @@ +version: 1.0.{build} +configuration: Debug +platform: Any CPU +install: +- git submodule update --init --recursive +before_build: +- nuget restore ILSpy.sln +build: + project: ILSpy.sln + parallel: true + verbosity: minimal \ No newline at end of file From bf5861babd892dc54b0bca8cdd2b3f7d9db6712e Mon Sep 17 00:00:00 2001 From: Daniel Grunwald Date: Sat, 12 Dec 2015 15:55:47 +0100 Subject: [PATCH 12/98] Fix #650 - C++ switch over `char`/`long` values crashes ILSpy --- ICSharpCode.Decompiler/ILAst/TypeAnalysis.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ICSharpCode.Decompiler/ILAst/TypeAnalysis.cs b/ICSharpCode.Decompiler/ILAst/TypeAnalysis.cs index 6ed1f4dc0..a507ebcc2 100644 --- a/ICSharpCode.Decompiler/ILAst/TypeAnalysis.cs +++ b/ICSharpCode.Decompiler/ILAst/TypeAnalysis.cs @@ -1266,6 +1266,9 @@ namespace ICSharpCode.Decompiler.ILAst return TypeCode.Double; case MetadataType.String: return TypeCode.String; + case MetadataType.RequiredModifier: + case MetadataType.OptionalModifier: + return GetTypeCode(((IModifierType)type).ElementType); default: return TypeCode.Object; } From fe3bee36add7f0678368d8635e48920ebae3fe19 Mon Sep 17 00:00:00 2001 From: Daniel Grunwald Date: Wed, 23 Dec 2015 16:48:32 +0100 Subject: [PATCH 13/98] Use tabs, not spaces. --- BuildTools/tidy.py | 30 ++++++++++++ .../Ast/AstMethodBodyBuilder.cs | 2 +- .../Disassembler/MethodBodyDisassembler.cs | 4 +- ILSpy/OpenListDialog.xaml.cs | 10 ++-- ILSpy/Options/DisplaySettings.cs | 28 +++++------ ILSpy/Options/DisplaySettingsPanel.xaml.cs | 2 +- ILSpy/Properties/WPFAssemblyInfo.cs | 14 +++--- ILSpy/TextView/DecompilerTextView.cs | 4 +- .../Analyzer/RemoveAnalyzeContextMenuEntry.cs | 8 ++-- ILSpy/TreeNodes/AssemblyListTreeNode.cs | 48 +++++++++---------- appveyor.yml | 4 +- 11 files changed, 93 insertions(+), 61 deletions(-) create mode 100644 BuildTools/tidy.py diff --git a/BuildTools/tidy.py b/BuildTools/tidy.py new file mode 100644 index 000000000..97b349425 --- /dev/null +++ b/BuildTools/tidy.py @@ -0,0 +1,30 @@ +import os, sys + +def check(filename): + ok = True + with open(filename, 'r') as f: + for i, line in enumerate(f): + if line.startswith(' '): + print('{}:{}: Line starting with spaces. Use tabs for indentation instead!'.format(filename, i+1)) + ok = False + return ok + +def main(): + root_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), '..')) + dirs_to_check = ( + os.path.join(root_dir, subdir) + for subdir in ('ICSharpCode.Decompiler', 'ILSpy', 'ILSpy.BamlDecompiler')) + ok = True + for dir in dirs_to_check: + for root, dirs, files in os.walk(dir): + if '\\obj\\' in root: + continue + for filename in files: + if filename.lower().endswith('.cs'): + if not check(os.path.join(root, filename)): + ok = False + print('Tidy check: {}'.format('successful' if ok else 'failed')) + return 0 if ok else 1 + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/ICSharpCode.Decompiler/Ast/AstMethodBodyBuilder.cs b/ICSharpCode.Decompiler/Ast/AstMethodBodyBuilder.cs index e98e8dbc7..b5b7d57ff 100644 --- a/ICSharpCode.Decompiler/Ast/AstMethodBodyBuilder.cs +++ b/ICSharpCode.Decompiler/Ast/AstMethodBodyBuilder.cs @@ -715,7 +715,7 @@ namespace ICSharpCode.Decompiler.Ast } return new StackAllocExpression { Type = AstBuilder.ConvertType(type), - CountExpression = arg1 + CountExpression = arg1 }; } case ILCode.Mkrefany: diff --git a/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs b/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs index ef6d32e69..9ec39f23a 100644 --- a/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs +++ b/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs @@ -54,8 +54,8 @@ namespace ICSharpCode.Decompiler.Disassembler output.WriteLine("// Method begins at RVA 0x{0:x4}", method.RVA); output.WriteLine("// Code size {0} (0x{0:x})", body.CodeSize); output.WriteLine(".maxstack {0}", body.MaxStackSize); - if (method.DeclaringType.Module.Assembly != null && method.DeclaringType.Module.Assembly.EntryPoint == method) - output.WriteLine (".entrypoint"); + if (method.DeclaringType.Module.Assembly != null && method.DeclaringType.Module.Assembly.EntryPoint == method) + output.WriteLine (".entrypoint"); if (method.Body.HasVariables) { output.Write(".locals "); diff --git a/ILSpy/OpenListDialog.xaml.cs b/ILSpy/OpenListDialog.xaml.cs index 3da2a9ed3..61f1bd855 100644 --- a/ILSpy/OpenListDialog.xaml.cs +++ b/ILSpy/OpenListDialog.xaml.cs @@ -181,11 +181,11 @@ namespace ICSharpCode.ILSpy manager.DeleteList(listView.SelectedItem.ToString()); } - private void listView_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - if (e.ChangedButton == MouseButton.Left && listView.SelectedItem != null) - this.DialogResult = true; - } + private void listView_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (e.ChangedButton == MouseButton.Left && listView.SelectedItem != null) + this.DialogResult = true; + } } } diff --git a/ILSpy/Options/DisplaySettings.cs b/ILSpy/Options/DisplaySettings.cs index 8f73b095c..d1d703434 100644 --- a/ILSpy/Options/DisplaySettings.cs +++ b/ILSpy/Options/DisplaySettings.cs @@ -96,27 +96,27 @@ namespace ICSharpCode.ILSpy.Options } } - bool enableWordWrap; + bool enableWordWrap; - public bool EnableWordWrap - { - get { return enableWordWrap; } - set - { - if (enableWordWrap != value) { - enableWordWrap = value; - OnPropertyChanged("EnableWordWrap"); - } - } - } + public bool EnableWordWrap + { + get { return enableWordWrap; } + set + { + if (enableWordWrap != value) { + enableWordWrap = value; + OnPropertyChanged("EnableWordWrap"); + } + } + } - public void CopyValues(DisplaySettings s) + public void CopyValues(DisplaySettings s) { this.SelectedFont = s.selectedFont; this.SelectedFontSize = s.selectedFontSize; this.ShowLineNumbers = s.showLineNumbers; this.ShowMetadataTokens = s.showMetadataTokens; - this.EnableWordWrap = s.enableWordWrap; + this.EnableWordWrap = s.enableWordWrap; } } } diff --git a/ILSpy/Options/DisplaySettingsPanel.xaml.cs b/ILSpy/Options/DisplaySettingsPanel.xaml.cs index 6ad4d8a58..5ca096e7b 100644 --- a/ILSpy/Options/DisplaySettingsPanel.xaml.cs +++ b/ILSpy/Options/DisplaySettingsPanel.xaml.cs @@ -117,7 +117,7 @@ namespace ICSharpCode.ILSpy.Options section.SetAttributeValue("FontSize", s.SelectedFontSize); section.SetAttributeValue("ShowLineNumbers", s.ShowLineNumbers); section.SetAttributeValue("ShowMetadataTokens", s.ShowMetadataTokens); - section.SetAttributeValue("EnableWordWrap", s.EnableWordWrap); + section.SetAttributeValue("EnableWordWrap", s.EnableWordWrap); XElement existingElement = root.Element("DisplaySettings"); if (existingElement != null) diff --git a/ILSpy/Properties/WPFAssemblyInfo.cs b/ILSpy/Properties/WPFAssemblyInfo.cs index 8b337b962..a83408fca 100644 --- a/ILSpy/Properties/WPFAssemblyInfo.cs +++ b/ILSpy/Properties/WPFAssemblyInfo.cs @@ -7,7 +7,7 @@ using System.Windows; -//In order to begin building localizable applications, set +//In order to begin building localizable applications, set //CultureYouAreCodingWith in your .csproj file //inside a . For example, if you are using US english //in your source files, set the to en-US. Then uncomment @@ -18,10 +18,10 @@ using System.Windows; [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) + 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) )] diff --git a/ILSpy/TextView/DecompilerTextView.cs b/ILSpy/TextView/DecompilerTextView.cs index b99b752bf..e7a502094 100644 --- a/ILSpy/TextView/DecompilerTextView.cs +++ b/ILSpy/TextView/DecompilerTextView.cs @@ -97,9 +97,9 @@ namespace ICSharpCode.ILSpy.TextView textEditor.TextArea.TextView.MouseDown += TextViewMouseDown; textEditor.SetBinding(Control.FontFamilyProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("SelectedFont") }); textEditor.SetBinding(Control.FontSizeProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("SelectedFontSize") }); - textEditor.SetBinding(TextEditor.WordWrapProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("EnableWordWrap") }); + textEditor.SetBinding(TextEditor.WordWrapProperty, new Binding { Source = DisplaySettingsPanel.CurrentDisplaySettings, Path = new PropertyPath("EnableWordWrap") }); - textMarkerService = new TextMarkerService(textEditor.TextArea.TextView); + textMarkerService = new TextMarkerService(textEditor.TextArea.TextView); textEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService); textEditor.TextArea.TextView.LineTransformers.Add(textMarkerService); textEditor.ShowLineNumbers = true; diff --git a/ILSpy/TreeNodes/Analyzer/RemoveAnalyzeContextMenuEntry.cs b/ILSpy/TreeNodes/Analyzer/RemoveAnalyzeContextMenuEntry.cs index 55d4ff412..3bcbe782f 100644 --- a/ILSpy/TreeNodes/Analyzer/RemoveAnalyzeContextMenuEntry.cs +++ b/ILSpy/TreeNodes/Analyzer/RemoveAnalyzeContextMenuEntry.cs @@ -27,19 +27,19 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer { if (context.TreeView is AnalyzerTreeView && context.SelectedTreeNodes != null && context.SelectedTreeNodes.All(n => n.Parent.IsRoot)) return true; - return false; + return false; } public bool IsEnabled(TextViewContext context) { - return true; + return true; } public void Execute(TextViewContext context) { - if (context.SelectedTreeNodes != null) { + if (context.SelectedTreeNodes != null) { foreach (var node in context.SelectedTreeNodes) { - node.Parent.Children.Remove(node); + node.Parent.Children.Remove(node); } } } diff --git a/ILSpy/TreeNodes/AssemblyListTreeNode.cs b/ILSpy/TreeNodes/AssemblyListTreeNode.cs index d2bb70447..6225516cc 100644 --- a/ILSpy/TreeNodes/AssemblyListTreeNode.cs +++ b/ILSpy/TreeNodes/AssemblyListTreeNode.cs @@ -130,34 +130,34 @@ namespace ICSharpCode.ILSpy.TreeNodes } } - #region Find*Node + #region Find*Node - public ILSpyTreeNode FindResourceNode(Resource resource) - { - if (resource == null) - return null; - foreach (AssemblyTreeNode node in this.Children) - { - if (node.LoadedAssembly.IsLoaded) - { - node.EnsureLazyChildren(); - foreach (var item in node.Children.OfType()) - { - var founded = item.Children.OfType().Where(x => x.Resource == resource).FirstOrDefault(); - if (founded != null) - return founded; + public ILSpyTreeNode FindResourceNode(Resource resource) + { + if (resource == null) + return null; + foreach (AssemblyTreeNode node in this.Children) + { + if (node.LoadedAssembly.IsLoaded) + { + node.EnsureLazyChildren(); + foreach (var item in node.Children.OfType()) + { + var founded = item.Children.OfType().Where(x => x.Resource == resource).FirstOrDefault(); + if (founded != null) + return founded; - var foundedResEntry = item.Children.OfType().Where(x => resource.Name.Equals(x.Text)).FirstOrDefault(); - if (foundedResEntry != null) - return foundedResEntry; - } - } - } - return null; - } + var foundedResEntry = item.Children.OfType().Where(x => resource.Name.Equals(x.Text)).FirstOrDefault(); + if (foundedResEntry != null) + return foundedResEntry; + } + } + } + return null; + } - public AssemblyTreeNode FindAssemblyNode(ModuleDefinition module) + public AssemblyTreeNode FindAssemblyNode(ModuleDefinition module) { if (module == null) return null; diff --git a/appveyor.yml b/appveyor.yml index 2870d918a..4a1154b81 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -8,4 +8,6 @@ before_build: build: project: ILSpy.sln parallel: true - verbosity: minimal \ No newline at end of file + verbosity: minimal +after_test: +- python ICSharpCode.AvalonEdit.Tests\tidy.py From 6e47de16f8980c8f1ddd60e9d0a4b82839a53024 Mon Sep 17 00:00:00 2001 From: Daniel Grunwald Date: Sun, 27 Dec 2015 21:17:24 +0100 Subject: [PATCH 14/98] Delete in-tree AvalonEdit, NRefactory and Mono.Cecil in preparation for using git submodules. NRefactory.VB remains in the ILSpy repository. --- AvalonEdit/Documentation/Architecture.aml | 33 - AvalonEdit/Documentation/Code Completion.aml | 133 - .../Documentation/Coordinate Systems.aml | 175 - AvalonEdit/Documentation/Folding.aml | 58 - .../ICSharpCode.AvalonEdit.content | 11 - .../ICSharpCode.AvalonEdit.shfbproj | 182 - AvalonEdit/Documentation/License.html | 35 - .../Media/NamespaceDependencies.png | Bin 30932 -> 0 bytes .../Documentation/Media/RenderingPipeline.png | Bin 31718 -> 0 bytes AvalonEdit/Documentation/Media/VisualTree.png | Bin 10086 -> 0 bytes .../Documentation/Media/WelcomeScreenshot.png | Bin 86390 -> 0 bytes .../Documentation/Sample Application.aml | 78 - .../Documentation/Syntax Highlighting.aml | 234 - AvalonEdit/Documentation/Text Rendering.aml | 178 - AvalonEdit/Documentation/Welcome.aml | 70 - .../Document/ChangeTrackingTest.cs | 79 - .../Document/CollapsingTests.cs | 170 - .../Document/HeightTests.cs | 91 - .../Document/LineManagerTests.cs | 553 - .../Document/RandomizedLineManagerTest.cs | 183 - .../Document/TextAnchorTest.cs | 331 - .../Document/TextSegmentTreeTest.cs | 368 - .../Document/TextUtilitiesTests.cs | 94 - .../Document/UndoStackTests.cs | 92 - .../Editing/ChangeDocumentTests.cs | 78 - .../TextSegmentReadOnlySectionTests.cs | 183 - .../Highlighting/HighlightedLineMergeTests.cs | 182 - .../Highlighting/HtmlClipboardTests.cs | 56 - ...rpCode.AvalonEdit.Tests.PartCover.Settings | 3 - .../ICSharpCode.AvalonEdit.Tests.csproj | 126 - .../MultipleUIThreads.cs | 44 - .../Properties/AssemblyInfo.cs | 55 - .../Search/FindTests.cs | 132 - .../Utils/CaretNavigationTests.cs | 158 - .../Utils/CompressingTreeListTests.cs | 146 - .../Utils/ExtensionMethodsTests.cs | 51 - .../Utils/IndentationStringTests.cs | 51 - .../Utils/RopeTests.cs | 195 - .../WeakReferenceTests.cs | 127 - .../packages.config | 4 - .../AvalonEditCommands.cs | 102 - .../CodeCompletion/CompletionList.cs | 416 - .../CodeCompletion/CompletionList.xaml | 56 - .../CodeCompletion/CompletionListBox.cs | 111 - .../CodeCompletion/CompletionWindow.cs | 210 - .../CodeCompletion/CompletionWindowBase.cs | 397 - .../CodeCompletion/ICompletionData.cs | 73 - .../CodeCompletion/IOverloadProvider.cs | 57 - .../CodeCompletion/InsightWindow.cs | 109 - .../CodeCompletion/InsightWindow.xaml | 118 - .../CodeCompletion/OverloadInsightWindow.cs | 73 - .../CodeCompletion/OverloadViewer.cs | 116 - .../Document/DocumentChangeEventArgs.cs | 123 - .../Document/DocumentChangeOperation.cs | 67 - .../Document/DocumentLine.cs | 268 - .../Document/DocumentLineTree.cs | 727 - .../Document/DocumentTextWriter.cs | 86 - .../Document/GapTextBuffer.cs | 207 - .../Document/IDocument.cs | 343 - .../Document/ILineTracker.cs | 77 - .../Document/ITextAnchor.cs | 142 - .../Document/ITextSource.cs | 357 - .../Document/IUndoableOperation.cs | 45 - .../Document/LineManager.cs | 318 - .../Document/LineNode.cs | 98 - .../Document/NewLineFinder.cs | 150 - .../Document/OffsetChangeMap.cs | 364 - .../Document/RopeTextSource.cs | 169 - .../Document/SimpleSegment.cs | 197 - .../Document/TextAnchor.cs | 158 - .../Document/TextAnchorNode.cs | 102 - .../Document/TextAnchorTree.cs | 770 - .../Document/TextDocument.cs | 1153 -- .../Document/TextDocumentWeakEventManager.cs | 167 - .../Document/TextLocation.cs | 271 - .../Document/TextSegment.cs | 266 - .../Document/TextSegmentCollection.cs | 989 - .../Document/TextSourceVersionProvider.cs | 136 - .../Document/TextUtilities.cs | 422 - .../Document/UndoOperationGroup.cs | 76 - .../Document/UndoStack.cs | 458 - .../Document/WeakLineTracker.cs | 109 - .../Editing/AbstractMargin.cs | 117 - .../ICSharpCode.AvalonEdit/Editing/Caret.cs | 538 - .../Editing/CaretLayer.cs | 115 - .../Editing/CaretNavigationCommandHandler.cs | 392 - .../Editing/CaretWeakEventHandler.cs | 48 - .../Editing/DottedLineMargin.cs | 78 - .../Editing/DragDropException.cs | 61 - .../Editing/EditingCommandHandler.cs | 644 - .../Editing/EmptySelection.cs | 105 - .../Editing/IReadOnlySectionProvider.cs | 51 - .../Editing/ImeNativeWrapper.cs | 221 - .../Editing/ImeSupport.cs | 165 - .../Editing/LineNumberMargin.cs | 263 - .../Editing/NoReadOnlySections.cs | 66 - .../Editing/RectangleSelection.cs | 417 - .../Editing/Selection.cs | 302 - .../Editing/SelectionColorizer.cs | 74 - .../Editing/SelectionLayer.cs | 68 - .../Editing/SelectionMouseHandler.cs | 676 - .../Editing/SelectionSegment.cs | 108 - .../Editing/SimpleSelection.cs | 174 - .../Editing/TextArea.cs | 1138 -- .../Editing/TextAreaDefaultInputHandlers.cs | 135 - .../Editing/TextAreaInputHandler.cs | 257 - .../TextSegmentReadOnlySectionProvider.cs | 103 - .../Folding/FoldingElementGenerator.cs | 210 - .../Folding/FoldingManager.cs | 397 - .../Folding/FoldingMargin.cs | 350 - .../Folding/FoldingMarginMarker.cs | 103 - .../Folding/FoldingSection.cs | 203 - .../Folding/NewFolding.cs | 87 - .../Folding/XmlFoldingStrategy.cs | 240 - .../Highlighting/DocumentHighlighter.cs | 357 - .../Highlighting/HighlightedInlineBuilder.cs | 205 - .../Highlighting/HighlightedLine.cs | 335 - .../Highlighting/HighlightedSection.cs | 58 - .../Highlighting/HighlightingBrush.cs | 165 - .../Highlighting/HighlightingColor.cs | 309 - .../Highlighting/HighlightingColorizer.cs | 363 - .../HighlightingDefinitionInvalidException.cs | 58 - .../HighlightingDefinitionTypeConverter.cs | 69 - .../Highlighting/HighlightingEngine.cs | 325 - .../Highlighting/HighlightingManager.cs | 289 - .../Highlighting/HighlightingRule.cs | 46 - .../Highlighting/HighlightingRuleSet.cs | 61 - .../Highlighting/HighlightingSpan.cs | 79 - .../Highlighting/HtmlClipboard.cs | 112 - .../Highlighting/HtmlOptions.cs | 85 - .../Highlighting/HtmlRichTextWriter.cs | 268 - .../Highlighting/IHighlighter.cs | 126 - .../Highlighting/IHighlightingDefinition.cs | 63 - ...HighlightingDefinitionReferenceResolver.cs | 33 - .../Highlighting/Resources/ASPX.xshd | 16 - .../Highlighting/Resources/Boo.xshd | 212 - .../Highlighting/Resources/CPP-Mode.xshd | 195 - .../Highlighting/Resources/CSS-Mode.xshd | 56 - .../Highlighting/Resources/CSharp-Mode.xshd | 292 - .../Highlighting/Resources/Coco-Mode.xshd | 74 - .../Highlighting/Resources/HTML-Mode.xshd | 388 - .../Highlighting/Resources/Java-Mode.xshd | 152 - .../Resources/JavaScript-Mode.xshd | 132 - .../Highlighting/Resources/MarkDown-Mode.xshd | 56 - .../Highlighting/Resources/ModeV1.xsd | 296 - .../Highlighting/Resources/ModeV2.xsd | 168 - .../Highlighting/Resources/PHP-Mode.xshd | 158 - .../Highlighting/Resources/Patch-Mode.xshd | 35 - .../Highlighting/Resources/PowerShell.xshd | 146 - .../Highlighting/Resources/Resources.cs | 63 - .../Highlighting/Resources/Tex-Mode.xshd | 108 - .../Highlighting/Resources/VB-Mode.xshd | 256 - .../Highlighting/Resources/XML-Mode.xshd | 63 - .../Highlighting/Resources/XmlDoc.xshd | 57 - .../Highlighting/RichText.cs | 272 - .../Highlighting/RichTextColorizer.cs | 54 - .../Highlighting/RichTextModel.cs | 298 - .../Highlighting/RichTextModelWriter.cs | 128 - .../Highlighting/Xshd/HighlightingLoader.cs | 114 - .../Highlighting/Xshd/IXshdVisitor.cs | 46 - .../Highlighting/Xshd/SaveXshdVisitor.cs | 197 - .../Highlighting/Xshd/V1Loader.cs | 340 - .../Highlighting/Xshd/V2Loader.cs | 350 - .../Xshd/XmlHighlightingDefinition.cs | 422 - .../Highlighting/Xshd/XshdColor.cs | 126 - .../Highlighting/Xshd/XshdElement.cs | 44 - .../Highlighting/Xshd/XshdImport.cs | 40 - .../Highlighting/Xshd/XshdKeywords.cs | 51 - .../Highlighting/Xshd/XshdProperty.cs | 53 - .../Highlighting/Xshd/XshdReference.cs | 142 - .../Highlighting/Xshd/XshdRule.cs | 50 - .../Highlighting/Xshd/XshdRuleSet.cs | 66 - .../Highlighting/Xshd/XshdSpan.cs | 97 - .../Highlighting/Xshd/XshdSyntaxDefinition.cs | 65 - .../ICSharpCode.AvalonEdit.csproj | 457 - .../ICSharpCode.AvalonEdit.snk | Bin 596 -> 0 bytes .../CSharp/CSharpIndentationStrategy.cs | 95 - .../Indentation/CSharp/DocumentAccessor.cs | 122 - .../CSharp/IndentationReformatter.cs | 489 - .../Indentation/DefaultIndentationStrategy.cs | 55 - .../Indentation/IIndentationStrategy.cs | 40 - .../Properties/AssemblyInfo.cs | 71 - .../Properties/CodeAnalysisDictionary.xml | 33 - .../Rendering/BackgroundGeometryBuilder.cs | 358 - .../Rendering/CollapsedLineSection.cs | 110 - .../Rendering/ColorizingTransformer.cs | 123 - .../Rendering/ColumnRulerRenderer.cs | 79 - .../Rendering/CurrentLineHighlightRenderer.cs | 88 - .../DefaultTextRunTypographyProperties.cs | 186 - .../DocumentColorizingTransformer.cs | 98 - .../Rendering/FormattedTextElement.cs | 222 - .../Rendering/GlobalTextRunProperties.cs | 43 - .../Rendering/HeightTree.cs | 1111 -- .../Rendering/HeightTreeLineNode.cs | 64 - .../Rendering/HeightTreeNode.cs | 170 - .../Rendering/IBackgroundRenderer.cs | 41 - .../Rendering/ITextRunConstructionContext.cs | 62 - .../Rendering/ITextViewConnect.cs | 39 - .../Rendering/IVisualLineTransformer.cs | 34 - .../Rendering/InlineObjectRun.cs | 160 - .../ICSharpCode.AvalonEdit/Rendering/Layer.cs | 58 - .../Rendering/LayerPosition.cs | 106 - .../Rendering/LinkElementGenerator.cs | 159 - .../Rendering/MouseHoverLogic.cs | 149 - .../Rendering/SimpleTextSource.cs | 54 - .../SingleCharacterElementGenerator.cs | 283 - .../Rendering/TextLayer.cs | 85 - .../Rendering/TextView.cs | 2108 -- .../Rendering/TextViewCachedElements.cs | 58 - .../Rendering/TextViewWeakEventManager.cs | 86 - .../Rendering/VisualLine.cs | 772 - .../VisualLineConstructionStartEventArgs.cs | 44 - .../Rendering/VisualLineElement.cs | 264 - .../Rendering/VisualLineElementGenerator.cs | 78 - .../VisualLineElementTextRunProperties.cs | 256 - .../Rendering/VisualLineLinkText.cs | 130 - .../Rendering/VisualLineText.cs | 137 - .../VisualLineTextParagraphProperties.cs | 46 - .../Rendering/VisualLineTextSource.cs | 138 - .../Rendering/VisualLinesInvalidException.cs | 59 - .../Rendering/VisualYPosition.cs | 61 - .../Search/DropDownButton.cs | 89 - .../Search/DropDownButton.xaml | 71 - .../Search/ISearchStrategy.cs | 103 - .../Search/Localization.cs | 79 - .../Search/RegexSearchStrategy.cs | 85 - .../Search/SearchCommands.cs | 155 - .../Search/SearchPanel.cs | 528 - .../Search/SearchPanel.xaml | 47 - .../Search/SearchResultBackgroundRenderer.cs | 93 - .../Search/SearchStrategyFactory.cs | 83 - .../ICSharpCode.AvalonEdit/Search/next.png | Bin 1304 -> 0 bytes .../ICSharpCode.AvalonEdit/Search/prev.png | Bin 1300 -> 0 bytes .../Snippets/IActiveElement.cs | 50 - .../Snippets/InsertionContext.cs | 302 - .../Snippets/Snippet.cs | 59 - .../Snippets/SnippetAnchorElement.cs | 113 - .../Snippets/SnippetBoundElement.cs | 138 - .../Snippets/SnippetCaretElement.cs | 73 - .../Snippets/SnippetContainerElement.cs | 62 - .../Snippets/SnippetElement.cs | 43 - .../Snippets/SnippetEventArgs.cs | 72 - .../Snippets/SnippetInputHandler.cs | 93 - .../Snippets/SnippetReplaceableTextElement.cs | 227 - .../Snippets/SnippetSelectionElement.cs | 58 - .../Snippets/SnippetTextElement.cs | 53 - .../ICSharpCode.AvalonEdit/TextEditor.cs | 1182 -- .../ICSharpCode.AvalonEdit/TextEditor.xaml | 78 - .../TextEditorAutomationPeer.cs | 80 - .../TextEditorComponent.cs | 55 - .../TextEditorOptions.cs | 497 - .../TextEditorWeakEventManager.cs | 67 - .../TextViewPosition.cs | 199 - .../ICSharpCode.AvalonEdit/Utils/Boxes.cs | 36 - .../Utils/CallbackOnDispose.cs | 101 - .../ICSharpCode.AvalonEdit/Utils/CharRope.cs | 226 - .../Utils/CompressingTreeList.cs | 927 - .../ICSharpCode.AvalonEdit/Utils/Constants.cs | 30 - .../Utils/DelayedEvents.cs | 63 - .../ICSharpCode.AvalonEdit/Utils/Deque.cs | 189 - .../Utils/DocumentPrinter.cs | 122 - .../ICSharpCode.AvalonEdit/Utils/Empty.cs | 32 - .../Utils/ExtensionMethods.cs | 237 - .../Utils/FileReader.cs | 240 - .../Utils/IFreezable.cs | 123 - .../Utils/ImmutableStack.cs | 132 - .../Utils/NullSafeCollection.cs | 46 - .../Utils/ObserveAddRemoveCollection.cs | 89 - .../Utils/PixelSnapHelpers.cs | 107 - .../Utils/PlainRichTextWriter.cs | 140 - .../Utils/PropertyChangedWeakEventManager.cs | 41 - .../Utils/RichTextWriter.cs | 124 - .../ICSharpCode.AvalonEdit/Utils/Rope.cs | 854 - .../ICSharpCode.AvalonEdit/Utils/RopeNode.cs | 620 - .../Utils/RopeTextReader.cs | 120 - .../Utils/StringSegment.cs | 122 - .../Utils/TextFormatterFactory.cs | 143 - .../ICSharpCode.AvalonEdit/Utils/ThrowUtil.cs | 71 - .../Utils/WeakEventManagerBase.cs | 101 - .../ICSharpCode.AvalonEdit/Utils/Win32.cs | 100 - .../themes/RightArrow.cur | Bin 326 -> 0 bytes .../themes/generic.xaml | 15 - AvalonEdit/copyright.txt | 10 - AvalonEdit/license.txt | 458 - Mono.Cecil/.gitignore | 10 - Mono.Cecil/Mono.Cecil.Cil/Code.cs | 252 - Mono.Cecil/Mono.Cecil.Cil/CodeReader.cs | 598 - Mono.Cecil/Mono.Cecil.Cil/CodeWriter.cs | 649 - Mono.Cecil/Mono.Cecil.Cil/Document.cs | 112 - Mono.Cecil/Mono.Cecil.Cil/ExceptionHandler.cs | 89 - Mono.Cecil/Mono.Cecil.Cil/ILProcessor.cs | 278 - Mono.Cecil/Mono.Cecil.Cil/Instruction.cs | 321 - Mono.Cecil/Mono.Cecil.Cil/MethodBody.cs | 247 - Mono.Cecil/Mono.Cecil.Cil/OpCode.cs | 455 - Mono.Cecil/Mono.Cecil.Cil/OpCodes.cs | 912 - Mono.Cecil/Mono.Cecil.Cil/SequencePoint.cs | 70 - Mono.Cecil/Mono.Cecil.Cil/Symbols.cs | 277 - .../Mono.Cecil.Cil/VariableDefinition.cs | 52 - .../Mono.Cecil.Cil/VariableReference.cs | 75 - Mono.Cecil/Mono.Cecil.Metadata/BlobHeap.cs | 59 - Mono.Cecil/Mono.Cecil.Metadata/Buffers.cs | 373 - Mono.Cecil/Mono.Cecil.Metadata/CodedIndex.cs | 46 - Mono.Cecil/Mono.Cecil.Metadata/ElementType.cs | 73 - Mono.Cecil/Mono.Cecil.Metadata/GuidHeap.cs | 59 - Mono.Cecil/Mono.Cecil.Metadata/Heap.cs | 48 - .../Mono.Cecil.Metadata/MetadataToken.cs | 105 - Mono.Cecil/Mono.Cecil.Metadata/Row.cs | 170 - Mono.Cecil/Mono.Cecil.Metadata/StringHeap.cs | 81 - Mono.Cecil/Mono.Cecil.Metadata/TableHeap.cs | 111 - Mono.Cecil/Mono.Cecil.Metadata/TokenType.cs | 56 - .../Mono.Cecil.Metadata/UserStringHeap.cs | 59 - Mono.Cecil/Mono.Cecil.Metadata/Utilities.cs | 529 - .../Mono.Cecil.PE/BinaryStreamReader.cs | 51 - .../Mono.Cecil.PE/BinaryStreamWriter.cs | 96 - Mono.Cecil/Mono.Cecil.PE/ByteBuffer.cs | 359 - .../ByteBufferEqualityComparer.cs | 78 - Mono.Cecil/Mono.Cecil.PE/DataDirectory.cs | 50 - Mono.Cecil/Mono.Cecil.PE/Image.cs | 161 - Mono.Cecil/Mono.Cecil.PE/ImageReader.cs | 681 - Mono.Cecil/Mono.Cecil.PE/ImageWriter.cs | 824 - Mono.Cecil/Mono.Cecil.PE/Section.cs | 43 - Mono.Cecil/Mono.Cecil.PE/TextMap.cs | 129 - Mono.Cecil/Mono.Cecil.csproj | 264 - Mono.Cecil/Mono.Cecil.nunit | 9 - Mono.Cecil/Mono.Cecil.nuspec | 23 - Mono.Cecil/Mono.Cecil.sln | 197 - Mono.Cecil/Mono.Cecil/ArrayType.cs | 159 - Mono.Cecil/Mono.Cecil/AssemblyDefinition.cs | 189 - Mono.Cecil/Mono.Cecil/AssemblyFlags.cs | 42 - .../Mono.Cecil/AssemblyHashAlgorithm.cs | 36 - Mono.Cecil/Mono.Cecil/AssemblyInfo.cs | 49 - .../Mono.Cecil/AssemblyLinkedResource.cs | 57 - .../Mono.Cecil/AssemblyNameDefinition.cs | 50 - .../Mono.Cecil/AssemblyNameReference.cs | 270 - Mono.Cecil/Mono.Cecil/AssemblyReader.cs | 3166 --- Mono.Cecil/Mono.Cecil/AssemblyWriter.cs | 2571 --- Mono.Cecil/Mono.Cecil/BaseAssemblyResolver.cs | 363 - Mono.Cecil/Mono.Cecil/CallSite.cs | 124 - Mono.Cecil/Mono.Cecil/CustomAttribute.cs | 231 - .../Mono.Cecil/DefaultAssemblyResolver.cs | 70 - Mono.Cecil/Mono.Cecil/EmbeddedResource.cs | 105 - Mono.Cecil/Mono.Cecil/EventAttributes.cs | 39 - Mono.Cecil/Mono.Cecil/EventDefinition.cs | 170 - Mono.Cecil/Mono.Cecil/EventReference.cs | 57 - Mono.Cecil/Mono.Cecil/ExportedType.cs | 249 - Mono.Cecil/Mono.Cecil/FieldAttributes.cs | 59 - Mono.Cecil/Mono.Cecil/FieldDefinition.cs | 271 - Mono.Cecil/Mono.Cecil/FieldReference.cs | 83 - Mono.Cecil/Mono.Cecil/FileAttributes.cs | 35 - Mono.Cecil/Mono.Cecil/FunctionPointerType.cs | 128 - .../Mono.Cecil/GenericInstanceMethod.cs | 85 - Mono.Cecil/Mono.Cecil/GenericInstanceType.cs | 83 - Mono.Cecil/Mono.Cecil/GenericParameter.cs | 277 - .../Mono.Cecil/GenericParameterAttributes.cs | 45 - Mono.Cecil/Mono.Cecil/IConstantProvider.cs | 57 - .../Mono.Cecil/ICustomAttributeProvider.cs | 60 - Mono.Cecil/Mono.Cecil/IGenericInstance.cs | 66 - .../Mono.Cecil/IGenericParameterProvider.cs | 74 - Mono.Cecil/Mono.Cecil/IMarshalInfoProvider.cs | 56 - Mono.Cecil/Mono.Cecil/IMemberDefinition.cs | 100 - Mono.Cecil/Mono.Cecil/IMetadataScope.cs | 41 - .../Mono.Cecil/IMetadataTokenProvider.cs | 35 - Mono.Cecil/Mono.Cecil/IMethodSignature.cs | 75 - Mono.Cecil/Mono.Cecil/Import.cs | 566 - Mono.Cecil/Mono.Cecil/LinkedResource.cs | 60 - .../Mono.Cecil/ManifestResourceAttributes.cs | 39 - Mono.Cecil/Mono.Cecil/MarshalInfo.cs | 171 - .../Mono.Cecil/MemberDefinitionCollection.cs | 92 - Mono.Cecil/Mono.Cecil/MemberReference.cs | 101 - Mono.Cecil/Mono.Cecil/MetadataResolver.cs | 364 - Mono.Cecil/Mono.Cecil/MetadataSystem.cs | 395 - Mono.Cecil/Mono.Cecil/MethodAttributes.cs | 66 - .../Mono.Cecil/MethodCallingConvention.cs | 40 - Mono.Cecil/Mono.Cecil/MethodDefinition.cs | 495 - Mono.Cecil/Mono.Cecil/MethodImplAttributes.cs | 53 - Mono.Cecil/Mono.Cecil/MethodReference.cs | 214 - Mono.Cecil/Mono.Cecil/MethodReturnType.cs | 111 - .../Mono.Cecil/MethodSemanticsAttributes.cs | 43 - Mono.Cecil/Mono.Cecil/MethodSpecification.cs | 103 - Mono.Cecil/Mono.Cecil/Modifiers.cs | 137 - Mono.Cecil/Mono.Cecil/ModuleDefinition.cs | 1095 -- Mono.Cecil/Mono.Cecil/ModuleKind.cs | 64 - Mono.Cecil/Mono.Cecil/ModuleReference.cs | 67 - Mono.Cecil/Mono.Cecil/NativeType.cs | 73 - Mono.Cecil/Mono.Cecil/PInvokeAttributes.cs | 62 - Mono.Cecil/Mono.Cecil/PInvokeInfo.cs | 138 - Mono.Cecil/Mono.Cecil/ParameterAttributes.cs | 45 - Mono.Cecil/Mono.Cecil/ParameterDefinition.cs | 164 - .../ParameterDefinitionCollection.cs | 80 - Mono.Cecil/Mono.Cecil/ParameterReference.cs | 75 - Mono.Cecil/Mono.Cecil/PinnedType.cs | 53 - Mono.Cecil/Mono.Cecil/PointerType.cs | 61 - Mono.Cecil/Mono.Cecil/PropertyAttributes.cs | 41 - Mono.Cecil/Mono.Cecil/PropertyDefinition.cs | 259 - Mono.Cecil/Mono.Cecil/PropertyReference.cs | 59 - Mono.Cecil/Mono.Cecil/ReferenceType.cs | 61 - Mono.Cecil/Mono.Cecil/Resource.cs | 76 - Mono.Cecil/Mono.Cecil/SecurityDeclaration.cs | 192 - Mono.Cecil/Mono.Cecil/SentinelType.cs | 53 - Mono.Cecil/Mono.Cecil/TargetRuntime.cs | 37 - Mono.Cecil/Mono.Cecil/TypeAttributes.cs | 81 - Mono.Cecil/Mono.Cecil/TypeDefinition.cs | 518 - .../Mono.Cecil/TypeDefinitionCollection.cs | 118 - Mono.Cecil/Mono.Cecil/TypeParser.cs | 555 - Mono.Cecil/Mono.Cecil/TypeReference.cs | 330 - Mono.Cecil/Mono.Cecil/TypeSpecification.cs | 94 - Mono.Cecil/Mono.Cecil/TypeSystem.cs | 300 - Mono.Cecil/Mono.Cecil/VariantType.cs | 53 - .../Mono.Collections.Generic/Collection.cs | 420 - .../ReadOnlyCollection.cs | 112 - .../CryptoConvert.cs | 243 - .../CryptoService.cs | 177 - Mono.Cecil/Mono/Actions.cs | 38 - Mono.Cecil/Mono/Empty.cs | 53 - Mono.Cecil/Mono/Funcs.cs | 39 - Mono.Cecil/NOTES.txt | 189 - .../ExtensionAttribute.cs | 40 - Mono.Cecil/Test/.gitignore | 7 - Mono.Cecil/Test/Mono.Cecil.Tests.csproj | 179 - Mono.Cecil/Test/Mono.Cecil.Tests/Addin.cs | 305 - .../Test/Mono.Cecil.Tests/AssemblyInfo.cs | 14 - .../Test/Mono.Cecil.Tests/AssemblyTests.cs | 35 - .../Test/Mono.Cecil.Tests/BaseTestFixture.cs | 76 - .../Mono.Cecil.Tests/CompilationService.cs | 237 - .../Mono.Cecil.Tests/CustomAttributesTests.cs | 519 - .../Test/Mono.Cecil.Tests/EventTests.cs | 66 - .../Test/Mono.Cecil.Tests/Extensions.cs | 92 - .../Test/Mono.Cecil.Tests/FieldTests.cs | 333 - Mono.Cecil/Test/Mono.Cecil.Tests/Formatter.cs | 179 - .../Test/Mono.Cecil.Tests/ILProcessorTests.cs | 79 - .../Test/Mono.Cecil.Tests/ImageReadTests.cs | 144 - .../Test/Mono.Cecil.Tests/ImportCecilTests.cs | 310 - .../Mono.Cecil.Tests/ImportReflectionTests.cs | 409 - Mono.Cecil/Test/Mono.Cecil.Tests/Linq.cs | 47 - .../Test/Mono.Cecil.Tests/MethodBodyTests.cs | 412 - .../Test/Mono.Cecil.Tests/MethodTests.cs | 201 - .../Test/Mono.Cecil.Tests/ModuleTests.cs | 250 - .../Test/Mono.Cecil.Tests/NestedTypesTests.cs | 45 - .../Test/Mono.Cecil.Tests/ParameterTests.cs | 224 - .../Test/Mono.Cecil.Tests/PropertyTests.cs | 112 - .../Test/Mono.Cecil.Tests/ResolveTests.cs | 262 - .../SecurityDeclarationTests.cs | 290 - .../Test/Mono.Cecil.Tests/TypeParserTests.cs | 394 - Mono.Cecil/Test/Mono.Cecil.Tests/TypeTests.cs | 228 - .../Test/Mono.Cecil.Tests/VariableTests.cs | 108 - .../Test/Resources/assemblies/boxedoptarg.dll | Bin 3072 -> 0 bytes .../Test/Resources/assemblies/catch.exe | Bin 3584 -> 0 bytes .../Test/Resources/assemblies/cppcli.dll | Bin 50176 -> 0 bytes .../Test/Resources/assemblies/cscgpbug.dll | Bin 3584 -> 0 bytes .../Test/Resources/assemblies/decsec-att.dll | Bin 4096 -> 0 bytes .../Test/Resources/assemblies/decsec-xml.dll | Bin 5120 -> 0 bytes .../Test/Resources/assemblies/decsec1-xml.dll | Bin 4096 -> 0 bytes .../Resources/assemblies/delay-signed.dll | Bin 3584 -> 0 bytes .../Resources/assemblies/empty-decsec-att.dll | Bin 3584 -> 0 bytes Mono.Cecil/Test/Resources/assemblies/fptr.exe | Bin 2048 -> 0 bytes .../Test/Resources/assemblies/gifaceref.exe | Bin 5120 -> 0 bytes .../Resources/assemblies/hello.anycpu.exe | Bin 3584 -> 0 bytes .../Test/Resources/assemblies/hello.exe | Bin 3584 -> 0 bytes .../Test/Resources/assemblies/hello.ia64.exe | Bin 3072 -> 0 bytes .../Test/Resources/assemblies/hello.x64.exe | Bin 3072 -> 0 bytes .../Test/Resources/assemblies/hello.x86.exe | Bin 3584 -> 0 bytes .../Test/Resources/assemblies/hello1.exe | Bin 3072 -> 0 bytes .../Test/Resources/assemblies/hellow.exe | Bin 3584 -> 0 bytes .../Test/Resources/assemblies/iterator.exe | Bin 5632 -> 0 bytes .../Test/Resources/assemblies/libhello.dll | Bin 3072 -> 0 bytes .../Test/Resources/assemblies/libres.dll | Bin 3072 -> 0 bytes .../Test/Resources/assemblies/marshal.dll | Bin 3584 -> 0 bytes .../Test/Resources/assemblies/metro.exe | Bin 15872 -> 0 bytes Mono.Cecil/Test/Resources/assemblies/mma.exe | Bin 3584 -> 0 bytes .../Test/Resources/assemblies/moda.netmodule | Bin 2048 -> 0 bytes .../Test/Resources/assemblies/modb.netmodule | Bin 2048 -> 0 bytes .../Test/Resources/assemblies/noblob.dll | Bin 3072 -> 0 bytes .../Test/Resources/assemblies/pinvoke.exe | Bin 4096 -> 0 bytes .../Test/Resources/assemblies/switch.exe | Bin 3584 -> 0 bytes .../Test/Resources/assemblies/text_file.txt | 1 - .../Test/Resources/assemblies/varargs.exe | Bin 2048 -> 0 bytes Mono.Cecil/Test/Resources/assemblies/wp7.dll | Bin 10752 -> 0 bytes .../Test/Resources/cs/CustomAttributes.cs | 152 - Mono.Cecil/Test/Resources/cs/Events.cs | 8 - Mono.Cecil/Test/Resources/cs/Fields.cs | 41 - Mono.Cecil/Test/Resources/cs/Generics.cs | 121 - Mono.Cecil/Test/Resources/cs/Interfaces.cs | 22 - Mono.Cecil/Test/Resources/cs/Layouts.cs | 16 - Mono.Cecil/Test/Resources/cs/Methods.cs | 21 - Mono.Cecil/Test/Resources/cs/NestedTypes.cs | 16 - Mono.Cecil/Test/Resources/cs/Properties.cs | 18 - Mono.Cecil/Test/Resources/il/explicitthis.il | 113 - Mono.Cecil/Test/Resources/il/hello.il | 84 - Mono.Cecil/Test/Resources/il/methodspecs.il | 43 - Mono.Cecil/Test/Resources/il/others.il | 81 - Mono.Cecil/Test/Resources/il/types.il | 58 - Mono.Cecil/Test/libs/nunit-2.4.8/license.txt | 15 - .../Test/libs/nunit-2.5.10/nunit.core.dll | Bin 139264 -> 0 bytes .../nunit-2.5.10/nunit.core.interfaces.dll | Bin 57344 -> 0 bytes .../libs/nunit-2.5.10/nunit.framework.dll | Bin 139264 -> 0 bytes Mono.Cecil/dbg/Program.cs | 60 - Mono.Cecil/dbg/Properties/AssemblyInfo.cs | 36 - Mono.Cecil/dbg/dbg.csproj | 85 - Mono.Cecil/mono.snk | Bin 596 -> 0 bytes Mono.Cecil/rocks/.gitignore | 7 - Mono.Cecil/rocks/Mono.Cecil.Rocks.csproj | 129 - .../rocks/Mono.Cecil.Rocks/AssemblyInfo.cs | 41 - .../rocks/Mono.Cecil.Rocks/Functional.cs | 59 - Mono.Cecil/rocks/Mono.Cecil.Rocks/ILParser.cs | 236 - .../rocks/Mono.Cecil.Rocks/MethodBodyRocks.cs | 407 - .../Mono.Cecil.Rocks/MethodDefinitionRocks.cs | 88 - .../Mono.Cecil.Rocks/ModuleDefinitionRocks.cs | 50 - .../ParameterReferenceRocks.cs | 11 - .../SecurityDeclarationRocks.cs | 174 - .../Mono.Cecil.Rocks/TypeDefinitionRocks.cs | 83 - .../Mono.Cecil.Rocks/TypeReferenceRocks.cs | 107 - Mono.Cecil/rocks/Test/.gitignore | 7 - .../rocks/Test/Mono.Cecil.Rocks.Tests.csproj | 106 - .../rocks/Test/Mono.Cecil.Tests/Addin.cs | 8 - .../MethodDefinitionRocksTests.cs | 53 - .../ModuleDefinitionRocksTests.cs | 27 - .../SecurityDeclarationRocksTests.cs | 63 - .../TypeDefinitionRocksTests.cs | 97 - .../TypeReferenceRocksTests.cs | 124 - .../Test/Resources/assemblies/decsec-att.dll | Bin 4096 -> 0 bytes .../Test/Resources/assemblies/decsec-xml.dll | Bin 5120 -> 0 bytes Mono.Cecil/rocks/Test/Resources/cs/Types.cs | 14 - Mono.Cecil/symbols/mdb/.gitignore | 4 - Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb.csproj | 103 - .../mdb/Mono.Cecil.Mdb/AssemblyInfo.cs | 41 - .../symbols/mdb/Mono.Cecil.Mdb/MdbReader.cs | 213 - .../symbols/mdb/Mono.Cecil.Mdb/MdbWriter.cs | 251 - .../MonoSymbolFile.cs | 738 - .../MonoSymbolTable.cs | 1376 -- .../MonoSymbolWriter.cs | 403 - .../SymbolWriterImpl.cs | 349 - Mono.Cecil/symbols/mdb/Test/.gitignore | 4 - .../mdb/Test/Mono.Cecil.Mdb.Tests.csproj | 119 - .../mdb/Test/Mono.Cecil.Tests/Addin.cs | 8 - .../mdb/Test/Mono.Cecil.Tests/MdbTests.cs | 58 - .../mdb/Test/Resources/assemblies/hello.exe | Bin 3072 -> 0 bytes .../Test/Resources/assemblies/hello.exe.mdb | Bin 369 -> 0 bytes Mono.Cecil/symbols/pdb/.gitignore | 4 - .../pdb/Microsoft.Cci.Pdb/BitAccess.cs | 249 - .../symbols/pdb/Microsoft.Cci.Pdb/BitSet.cs | 74 - .../symbols/pdb/Microsoft.Cci.Pdb/CvInfo.cs | 2435 --- .../pdb/Microsoft.Cci.Pdb/DataStream.cs | 111 - .../pdb/Microsoft.Cci.Pdb/DbiDbgHdr.cs | 41 - .../pdb/Microsoft.Cci.Pdb/DbiHeader.cs | 59 - .../pdb/Microsoft.Cci.Pdb/DbiModuleInfo.cs | 57 - .../pdb/Microsoft.Cci.Pdb/DbiSecCon.cs | 42 - .../pdb/Microsoft.Cci.Pdb/IntHashTable.cs | 583 - .../pdb/Microsoft.Cci.Pdb/Interfaces.cs | 77 - .../symbols/pdb/Microsoft.Cci.Pdb/LICENSE | 22 - .../pdb/Microsoft.Cci.Pdb/MsfDirectory.cs | 58 - .../pdb/Microsoft.Cci.Pdb/PdbConstant.cs | 89 - .../Microsoft.Cci.Pdb/PdbDebugException.cs | 20 - .../pdb/Microsoft.Cci.Pdb/PdbException.cs | 20 - .../symbols/pdb/Microsoft.Cci.Pdb/PdbFile.cs | 439 - .../pdb/Microsoft.Cci.Pdb/PdbFileHeader.cs | 90 - .../pdb/Microsoft.Cci.Pdb/PdbFunction.cs | 452 - .../symbols/pdb/Microsoft.Cci.Pdb/PdbLine.cs | 29 - .../symbols/pdb/Microsoft.Cci.Pdb/PdbLines.cs | 23 - .../pdb/Microsoft.Cci.Pdb/PdbReader.cs | 40 - .../symbols/pdb/Microsoft.Cci.Pdb/PdbScope.cs | 122 - .../symbols/pdb/Microsoft.Cci.Pdb/PdbSlot.cs | 40 - .../pdb/Microsoft.Cci.Pdb/PdbSource.cs | 29 - .../SourceLocationProvider.cs | 33 - Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb.csproj | 130 - .../pdb/Mono.Cecil.Pdb/AssemblyInfo.cs | 41 - .../ISymUnmanagedDocumentWriter.cs | 41 - .../Mono.Cecil.Pdb/ISymUnmanagedWriter2.cs | 103 - .../pdb/Mono.Cecil.Pdb/ModuleMetadata.cs | 796 - .../symbols/pdb/Mono.Cecil.Pdb/PdbHelper.cs | 206 - .../symbols/pdb/Mono.Cecil.Pdb/PdbReader.cs | 278 - .../symbols/pdb/Mono.Cecil.Pdb/PdbWriter.cs | 222 - .../pdb/Mono.Cecil.Pdb/SymDocumentWriter.cs | 51 - .../symbols/pdb/Mono.Cecil.Pdb/SymWriter.cs | 170 - Mono.Cecil/symbols/pdb/Test/.gitignore | 4 - .../pdb/Test/Mono.Cecil.Pdb.Tests.csproj | 124 - .../pdb/Test/Mono.Cecil.Tests/Addin.cs | 8 - .../symbols/pdb/Test/Mono.Cecil.Tests/Linq.cs | 47 - .../pdb/Test/Mono.Cecil.Tests/PdbTests.cs | 175 - .../Test/Resources/assemblies/VBConsApp.exe | Bin 15360 -> 0 bytes .../Test/Resources/assemblies/VBConsApp.pdb | Bin 36352 -> 0 bytes .../pdb/Test/Resources/assemblies/fsapp.exe | Bin 5120 -> 0 bytes .../pdb/Test/Resources/assemblies/fsapp.pdb | Bin 11776 -> 0 bytes .../pdb/Test/Resources/assemblies/test.exe | Bin 4096 -> 0 bytes .../pdb/Test/Resources/assemblies/test.pdb | Bin 11776 -> 0 bytes .../AssemblyInfo.cs | 0 .../General/UnitTest.cs | 0 .../ICSharpCode.NRefactory.VB.Tests.csproj | 0 .../Lexer/CustomLexerTests.cs | 0 .../Lexer/ImplicitLineContinuationTests.cs | 0 .../Lexer/LATextReaderTests.cs | 0 .../Lexer/LexerContextTests.cs | 0 .../Lexer/LexerPositionTests.cs | 0 .../Lexer/LexerTests.cs | 0 .../Lexer/LiteralsTests.cs | 0 .../Lexer/TokenTests.cs | 0 .../Lexer/XmlModeLexerTests.cs | 0 .../CodeDOMParenthesizedExpressionTest.cs | 0 .../CodeDOM/CodeDOMPrimitiveExpressionTest.cs | 0 .../CodeDOM/CodeDOMTypeReferenceTest.cs | 0 .../CodeDOM/InvocationExpressionTest.cs | 0 .../Output/SpecialOutputVisitorTest.cs | 0 .../Output/VBNet/VBNetOutputTest.cs | 0 .../Expressions/AddressOfExpressionTests.cs | 0 .../Expressions/ArrayCreateExpressionTests.cs | 0 .../Expressions/AssignmentExpressionTests.cs | 0 .../BaseReferenceExpressionTests.cs | 0 .../BinaryOperatorExpressionTests.cs | 0 .../Parser/Expressions/CastExpressionTests.cs | 0 .../ClassReferenceExpressionTests.cs | 0 .../Expressions/ConditionalExpressionTests.cs | 0 .../GlobalReferenceExpressionTests.cs | 0 .../Expressions/IdentifierExpressionTests.cs | 0 .../Expressions/InvocationExpressionTests.cs | 0 .../Expressions/LambdaExpressionTests.cs | 0 .../MemberReferenceExpressionTests.cs | 0 .../ObjectCreateExpressionTests.cs | 0 .../ParenthesizedExpressionTest.cs | 0 .../Expressions/PrimitiveExpressionTests.cs | 0 .../Expressions/QueryExpressionTests.cs | 0 .../ThisReferenceExpressionTests.cs | 0 .../Expressions/TypeOfExpressionTests.cs | 0 .../Expressions/TypeOfIsExpressionTests.cs | 0 .../TypeReferenceExpressionTests.cs | 0 .../UnaryOperatorExpressionTests.cs | 0 .../Parser/Expressions/XmlExpressionTests.cs | 0 .../XmlMemberAccessExpressionTests.cs | 0 .../GlobalScope/AttributeSectionTests.cs | 0 .../GlobalScope/ImportsStatementTests.cs | 0 .../GlobalScope/NamespaceDeclarationTests.cs | 0 .../GlobalScope/OptionStatementTests.cs | 0 .../GlobalScope/TypeDeclarationTests.cs | 0 .../Parser/ParseUtil.cs | 0 .../Parser/SnippetParserTests.cs | 0 .../Statements/AddHandlerStatementTests.cs | 0 .../Parser/Statements/BlockStatementTests.cs | 0 .../Statements/ContinueStatementTests.cs | 0 .../Parser/Statements/DoLoopStatementTests.cs | 0 .../Parser/Statements/EndStatementTests.cs | 0 .../Parser/Statements/EraseStatementTests.cs | 0 .../Parser/Statements/ErrorStatementTests.cs | 0 .../Statements/ExpressionStatementTests.cs | 0 .../Statements/ForNextStatementTests.cs | 0 .../Statements/ForeachStatementTests.cs | 0 .../Parser/Statements/GotoStatementTests.cs | 0 .../Parser/Statements/IfElseStatementTests.cs | 0 .../Parser/Statements/LabelStatementTests.cs | 0 .../LocalVariableDeclarationTests.cs | 0 .../Parser/Statements/LockStatementTests.cs | 0 .../Parser/Statements/OnErrorStatementTest.cs | 0 .../Statements/RaiseEventStatementTest.cs | 0 .../Parser/Statements/ReDimStatementTests.cs | 0 .../Statements/RemoveHandlerStatement.cs | 0 .../Parser/Statements/ResumeStatement.cs | 0 .../Parser/Statements/ReturnStatementTests.cs | 0 .../Parser/Statements/StopStatementTests.cs | 0 .../Parser/Statements/SwitchStatementTests.cs | 0 .../Parser/Statements/ThrowStatementTests.cs | 0 .../Statements/TryCatchStatementTests.cs | 0 .../Parser/Statements/UsingStatementTests.cs | 0 .../Parser/Statements/WithStatementTests.cs | 0 .../TypeLevel/ConstructorDeclarationTests.cs | 0 .../Parser/TypeLevel/CustomEventTests.cs | 0 .../TypeLevel/DeclareDeclarationTests.cs | 0 .../Parser/TypeLevel/EventDeclarationTests.cs | 0 .../Parser/TypeLevel/FieldDeclarationTests.cs | 0 .../TypeLevel/MethodDeclarationTests.cs | 0 .../TypeLevel/OperatorDeclarationTests.cs | 0 .../TypeLevel/PropertyDeclarationTests.cs | 0 .../ICSharpCode.NRefactory.VB/Ast/AstNode.cs | 0 .../Ast/AstNodeCollection.cs | 0 .../ICSharpCode.NRefactory.VB/Ast/Comment.cs | 0 .../ICSharpCode.NRefactory.VB/Ast/Enums.cs | 0 .../AnonymousObjectCreationExpression.cs | 0 .../Ast/Expressions/ArrayCreateExpression.cs | 0 .../Expressions/ArrayInitializerExpression.cs | 0 .../Ast/Expressions/AssignmentExpression.cs | 0 .../Expressions/BinaryOperatorExpression.cs | 0 .../Ast/Expressions/CastExpression.cs | 0 .../CollectionRangeVariableDeclaration.cs | 0 .../Ast/Expressions/ConditionalExpression.cs | 0 .../Ast/Expressions/EmptyExpression.cs | 0 .../Ast/Expressions/Expression.cs | 0 .../Expressions/FieldInitializerExpression.cs | 0 .../Ast/Expressions/GetTypeExpression.cs | 0 .../Expressions/GetXmlNamespaceExpression.cs | 0 .../Ast/Expressions/IdentifierExpression.cs | 0 .../Ast/Expressions/InstanceExpression.cs | 0 .../Ast/Expressions/InvocationExpression.cs | 0 .../Ast/Expressions/LambdaExpression.cs | 0 .../Ast/Expressions/MemberAccessExpression.cs | 0 .../Expressions/NamedArgumentExpression.cs | 0 .../Expressions/ObjectCreationExpression.cs | 0 .../Expressions/ParenthesizedExpression.cs | 0 .../Ast/Expressions/PrimitiveExpression.cs | 0 .../Ast/Expressions/QueryExpression.cs | 0 .../Ast/Expressions/SimpleNameExpression.cs | 0 .../Ast/Expressions/TypeOfIsExpression.cs | 0 .../Expressions/TypeReferenceExpression.cs | 0 .../Expressions/UnaryOperatorExpression.cs | 0 .../Ast/Expressions/VariableInitializer.cs | 0 .../Ast/Expressions/XmlIdentifier.cs | 0 .../Ast/Expressions/XmlLiteralString.cs | 0 .../Ast/General/Attribute.cs | 0 .../Ast/General/AttributeBlock.cs | 0 .../Ast/General/AttributedNode.cs | 0 .../Ast/General/CompilationUnit.cs | 0 .../Ast/General/EventMemberSpecifier.cs | 0 .../Ast/General/InterfaceMemberSpecifier.cs | 0 .../Ast/General/ParameterDeclaration.cs | 0 .../Ast/General/TypeParameterDeclaration.cs | 0 .../Ast/Generated.cs | 0 .../Ast/GlobalScope/DelegateDeclaration.cs | 0 .../Ast/GlobalScope/EnumDeclaration.cs | 0 .../Ast/GlobalScope/EnumMemberDeclaration.cs | 0 .../Ast/GlobalScope/ImportsClause.cs | 0 .../Ast/GlobalScope/ImportsStatement.cs | 0 .../Ast/GlobalScope/NamespaceDeclaration.cs | 0 .../Ast/GlobalScope/OptionStatement.cs | 0 .../Ast/GlobalScope/TypeDeclaration.cs | 0 .../Ast/INullable.cs | 0 .../Ast/Identifier.cs | 0 .../Statements/AddRemoveHandlerStatement.cs | 0 .../Ast/Statements/BlockStatement.cs | 0 .../Ast/Statements/ContinueStatement.cs | 0 .../Ast/Statements/DoLoopStatement.cs | 0 .../Ast/Statements/ExitStatement.cs | 0 .../Ast/Statements/ExpressionStatement.cs | 0 .../Ast/Statements/ForEachStatement.cs | 0 .../Ast/Statements/ForStatement.cs | 0 .../Ast/Statements/GoToStatement.cs | 0 .../Ast/Statements/IfElseStatement.cs | 0 .../Statements/LabelDeclarationStatement.cs | 0 .../Statements/LocalDeclarationStatement.cs | 0 .../Ast/Statements/ReturnStatement.cs | 0 .../Ast/Statements/SelectStatement.cs | 0 .../Ast/Statements/Statement.cs | 0 .../Ast/Statements/SyncLockStatement.cs | 0 .../Ast/Statements/ThrowStatement.cs | 0 .../Ast/Statements/TryStatement.cs | 0 .../Ast/Statements/UsingStatement.cs | 0 .../Ast/Statements/WhileStatement.cs | 0 .../Ast/Statements/WithStatement.cs | 0 .../Ast/Statements/YieldStatement.cs | 0 .../Ast/TypeMembers/Accessor.cs | 0 .../Ast/TypeMembers/ConstructorDeclaration.cs | 0 .../Ast/TypeMembers/EventDeclaration.cs | 0 .../TypeMembers/ExternalMethodDeclaration.cs | 0 .../Ast/TypeMembers/FieldDeclaration.cs | 0 .../Ast/TypeMembers/MethodDeclaration.cs | 0 .../Ast/TypeMembers/OperatorDeclaration.cs | 0 .../Ast/TypeMembers/PropertyDeclaration.cs | 0 .../Ast/TypeMembers/VariableDeclarator.cs | 0 .../Ast/TypeName/AstType.cs | 0 .../Ast/TypeName/ComposedType.cs | 0 .../Ast/TypeName/PrimitiveType.cs | 0 .../Ast/TypeName/QualifiedType.cs | 0 .../Ast/TypeName/SimpleType.cs | 0 .../Ast/VBModifierToken.cs | 0 .../Ast/VBTokenNode.cs | 0 .../ICSharpCode.NRefactory.VB/IAstVisitor.cs | 0 .../ICSharpCode.NRefactory.VB.csproj | 0 .../ICSharpCode.NRefactory.VB/Lexer/Block.cs | 0 .../Lexer/ExpressionFinder.atg | 0 .../Lexer/ExpressionFinder.cs | 0 .../Lexer/ExpressionFinderState.cs | 0 .../Lexer/Extensions.cs | 0 .../Lexer/KeywordList.txt | 0 .../Lexer/Keywords.cs | 0 .../Lexer/LATextReader.cs | 0 .../Lexer/LookupTable.cs | 0 .../ICSharpCode.NRefactory.VB/Lexer/Parser.cs | 0 .../Lexer/PushParser.frame | 0 .../Lexer/SavepointEventArgs.cs | 0 .../Lexer/Special/BlankLine.cs | 0 .../Lexer/Special/Comment.cs | 0 .../Lexer/Special/CommentType.cs | 0 .../Lexer/Special/ISpecial.cs | 0 .../Lexer/Special/PreProcessingDirective.cs | 0 .../Lexer/Special/SpecialTracker.cs | 0 .../Lexer/Special/TagComment.cs | 0 .../ICSharpCode.NRefactory.VB/Lexer/Token.cs | 0 .../ICSharpCode.NRefactory.VB/Lexer/Tokens.cs | 0 .../Lexer/VBLexer.cs | 0 .../Lexer/VBLexerMemento.cs | 0 .../Lexer/XmlModeInfo.cs | 0 .../OutputVisitor/IOutputFormatter.cs | 0 .../OutputVisitor/OutputVisitor.cs | 0 .../TextWriterOutputFormatter.cs | 0 .../OutputVisitor/VBFormattingOptions.cs | 0 .../Parser/Errors.cs | 0 .../Parser/Parser.cs | 0 .../Parser/Parser.frame | 0 .../Parser/VBParser.cs | 0 .../ICSharpCode.NRefactory.VB/Parser/vb.atg | 0 .../PrettyPrinter/AbstractOutputFormatter.cs | 0 .../AbstractPrettyPrintOptions.cs | 0 .../PrettyPrinter/IOutputAstVisitor.cs | 0 .../PrettyPrinter/SpecialNodesInserter.cs | 0 .../VBNet/VBNetOutputFormatter.cs | 0 .../PrettyPrinter/VBNet/VBNetOutputVisitor.cs | 0 .../VBNet/VBNetPrettyPrintOptions.cs | 0 .../Properties/AssemblyInfo.cs | 0 .../ICSharpCode.NRefactory.VB/VBParser.cs | 0 .../Visitors/CSharpToVBConverterVisitor.cs | 0 NRefactory/.gitattributes | 3 - NRefactory/.gitignore | 6 - .../Analysis/AnnotationNames.cs | 48 - .../Analysis/ControlFlow.cs | 803 - .../DeclarationSpace/LocalDeclarationSpace.cs | 157 - .../LocalDeclarationSpaceVisitor.cs | 138 - .../Analysis/DefiniteAssignmentAnalysis.cs | 759 - .../Analysis/NullValueAnalysis.cs | 2215 --- .../Analysis/NullValueStatus.cs | 84 - .../Analysis/ReachabilityAnalysis.cs | 209 - .../Analysis/SemanticHighlightingVisitor.cs | 685 - .../Ast/AstNode.cs | 1042 - .../Ast/AstNodeCollection.cs | 231 - .../Ast/AstType.cs | 280 - .../Ast/CSharpModifierToken.cs | 218 - .../Ast/CSharpTokenNode.cs | 131 - .../Ast/CSharpUtil.cs | 180 - .../Ast/ComposedType.cs | 230 - .../Ast/DepthFirstAstVisitor.cs | 1849 -- .../Ast/DocumentationReference.cs | 149 - .../Ast/ErrorNode.cs | 88 - .../Expressions/AnonymousMethodExpression.cs | 117 - .../AnonymousTypeCreateExpression.cs | 91 - .../Ast/Expressions/ArrayCreateExpression.cs | 80 - .../Expressions/ArrayInitializerExpression.cs | 192 - .../Ast/Expressions/AsExpression.cs | 150 - .../Ast/Expressions/AssignmentExpression.cs | 304 - .../Expressions/BaseReferenceExpression.cs | 71 - .../Expressions/BinaryOperatorExpression.cs | 325 - .../Ast/Expressions/CastExpression.cs | 152 - .../Ast/Expressions/CheckedExpression.cs | 83 - .../Ast/Expressions/ConditionalExpression.cs | 162 - .../Ast/Expressions/DefaultValueExpression.cs | 84 - .../Ast/Expressions/DirectionExpression.cs | 89 - .../Ast/Expressions/ErrorExpression.cs | 129 - .../Ast/Expressions/Expression.cs | 230 - .../Ast/Expressions/IdentifierExpression.cs | 93 - .../Ast/Expressions/IndexerExpression.cs | 92 - .../Ast/Expressions/InvocationExpression.cs | 92 - .../Ast/Expressions/IsExpression.cs | 150 - .../Ast/Expressions/LambdaExpression.cs | 89 - .../Expressions/MemberReferenceExpression.cs | 119 - .../Expressions/NamedArgumentExpression.cs | 87 - .../Ast/Expressions/NamedExpression.cs | 97 - .../Expressions/NullReferenceExpression.cs | 83 - .../Ast/Expressions/ObjectCreateExpression.cs | 104 - .../Expressions/ParenthesizedExpression.cs | 98 - .../Expressions/PointerReferenceExpression.cs | 90 - .../Ast/Expressions/PrimitiveExpression.cs | 162 - .../Ast/Expressions/QueryExpression.cs | 655 - .../Ast/Expressions/SizeOfExpression.cs | 83 - .../Ast/Expressions/StackAllocExpression.cs | 79 - .../Expressions/ThisReferenceExpression.cs | 71 - .../Ast/Expressions/TypeOfExpression.cs | 84 - .../Expressions/TypeReferenceExpression.cs | 64 - .../Expressions/UnaryOperatorExpression.cs | 181 - .../Ast/Expressions/UncheckedExpression.cs | 83 - .../Ast/Expressions/UndocumentedExpression.cs | 105 - .../Ast/GeneralScope/Attribute.cs | 93 - .../Ast/GeneralScope/AttributeSection.cs | 174 - .../Ast/GeneralScope/Comment.cs | 140 - .../Ast/GeneralScope/Constraint.cs | 85 - .../Ast/GeneralScope/DelegateDeclaration.cs | 92 - .../GeneralScope/ExternAliasDeclaration.cs | 91 - .../Ast/GeneralScope/NamespaceDeclaration.cs | 158 - .../Ast/GeneralScope/NewLineNode.cs | 91 - .../Ast/GeneralScope/PreProcessorDirective.cs | 205 - .../Ast/GeneralScope/TextNode.cs | 94 - .../Ast/GeneralScope/TypeDeclaration.cs | 145 - .../GeneralScope/TypeParameterDeclaration.cs | 113 - .../Ast/GeneralScope/UsingAliasDeclaration.cs | 107 - .../Ast/GeneralScope/UsingDeclaration.cs | 122 - .../Ast/GeneralScope/WhitespaceNode.cs | 91 - .../Ast/IAstVisitor.cs | 418 - .../Ast/Identifier.cs | 173 - .../Ast/IdentifierExpressionBackreference.cs | 54 - .../Ast/MemberType.cs | 150 - .../Ast/Modifiers.cs | 65 - .../Ast/NodeType.cs | 56 - .../Ast/ObservableAstVisitor.cs | 857 - .../Ast/PrimitiveType.cs | 163 - .../Ast/Roles.cs | 96 - .../Ast/SimpleType.cs | 169 - .../Ast/Statements/BlockStatement.cs | 164 - .../Ast/Statements/BreakStatement.cs | 65 - .../Ast/Statements/CheckedStatement.cs | 75 - .../Ast/Statements/ContinueStatement.cs | 65 - .../Ast/Statements/DoWhileStatement.cs | 99 - .../Ast/Statements/EmptyStatement.cs | 72 - .../Ast/Statements/ExpressionStatement.cs | 73 - .../Ast/Statements/FixedStatement.cs | 85 - .../Ast/Statements/ForStatement.cs | 97 - .../Ast/Statements/ForeachStatement.cs | 108 - .../Ast/Statements/GotoStatement.cs | 178 - .../Ast/Statements/IfElseStatement.cs | 103 - .../Ast/Statements/LabelStatement.cs | 73 - .../Ast/Statements/LockStatement.cs | 79 - .../Ast/Statements/ReturnStatement.cs | 79 - .../Ast/Statements/Statement.cs | 132 - .../Ast/Statements/SwitchStatement.cs | 230 - .../Ast/Statements/ThrowStatement.cs | 79 - .../Ast/Statements/TryCatchStatement.cs | 241 - .../Ast/Statements/UncheckedStatement.cs | 75 - .../Ast/Statements/UnsafeStatement.cs | 66 - .../Ast/Statements/UsingStatement.cs | 83 - .../VariableDeclarationStatement.cs | 90 - .../Ast/Statements/WhileStatement.cs | 89 - .../Ast/Statements/YieldBreakStatement.cs | 70 - .../Ast/Statements/YieldReturnStatement.cs | 75 - .../Ast/SyntaxExtensions.cs | 45 - .../Ast/SyntaxTree.cs | 193 - .../Ast/TokenRole.cs | 61 - .../Ast/TypeMembers/Accessor.cs | 117 - .../Ast/TypeMembers/ConstructorDeclaration.cs | 190 - .../Ast/TypeMembers/DestructorDeclaration.cs | 76 - .../Ast/TypeMembers/EntityDeclaration.cs | 117 - .../Ast/TypeMembers/EnumMemberDeclaration.cs | 72 - .../Ast/TypeMembers/EventDeclaration.cs | 152 - .../Ast/TypeMembers/FieldDeclaration.cs | 79 - .../Ast/TypeMembers/FixedFieldDeclaration.cs | 71 - .../TypeMembers/FixedVariableInitializer.cs | 105 - .../Ast/TypeMembers/IndexerDeclaration.cs | 122 - .../Ast/TypeMembers/MethodDeclaration.cs | 104 - .../Ast/TypeMembers/OperatorDeclaration.cs | 268 - .../Ast/TypeMembers/ParameterDeclaration.cs | 147 - .../Ast/TypeMembers/PropertyDeclaration.cs | 92 - .../Ast/TypeMembers/VariableInitializer.cs | 174 - .../CSharpProjectContent.cs | 289 - .../CombineQueryExpressions.cs | 216 - .../Completion/CSharpCompletionEngine.cs | 3807 ---- .../Completion/CSharpCompletionEngineBase.cs | 907 - .../CSharpParameterCompletionEngine.cs | 408 - .../Completion/CompletionDataWrapper.cs | 328 - .../Completion/ICompletionContextProvider.cs | 214 - .../Completion/ICompletionDataFactory.cs | 89 - .../IParameterCompletionDataFactory.cs | 54 - .../Formatter/CSharpFormatter.cs | 159 - .../Formatter/CSharpFormattingOptions.cs | 1039 - .../Formatter/ConstructFixer.cs | 514 - .../Formatter/FormattingChanges.cs | 169 - .../Formatter/FormattingOptionsFactory.cs | 446 - .../Formatter/FormattingVisitor.cs | 662 - .../FormattingVisitor_Expressions.cs | 735 - .../Formatter/FormattingVisitor_Global.cs | 351 - .../Formatter/FormattingVisitor_Query.cs | 124 - .../Formatter/FormattingVisitor_Statements.cs | 517 - .../FormattingVisitor_TypeMembers.cs | 477 - .../Formatter/GeneratedCodeSettings.cs | 216 - .../Formatter/Indent.cs | 246 - .../Formatter/TextEditorOptions.cs | 116 - .../ICSharpCode.NRefactory.CSharp.csproj | 420 - .../IndentEngine/CSharpIndentEngine.cs | 557 - .../IndentEngine/CacheIndentEngine.cs | 627 - .../IndentEngine/IDocumentIndentEngine.cs | 108 - .../IndentEngine/IStateMachineIndentEngine.cs | 60 - .../IndentEngine/IndentState.cs | 2017 -- .../NullIStateMachineIndentEngine.cs | 215 - .../IndentEngine/TextPasteIndentEngine.cs | 632 - .../IntroduceQueryExpressions.cs | 386 - .../NameLookupMode.cs | 47 - .../OutputVisitor/CSharpAmbience.cs | 312 - .../OutputVisitor/CSharpOutputVisitor.cs | 2401 --- .../OutputVisitor/CodeDomConvertVisitor.cs | 1429 -- .../OutputVisitor/ITokenWriter.cs | 161 - .../InsertMissingTokensDecorator.cs | 123 - .../OutputVisitor/InsertParenthesesVisitor.cs | 345 - .../InsertRequiredSpacesDecorator.cs | 184 - .../OutputVisitor/InsertSpecialsDecorator.cs | 157 - .../TextWriterOutputFormatter.cs | 419 - .../Parser/CSharpParser.cs | 4096 ---- .../Parser/CompilerSettings.cs | 151 - .../Parser/SeekableStreamReader.cs | 103 - .../Parser/mcs/CryptoConvert.cs | 754 - .../Parser/mcs/MonoSymbolFile.cs | 637 - .../Parser/mcs/MonoSymbolTable.cs | 1437 -- .../Parser/mcs/MonoSymbolWriter.cs | 238 - .../Parser/mcs/SourceMethodBuilder.cs | 190 - .../Parser/mcs/anonymous.cs | 2292 --- .../Parser/mcs/argument.cs | 674 - .../Parser/mcs/assembly.cs | 1257 -- .../Parser/mcs/assign.cs | 956 - .../Parser/mcs/async.cs | 1005 - .../Parser/mcs/attribute.cs | 2140 -- .../Parser/mcs/cfold.cs | 1192 -- .../Parser/mcs/class.cs | 3895 ---- .../Parser/mcs/codegen.cs | 1365 -- .../Parser/mcs/complete.cs | 226 - .../Parser/mcs/const.cs | 237 - .../Parser/mcs/constant.cs | 2496 --- .../Parser/mcs/context.cs | 751 - .../Parser/mcs/convert.cs | 2266 --- .../Parser/mcs/cs-parser.cs | 16238 ---------------- .../Parser/mcs/cs-parser.jay | 8195 -------- .../Parser/mcs/cs-tokenizer.cs | 4033 ---- .../Parser/mcs/decl.cs | 1297 -- .../Parser/mcs/delegate.cs | 952 - .../Parser/mcs/doc.cs | 755 - .../Parser/mcs/driver.cs | 475 - .../Parser/mcs/dynamic.cs | 986 - .../Parser/mcs/ecore.cs | 7426 ------- .../Parser/mcs/enum.cs | 339 - .../Parser/mcs/eval.cs | 1333 -- .../Parser/mcs/expression.cs | 11921 ------------ .../Parser/mcs/field.cs | 733 - .../Parser/mcs/flowanalysis.cs | 685 - .../Parser/mcs/generic.cs | 3660 ---- .../Parser/mcs/import.cs | 2352 --- .../Parser/mcs/iterators.cs | 1260 -- .../Parser/mcs/lambda.cs | 229 - .../Parser/mcs/linq.cs | 904 - .../Parser/mcs/literal.cs | 333 - .../Parser/mcs/location.cs | 883 - .../Parser/mcs/membercache.cs | 1501 -- .../Parser/mcs/method.cs | 2890 --- .../Parser/mcs/modifiers.cs | 282 - .../Parser/mcs/module.cs | 713 - .../Parser/mcs/namespace.cs | 1584 -- .../Parser/mcs/nullable.cs | 1380 -- .../Parser/mcs/outline.cs | 1038 - .../Parser/mcs/parameter.cs | 1472 -- .../Parser/mcs/pending.cs | 734 - .../Parser/mcs/property.cs | 1807 -- .../Parser/mcs/reflection.cs | 550 - .../Parser/mcs/report.cs | 1144 -- .../Parser/mcs/settings.cs | 1601 -- .../Parser/mcs/statement.cs | 8074 -------- .../Parser/mcs/support.cs | 364 - .../Parser/mcs/symbolwriter.cs | 234 - .../Parser/mcs/typemanager.cs | 1143 -- .../Parser/mcs/typespec.cs | 2021 -- .../Parser/mcs/visit.cs | 618 - .../PatternMatching/AnyType.cs | 37 - .../Properties/AssemblyInfo.cs | 33 - .../QueryExpressionExpander.cs | 430 - .../Refactoring/BaseRefactoringContext.cs | 319 - .../Refactoring/CodeAction.cs | 197 - .../Refactoring/CodeActionProvider.cs | 37 - ...veFieldRefactoryActionRefactoringAction.cs | 110 - .../Refactoring/CodeGenerationService.cs | 64 - .../Refactoring/CodeIssue.cs | 181 - .../Refactoring/CodeIssueProvider.cs | 76 - .../CodeIssues/Uncategorized/.DS_Store | Bin 6148 -> 0 bytes .../Refactoring/CommonSubIssues.cs | 37 - .../Refactoring/ContextActionAttribute.cs | 43 - .../Refactoring/DocumentScript.cs | 179 - .../Refactoring/FormatStringHelper.cs | 86 - .../Refactoring/IssueAttribute.cs | 91 - .../Refactoring/LambdaHelper.cs | 51 - .../Refactoring/LocalReferenceFinder.cs | 159 - .../Refactoring/NamingHelper.cs | 242 - .../Refactoring/PatternHelper.cs | 172 - .../Refactoring/RefactoringAstHelper.cs | 49 - .../Refactoring/RefactoringContext.cs | 108 - .../Refactoring/Script.cs | 651 - .../Refactoring/TypeGuessing.cs | 349 - .../Refactoring/TypeSystemAstBuilder.cs | 981 - .../Refactoring/UsingHelper.cs | 201 - .../Refactoring/VariableReferenceGraph.cs | 575 - .../Refactoring/WordParser.cs | 70 - .../Resolver/AliasNamespaceResolveResult.cs | 52 - .../Resolver/AliasTypeResolveResult.cs | 52 - .../Resolver/AwaitResolveResult.cs | 81 - .../Resolver/CSharpAstResolver.cs | 281 - .../Resolver/CSharpConversions.cs | 1248 -- .../Resolver/CSharpInvocationResolveResult.cs | 145 - .../Resolver/CSharpOperators.cs | 1059 - .../Resolver/CSharpResolver.cs | 2619 --- .../Resolver/CastResolveResult.cs | 63 - .../CompositeResolveVisitorNavigator.cs | 67 - .../Resolver/DetectSkippableNodesNavigator.cs | 88 - .../DynamicInvocationResolveResult.cs | 86 - .../Resolver/DynamicMemberResolveResult.cs | 57 - .../Resolver/FindReferenceSearchScope.cs | 63 - .../Resolver/FindReferencedEntities.cs | 100 - .../Resolver/FindReferences.cs | 1611 -- .../Resolver/IResolveVisitorNavigator.cs | 103 - .../Resolver/LambdaResolveResult.cs | 101 - .../Resolver/Log.cs | 94 - .../Resolver/MemberLookup.cs | 696 - .../Resolver/MethodGroupResolveResult.cs | 292 - .../NodeListResolveVisitorNavigator.cs | 76 - .../Resolver/OverloadResolution.cs | 960 - .../Resolver/OverloadResolutionErrors.cs | 87 - .../Resolver/ReducedExtensionMethod.cs | 455 - .../Resolver/RenameCallbackArguments.cs | 41 - .../Resolver/ResolveAtLocation.cs | 124 - .../Resolver/ResolveVisitor.cs | 4103 ---- .../Resolver/TypeInference.cs | 978 - .../TypeSystem/AliasNamespaceReference.cs | 76 - .../TypeSystem/AttributeTypeReference.cs | 91 - .../TypeSystem/CSharpAssembly.cs | 338 - .../TypeSystem/CSharpAttribute.cs | 169 - .../TypeSystem/CSharpDocumentationComment.cs | 63 - .../TypeSystem/CSharpTypeResolveContext.cs | 96 - .../TypeSystem/CSharpUnresolvedFile.cs | 213 - .../CSharpUnresolvedTypeDefinition.cs | 50 - .../TypeSystem/ConstantValues.cs | 521 - .../MemberTypeOrNamespaceReference.cs | 121 - ...odTypeParameterWithInheritedConstraints.cs | 121 - .../TypeSystem/ResolvedUsingScope.cs | 210 - .../SimpleTypeOrNamespaceReference.cs | 109 - .../TypeSystem/TypeOrNamespaceReference.cs | 80 - .../TypeSystem/TypeSystemConvertVisitor.cs | 1333 -- .../TypeSystem/UsingScope.cs | 174 - .../Util/CloneableStack.cs | 201 - .../AXmlAttribute.cs | 118 - .../AXmlDocument.cs | 58 - .../ICSharpCode.NRefactory.Xml/AXmlElement.cs | 243 - .../ICSharpCode.NRefactory.Xml/AXmlObject.cs | 246 - .../ICSharpCode.NRefactory.Xml/AXmlParser.cs | 147 - .../ICSharpCode.NRefactory.Xml/AXmlReader.cs | 478 - .../ICSharpCode.NRefactory.Xml/AXmlTag.cs | 98 - .../ICSharpCode.NRefactory.Xml/AXmlText.cs | 63 - .../ICSharpCode.NRefactory.Xml/AXmlVisitor.cs | 62 - .../DocumentationElement.cs | 285 - .../ICSharpCode.NRefactory.Xml.csproj | 124 - .../IncrementalParserState.cs | 115 - .../InternalDocument.cs | 175 - NRefactory/ICSharpCode.NRefactory.Xml/Log.cs | 88 - .../ObjectIterator.cs | 109 - .../Properties/AssemblyInfo.cs | 15 - .../ReuseEqualityComparer.cs | 52 - .../ICSharpCode.NRefactory.Xml/SyntaxError.cs | 73 - .../TagMatchingHeuristics.cs | 352 - .../ICSharpCode.NRefactory.Xml/TagReader.cs | 836 - .../ICSharpCode.NRefactory.Xml/TextType.cs | 47 - .../ICSharpCode.NRefactory.Xml/TokenReader.cs | 350 - .../ICSharpCode.NRefactory.Xml/XmlSegment.cs | 48 - NRefactory/ICSharpCode.NRefactory.snk | Bin 596 -> 0 bytes .../Analysis/AbiComparer.cs | 248 - .../Analysis/SymbolCollector.cs | 165 - .../Analysis/TypeGraph.cs | 82 - .../Analysis/TypeGraphNode.cs | 51 - .../Completion/CompletionCategory.cs | 49 - .../Completion/CompletionExtensionMethods.cs | 72 - .../Completion/DisplayFlags.cs | 42 - .../Completion/FrameworkLookup.cs | 490 - .../Completion/ICompletionData.cs | 53 - .../Completion/IEntityCompletionData.cs | 37 - .../Completion/IParameterDataProvider.cs | 84 - .../Completion/IVariableCompletionData.cs | 38 - .../Documentation/DocumentationComment.cs | 95 - .../GetPotentiallyNestedClassTypeReference.cs | 71 - .../Documentation/IDocumentationProvider.cs | 51 - .../Documentation/IdStringMemberReference.cs | 77 - .../Documentation/IdStringProvider.cs | 391 - .../Documentation/XmlDocumentationProvider.cs | 422 - .../Editor/IDocument.cs | 205 - .../Editor/IDocumentLine.cs | 60 - .../ICSharpCode.NRefactory/Editor/ISegment.cs | 71 - .../Editor/ITextAnchor.cs | 139 - .../Editor/ITextPasteHandler.cs | 51 - .../Editor/ITextSource.cs | 218 - .../Editor/ReadOnlyDocument.cs | 447 - .../Editor/StringBuilderDocument.cs | 493 - .../Editor/StringTextSource.cs | 160 - .../Editor/TextChangeEventArgs.cs | 118 - .../Editor/TextSourceVersionProvider.cs | 130 - .../Editor/UnicodeNewline.cs | 365 - .../ICSharpCode.NRefactory/IAnnotatable.cs | 252 - .../ICSharpCode.NRefactory.csproj | 313 - .../PatternMatching/AnyNode.cs | 47 - .../PatternMatching/AnyNodeOrNull.cs | 58 - .../PatternMatching/Backreference.cs | 50 - .../PatternMatching/BacktrackingInfo.cs | 32 - .../PatternMatching/Choice.cs | 68 - .../PatternMatching/INode.cs | 69 - .../PatternMatching/Match.cs | 100 - .../PatternMatching/NamedNode.cs | 53 - .../PatternMatching/OptionalNode.cs | 58 - .../PatternMatching/Pattern.cs | 114 - .../PatternMatching/Repeat.cs | 74 - .../Properties/AssemblyInfo.cs | 37 - .../Properties/GlobalAssemblyInfo.cs | 45 - .../Refactoring/IssueMarker.cs | 57 - .../Refactoring/Severity.cs | 61 - NRefactory/ICSharpCode.NRefactory/Role.cs | 113 - .../Semantics/AmbiguousResolveResult.cs | 51 - .../Semantics/ArrayAccessResolveResult.cs | 50 - .../Semantics/ArrayCreateResolveResult.cs | 60 - .../Semantics/ByReferenceResolveResult.cs | 66 - .../Semantics/ConstantResolveResult.cs | 55 - .../Semantics/Conversion.cs | 568 - .../Semantics/ConversionResolveResult.cs | 68 - .../Semantics/ErrorResolveResult.cs | 56 - .../Semantics/ForEachResolveResult.cs | 90 - .../InitializedObjectResolveResult.cs | 34 - .../Semantics/InvocationResolveResult.cs | 75 - .../Semantics/LocalResolveResult.cs | 77 - .../Semantics/MemberResolveResult.cs | 148 - .../Semantics/NamedArgumentResolveResult.cs | 81 - .../Semantics/NamespaceResolveResult.cs | 50 - .../Semantics/OperatorResolveResult.cs | 90 - .../Semantics/ResolveResult.cs | 78 - .../Semantics/SizeOfResolveResult.cs | 66 - .../Semantics/ThisResolveResult.cs | 44 - .../Semantics/TypeIsResolveResult.cs | 47 - .../Semantics/TypeOfResolveResult.cs | 46 - .../Semantics/TypeResolveResult.cs | 47 - .../Semantics/UnknownMemberResolveResult.cs | 122 - .../ICSharpCode.NRefactory/TextLocation.cs | 223 - .../TypeSystem/Accessibility.cs | 117 - .../TypeSystem/AnonymousType.cs | 221 - .../TypeSystem/ArrayType.cs | 200 - .../TypeSystem/AssemblyLoader.cs | 94 - .../TypeSystem/AssemblyQualifiedTypeName.cs | 79 - .../TypeSystem/ByReferenceType.cs | 112 - .../TypeSystem/ComHelper.cs | 63 - .../TypeSystem/DefaultSolutionSnapshot.cs | 86 - .../TypeSystem/DomRegion.cs | 230 - .../TypeSystem/EntityType.cs | 63 - .../TypeSystem/Error.cs | 139 - .../TypeSystem/FullTypeName.cs | 315 - .../TypeSystem/IAmbience.cs | 107 - .../TypeSystem/IAssembly.cs | 128 - .../TypeSystem/IAttribute.cs | 75 - .../TypeSystem/ICodeContext.cs | 38 - .../TypeSystem/ICompilation.cs | 91 - .../TypeSystem/IConstantValue.cs | 38 - .../TypeSystem/IEntity.cs | 178 - .../TypeSystem/IEvent.cs | 58 - .../TypeSystem/IField.cs | 99 - .../TypeSystem/IFreezable.cs | 35 - .../TypeSystem/IInterningProvider.cs | 102 - .../TypeSystem/IMember.cs | 196 - .../TypeSystem/IMethod.cs | 168 - .../TypeSystem/INamedElement.cs | 66 - .../TypeSystem/INamespace.cs | 88 - .../TypeSystem/IParameter.cs | 104 - .../TypeSystem/IParameterizedMember.cs | 40 - .../TypeSystem/IProjectContent.cs | 159 - .../TypeSystem/IProperty.cs | 62 - .../TypeSystem/ISolutionSnapshot.cs | 43 - .../TypeSystem/ISupportsInterning.cs | 39 - .../TypeSystem/ISymbol.cs | 100 - .../TypeSystem/IType.cs | 350 - .../TypeSystem/ITypeDefinition.cs | 170 - .../TypeSystem/ITypeParameter.cs | 151 - .../TypeSystem/ITypeReference.cs | 73 - .../TypeSystem/IUnresolvedFile.cs | 80 - .../TypeSystem/IVariable.cs | 54 - .../Implementation/AbstractFreezable.cs | 110 - .../Implementation/AbstractResolvedEntity.cs | 124 - .../Implementation/AbstractResolvedMember.cs | 167 - .../AbstractResolvedTypeParameter.cs | 412 - .../TypeSystem/Implementation/AbstractType.cs | 180 - .../AbstractUnresolvedEntity.cs | 334 - .../AbstractUnresolvedMember.cs | 272 - .../AccessorOwnerMemberReference.cs | 56 - .../Implementation/BaseTypeCollector.cs | 75 - .../TypeSystem/Implementation/BlobReader.cs | 387 - .../DefaultAssemblyReference.cs | 87 - .../Implementation/DefaultAttribute.cs | 97 - .../Implementation/DefaultMemberReference.cs | 118 - .../Implementation/DefaultParameter.cs | 202 - .../Implementation/DefaultResolvedEvent.cs | 69 - .../Implementation/DefaultResolvedField.cs | 87 - .../Implementation/DefaultResolvedMethod.cs | 322 - .../Implementation/DefaultResolvedProperty.cs | 83 - .../DefaultResolvedTypeDefinition.cs | 963 - .../DefaultResolvedTypeParameter.cs | 257 - .../DefaultUnresolvedAssembly.cs | 575 - .../DefaultUnresolvedAttribute.cs | 283 - .../Implementation/DefaultUnresolvedEvent.cs | 99 - .../Implementation/DefaultUnresolvedField.cs | 97 - .../Implementation/DefaultUnresolvedMethod.cs | 287 - .../DefaultUnresolvedParameter.cs | 275 - .../DefaultUnresolvedProperty.cs | 126 - .../DefaultUnresolvedTypeDefinition.cs | 240 - .../DefaultUnresolvedTypeParameter.cs | 194 - .../Implementation/DefaultVariable.cs | 109 - .../Implementation/DummyTypeParameter.cs | 217 - ...tInterfaceImplementationMemberReference.cs | 80 - .../FullNameAndTypeParameterCount.cs | 28 - .../Implementation/GetClassTypeReference.cs | 158 - .../Implementation/GetMembersHelper.cs | 296 - .../Implementation/KnownTypeCache.cs | 60 - .../Implementation/MergedNamespace.cs | 164 - .../Implementation/MinimalCorlib.cs | 65 - .../Implementation/NestedTypeReference.cs | 106 - .../Implementation/ResolvedAttributeBlob.cs | 176 - .../Implementation/SimpleCompilation.cs | 168 - .../Implementation/SimpleConstantValue.cs | 69 - .../Implementation/SimpleInterningProvider.cs | 143 - .../Implementation/SpecializedEvent.cs | 63 - .../Implementation/SpecializedField.cs | 61 - .../Implementation/SpecializedMember.cs | 410 - .../Implementation/SpecializedMethod.cs | 286 - .../Implementation/SpecializedProperty.cs | 59 - .../SpecializingMemberReference.cs | 67 - .../Implementation/TypeParameterReference.cs | 96 - .../Implementation/TypeWithElementType.cs | 61 - .../TypeSystem/Implementation/UnknownType.cs | 117 - .../Implementation/UnresolvedAttributeBlob.cs | 78 - .../UnresolvedSecurityDeclarationBlob.cs | 152 - .../Implementation/VoidTypeDefinition.cs | 73 - .../TypeSystem/InheritanceHelper.cs | 148 - .../TypeSystem/IntersectionType.cs | 178 - .../TypeSystem/KnownTypeReference.cs | 500 - .../TypeSystem/NullableType.cs | 87 - .../TypeSystem/ParameterListComparer.cs | 168 - .../TypeSystem/ParameterizedType.cs | 436 - .../TypeSystem/PointerType.cs | 113 - .../TypeSystem/ProjectReference.cs | 56 - .../TypeSystem/ReflectionHelper.cs | 424 - .../ReflectionNameParseException.cs | 63 - .../TypeSystem/SimpleTypeResolveContext.cs | 92 - .../TypeSystem/SpecialType.cs | 101 - .../TypeSystem/TaskType.cs | 78 - .../TypeSystem/TopLevelTypeName.cs | 144 - .../TypeSystem/TypeKind.cs | 84 - .../TypeSystem/TypeParameterSubstitution.cs | 193 - .../TypeSystem/TypeSystemExtensions.cs | 788 - .../TypeSystem/TypeVisitor.cs | 63 - .../Utils/7BitEncodedInts.cs | 123 - .../Utils/BitVector16.cs | 83 - .../Utils/BusyManager.cs | 73 - .../Utils/CSharpPrimitiveCast.cs | 431 - .../Utils/CacheManager.cs | 59 - .../Utils/CallbackOnDispose.cs | 51 - .../Utils/ComparableList.cs | 166 - .../CompositeFormatStringParser.cs | 343 - .../CompositeFormatStringParser/FormatItem.cs | 93 - .../FormatStringSegmentBase.cs | 66 - .../IFormatStringError.cs | 68 - .../IFormatStringSegment.cs | 48 - .../TextSegment.cs | 79 - .../ICSharpCode.NRefactory/Utils/EmptyList.cs | 118 - .../Utils/ExtensionMethods.cs | 44 - .../Utils/FastSerializer.cs | 1371 -- .../Utils/GraphVizGraph.cs | 219 - .../Utils/ImmutableStack.cs | 132 - .../Utils/KeyComparer.cs | 81 - .../ICSharpCode.NRefactory/Utils/LazyInit.cs | 48 - .../Utils/MultiDictionary.cs | 154 - .../ICSharpCode.NRefactory/Utils/Platform.cs | 40 - .../Utils/ProjectedList.cs | 239 - .../Utils/ReferenceComparer.cs | 39 - .../Utils/TreeTraversal.cs | 112 - NRefactory/README | 230 - NRefactory/doc/Pattern Matching.html | 115 - NRefactory/doc/TODO | 13 - NRefactory/doc/XML Documentation.html | 60 - NRefactory/doc/copyright.txt | 10 - NRefactory/doc/license.txt | 17 - 1349 files changed, 330034 deletions(-) delete mode 100644 AvalonEdit/Documentation/Architecture.aml delete mode 100644 AvalonEdit/Documentation/Code Completion.aml delete mode 100644 AvalonEdit/Documentation/Coordinate Systems.aml delete mode 100644 AvalonEdit/Documentation/Folding.aml delete mode 100644 AvalonEdit/Documentation/ICSharpCode.AvalonEdit.content delete mode 100644 AvalonEdit/Documentation/ICSharpCode.AvalonEdit.shfbproj delete mode 100644 AvalonEdit/Documentation/License.html delete mode 100644 AvalonEdit/Documentation/Media/NamespaceDependencies.png delete mode 100644 AvalonEdit/Documentation/Media/RenderingPipeline.png delete mode 100644 AvalonEdit/Documentation/Media/VisualTree.png delete mode 100644 AvalonEdit/Documentation/Media/WelcomeScreenshot.png delete mode 100644 AvalonEdit/Documentation/Sample Application.aml delete mode 100644 AvalonEdit/Documentation/Syntax Highlighting.aml delete mode 100644 AvalonEdit/Documentation/Text Rendering.aml delete mode 100644 AvalonEdit/Documentation/Welcome.aml delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/ChangeTrackingTest.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/CollapsingTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/HeightTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/LineManagerTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/RandomizedLineManagerTest.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/TextAnchorTest.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/TextSegmentTreeTest.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/TextUtilitiesTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/UndoStackTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Editing/ChangeDocumentTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Editing/TextSegmentReadOnlySectionTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Highlighting/HighlightedLineMergeTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Highlighting/HtmlClipboardTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/ICSharpCode.AvalonEdit.Tests.PartCover.Settings delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/ICSharpCode.AvalonEdit.Tests.csproj delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/MultipleUIThreads.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Properties/AssemblyInfo.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Search/FindTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/CaretNavigationTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/CompressingTreeListTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/ExtensionMethodsTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/IndentationStringTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/RopeTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/WeakReferenceTests.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit.Tests/packages.config delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/AvalonEditCommands.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionList.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionList.xaml delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionListBox.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionWindow.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionWindowBase.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/ICompletionData.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/IOverloadProvider.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/InsightWindow.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/InsightWindow.xaml delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/OverloadInsightWindow.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/OverloadViewer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentChangeEventArgs.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentChangeOperation.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentLine.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentLineTree.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentTextWriter.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/GapTextBuffer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/IDocument.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/ILineTracker.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/ITextAnchor.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/ITextSource.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/IUndoableOperation.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/LineManager.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/LineNode.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/NewLineFinder.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/OffsetChangeMap.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/RopeTextSource.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/SimpleSegment.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/TextAnchor.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/TextAnchorNode.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/TextAnchorTree.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/TextDocument.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/TextDocumentWeakEventManager.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/TextLocation.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/TextSegment.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/TextSegmentCollection.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/TextSourceVersionProvider.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/TextUtilities.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/UndoOperationGroup.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/UndoStack.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Document/WeakLineTracker.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/AbstractMargin.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/Caret.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretLayer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretNavigationCommandHandler.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretWeakEventHandler.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/DottedLineMargin.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/DragDropException.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/EditingCommandHandler.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/EmptySelection.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/IReadOnlySectionProvider.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/ImeNativeWrapper.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/ImeSupport.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/LineNumberMargin.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/NoReadOnlySections.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/RectangleSelection.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/Selection.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionColorizer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionLayer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionMouseHandler.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionSegment.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/SimpleSelection.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextArea.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextAreaDefaultInputHandlers.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextAreaInputHandler.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextSegmentReadOnlySectionProvider.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingElementGenerator.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingManager.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingMargin.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingMarginMarker.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingSection.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Folding/NewFolding.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Folding/XmlFoldingStrategy.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/DocumentHighlighter.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightedInlineBuilder.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightedLine.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightedSection.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingBrush.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingColor.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingColorizer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingDefinitionInvalidException.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingDefinitionTypeConverter.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingEngine.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingManager.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingRule.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingRuleSet.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingSpan.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HtmlClipboard.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HtmlOptions.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HtmlRichTextWriter.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/IHighlighter.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/IHighlightingDefinition.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/IHighlightingDefinitionReferenceResolver.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/ASPX.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Boo.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/CPP-Mode.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/CSS-Mode.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/CSharp-Mode.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Coco-Mode.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/HTML-Mode.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Java-Mode.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/JavaScript-Mode.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/MarkDown-Mode.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/ModeV1.xsd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/ModeV2.xsd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/PHP-Mode.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Patch-Mode.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/PowerShell.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Resources.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Tex-Mode.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/VB-Mode.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/XML-Mode.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/XmlDoc.xshd delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichText.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichTextColorizer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichTextModel.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichTextModelWriter.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/HighlightingLoader.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/IXshdVisitor.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/SaveXshdVisitor.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/V1Loader.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/V2Loader.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XmlHighlightingDefinition.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdColor.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdElement.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdImport.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdKeywords.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdProperty.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdReference.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdRule.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdRuleSet.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdSpan.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdSyntaxDefinition.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/ICSharpCode.AvalonEdit.csproj delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/ICSharpCode.AvalonEdit.snk delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Indentation/CSharp/CSharpIndentationStrategy.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Indentation/CSharp/DocumentAccessor.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Indentation/CSharp/IndentationReformatter.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Indentation/DefaultIndentationStrategy.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Indentation/IIndentationStrategy.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Properties/AssemblyInfo.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Properties/CodeAnalysisDictionary.xml delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/BackgroundGeometryBuilder.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/CollapsedLineSection.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ColorizingTransformer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ColumnRulerRenderer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/CurrentLineHighlightRenderer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/DefaultTextRunTypographyProperties.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/DocumentColorizingTransformer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/FormattedTextElement.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/GlobalTextRunProperties.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/HeightTree.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/HeightTreeLineNode.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/HeightTreeNode.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/IBackgroundRenderer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ITextRunConstructionContext.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ITextViewConnect.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/IVisualLineTransformer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/InlineObjectRun.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/Layer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/LayerPosition.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/LinkElementGenerator.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/MouseHoverLogic.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/SimpleTextSource.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/SingleCharacterElementGenerator.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextLayer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextView.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextViewCachedElements.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextViewWeakEventManager.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLine.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineConstructionStartEventArgs.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineElement.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineElementGenerator.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineElementTextRunProperties.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineLinkText.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineText.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineTextParagraphProperties.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineTextSource.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLinesInvalidException.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualYPosition.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Search/DropDownButton.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Search/DropDownButton.xaml delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Search/ISearchStrategy.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Search/Localization.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Search/RegexSearchStrategy.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchCommands.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchPanel.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchPanel.xaml delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchResultBackgroundRenderer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchStrategyFactory.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Search/next.png delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Search/prev.png delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Snippets/IActiveElement.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Snippets/InsertionContext.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Snippets/Snippet.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetAnchorElement.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetBoundElement.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetCaretElement.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetContainerElement.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetElement.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetEventArgs.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetInputHandler.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetReplaceableTextElement.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetSelectionElement.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetTextElement.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/TextEditor.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/TextEditor.xaml delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/TextEditorAutomationPeer.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/TextEditorComponent.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/TextEditorOptions.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/TextEditorWeakEventManager.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/TextViewPosition.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/Boxes.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/CallbackOnDispose.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/CharRope.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/CompressingTreeList.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/Constants.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/DelayedEvents.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/Deque.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/DocumentPrinter.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/Empty.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/ExtensionMethods.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/FileReader.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/IFreezable.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/ImmutableStack.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/NullSafeCollection.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/ObserveAddRemoveCollection.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/PixelSnapHelpers.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/PlainRichTextWriter.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/PropertyChangedWeakEventManager.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/RichTextWriter.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/Rope.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/RopeNode.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/RopeTextReader.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/StringSegment.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/TextFormatterFactory.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/ThrowUtil.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/WeakEventManagerBase.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/Utils/Win32.cs delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/themes/RightArrow.cur delete mode 100644 AvalonEdit/ICSharpCode.AvalonEdit/themes/generic.xaml delete mode 100644 AvalonEdit/copyright.txt delete mode 100644 AvalonEdit/license.txt delete mode 100644 Mono.Cecil/.gitignore delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/Code.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/CodeReader.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/CodeWriter.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/Document.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/ExceptionHandler.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/ILProcessor.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/Instruction.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/MethodBody.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/OpCode.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/OpCodes.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/SequencePoint.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/Symbols.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/VariableDefinition.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Cil/VariableReference.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Metadata/BlobHeap.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Metadata/Buffers.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Metadata/CodedIndex.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Metadata/ElementType.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Metadata/GuidHeap.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Metadata/Heap.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Metadata/MetadataToken.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Metadata/Row.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Metadata/StringHeap.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Metadata/TableHeap.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Metadata/TokenType.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Metadata/UserStringHeap.cs delete mode 100644 Mono.Cecil/Mono.Cecil.Metadata/Utilities.cs delete mode 100644 Mono.Cecil/Mono.Cecil.PE/BinaryStreamReader.cs delete mode 100644 Mono.Cecil/Mono.Cecil.PE/BinaryStreamWriter.cs delete mode 100644 Mono.Cecil/Mono.Cecil.PE/ByteBuffer.cs delete mode 100644 Mono.Cecil/Mono.Cecil.PE/ByteBufferEqualityComparer.cs delete mode 100644 Mono.Cecil/Mono.Cecil.PE/DataDirectory.cs delete mode 100644 Mono.Cecil/Mono.Cecil.PE/Image.cs delete mode 100644 Mono.Cecil/Mono.Cecil.PE/ImageReader.cs delete mode 100644 Mono.Cecil/Mono.Cecil.PE/ImageWriter.cs delete mode 100644 Mono.Cecil/Mono.Cecil.PE/Section.cs delete mode 100644 Mono.Cecil/Mono.Cecil.PE/TextMap.cs delete mode 100644 Mono.Cecil/Mono.Cecil.csproj delete mode 100755 Mono.Cecil/Mono.Cecil.nunit delete mode 100644 Mono.Cecil/Mono.Cecil.nuspec delete mode 100644 Mono.Cecil/Mono.Cecil.sln delete mode 100644 Mono.Cecil/Mono.Cecil/ArrayType.cs delete mode 100644 Mono.Cecil/Mono.Cecil/AssemblyDefinition.cs delete mode 100644 Mono.Cecil/Mono.Cecil/AssemblyFlags.cs delete mode 100644 Mono.Cecil/Mono.Cecil/AssemblyHashAlgorithm.cs delete mode 100644 Mono.Cecil/Mono.Cecil/AssemblyInfo.cs delete mode 100644 Mono.Cecil/Mono.Cecil/AssemblyLinkedResource.cs delete mode 100644 Mono.Cecil/Mono.Cecil/AssemblyNameDefinition.cs delete mode 100644 Mono.Cecil/Mono.Cecil/AssemblyNameReference.cs delete mode 100644 Mono.Cecil/Mono.Cecil/AssemblyReader.cs delete mode 100644 Mono.Cecil/Mono.Cecil/AssemblyWriter.cs delete mode 100644 Mono.Cecil/Mono.Cecil/BaseAssemblyResolver.cs delete mode 100644 Mono.Cecil/Mono.Cecil/CallSite.cs delete mode 100644 Mono.Cecil/Mono.Cecil/CustomAttribute.cs delete mode 100644 Mono.Cecil/Mono.Cecil/DefaultAssemblyResolver.cs delete mode 100644 Mono.Cecil/Mono.Cecil/EmbeddedResource.cs delete mode 100644 Mono.Cecil/Mono.Cecil/EventAttributes.cs delete mode 100644 Mono.Cecil/Mono.Cecil/EventDefinition.cs delete mode 100644 Mono.Cecil/Mono.Cecil/EventReference.cs delete mode 100644 Mono.Cecil/Mono.Cecil/ExportedType.cs delete mode 100644 Mono.Cecil/Mono.Cecil/FieldAttributes.cs delete mode 100644 Mono.Cecil/Mono.Cecil/FieldDefinition.cs delete mode 100644 Mono.Cecil/Mono.Cecil/FieldReference.cs delete mode 100644 Mono.Cecil/Mono.Cecil/FileAttributes.cs delete mode 100644 Mono.Cecil/Mono.Cecil/FunctionPointerType.cs delete mode 100644 Mono.Cecil/Mono.Cecil/GenericInstanceMethod.cs delete mode 100644 Mono.Cecil/Mono.Cecil/GenericInstanceType.cs delete mode 100644 Mono.Cecil/Mono.Cecil/GenericParameter.cs delete mode 100644 Mono.Cecil/Mono.Cecil/GenericParameterAttributes.cs delete mode 100644 Mono.Cecil/Mono.Cecil/IConstantProvider.cs delete mode 100644 Mono.Cecil/Mono.Cecil/ICustomAttributeProvider.cs delete mode 100644 Mono.Cecil/Mono.Cecil/IGenericInstance.cs delete mode 100644 Mono.Cecil/Mono.Cecil/IGenericParameterProvider.cs delete mode 100644 Mono.Cecil/Mono.Cecil/IMarshalInfoProvider.cs delete mode 100644 Mono.Cecil/Mono.Cecil/IMemberDefinition.cs delete mode 100644 Mono.Cecil/Mono.Cecil/IMetadataScope.cs delete mode 100644 Mono.Cecil/Mono.Cecil/IMetadataTokenProvider.cs delete mode 100644 Mono.Cecil/Mono.Cecil/IMethodSignature.cs delete mode 100644 Mono.Cecil/Mono.Cecil/Import.cs delete mode 100644 Mono.Cecil/Mono.Cecil/LinkedResource.cs delete mode 100644 Mono.Cecil/Mono.Cecil/ManifestResourceAttributes.cs delete mode 100644 Mono.Cecil/Mono.Cecil/MarshalInfo.cs delete mode 100644 Mono.Cecil/Mono.Cecil/MemberDefinitionCollection.cs delete mode 100644 Mono.Cecil/Mono.Cecil/MemberReference.cs delete mode 100644 Mono.Cecil/Mono.Cecil/MetadataResolver.cs delete mode 100644 Mono.Cecil/Mono.Cecil/MetadataSystem.cs delete mode 100644 Mono.Cecil/Mono.Cecil/MethodAttributes.cs delete mode 100644 Mono.Cecil/Mono.Cecil/MethodCallingConvention.cs delete mode 100644 Mono.Cecil/Mono.Cecil/MethodDefinition.cs delete mode 100644 Mono.Cecil/Mono.Cecil/MethodImplAttributes.cs delete mode 100644 Mono.Cecil/Mono.Cecil/MethodReference.cs delete mode 100644 Mono.Cecil/Mono.Cecil/MethodReturnType.cs delete mode 100644 Mono.Cecil/Mono.Cecil/MethodSemanticsAttributes.cs delete mode 100644 Mono.Cecil/Mono.Cecil/MethodSpecification.cs delete mode 100644 Mono.Cecil/Mono.Cecil/Modifiers.cs delete mode 100644 Mono.Cecil/Mono.Cecil/ModuleDefinition.cs delete mode 100644 Mono.Cecil/Mono.Cecil/ModuleKind.cs delete mode 100644 Mono.Cecil/Mono.Cecil/ModuleReference.cs delete mode 100644 Mono.Cecil/Mono.Cecil/NativeType.cs delete mode 100644 Mono.Cecil/Mono.Cecil/PInvokeAttributes.cs delete mode 100644 Mono.Cecil/Mono.Cecil/PInvokeInfo.cs delete mode 100644 Mono.Cecil/Mono.Cecil/ParameterAttributes.cs delete mode 100644 Mono.Cecil/Mono.Cecil/ParameterDefinition.cs delete mode 100644 Mono.Cecil/Mono.Cecil/ParameterDefinitionCollection.cs delete mode 100644 Mono.Cecil/Mono.Cecil/ParameterReference.cs delete mode 100644 Mono.Cecil/Mono.Cecil/PinnedType.cs delete mode 100644 Mono.Cecil/Mono.Cecil/PointerType.cs delete mode 100644 Mono.Cecil/Mono.Cecil/PropertyAttributes.cs delete mode 100644 Mono.Cecil/Mono.Cecil/PropertyDefinition.cs delete mode 100644 Mono.Cecil/Mono.Cecil/PropertyReference.cs delete mode 100644 Mono.Cecil/Mono.Cecil/ReferenceType.cs delete mode 100644 Mono.Cecil/Mono.Cecil/Resource.cs delete mode 100644 Mono.Cecil/Mono.Cecil/SecurityDeclaration.cs delete mode 100644 Mono.Cecil/Mono.Cecil/SentinelType.cs delete mode 100644 Mono.Cecil/Mono.Cecil/TargetRuntime.cs delete mode 100644 Mono.Cecil/Mono.Cecil/TypeAttributes.cs delete mode 100644 Mono.Cecil/Mono.Cecil/TypeDefinition.cs delete mode 100644 Mono.Cecil/Mono.Cecil/TypeDefinitionCollection.cs delete mode 100644 Mono.Cecil/Mono.Cecil/TypeParser.cs delete mode 100644 Mono.Cecil/Mono.Cecil/TypeReference.cs delete mode 100644 Mono.Cecil/Mono.Cecil/TypeSpecification.cs delete mode 100644 Mono.Cecil/Mono.Cecil/TypeSystem.cs delete mode 100644 Mono.Cecil/Mono.Cecil/VariantType.cs delete mode 100644 Mono.Cecil/Mono.Collections.Generic/Collection.cs delete mode 100644 Mono.Cecil/Mono.Collections.Generic/ReadOnlyCollection.cs delete mode 100644 Mono.Cecil/Mono.Security.Cryptography/CryptoConvert.cs delete mode 100644 Mono.Cecil/Mono.Security.Cryptography/CryptoService.cs delete mode 100644 Mono.Cecil/Mono/Actions.cs delete mode 100644 Mono.Cecil/Mono/Empty.cs delete mode 100644 Mono.Cecil/Mono/Funcs.cs delete mode 100644 Mono.Cecil/NOTES.txt delete mode 100644 Mono.Cecil/System.Runtime.CompilerServices/ExtensionAttribute.cs delete mode 100644 Mono.Cecil/Test/.gitignore delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests.csproj delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/Addin.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/AssemblyInfo.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/AssemblyTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/BaseTestFixture.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/CompilationService.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/CustomAttributesTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/EventTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/Extensions.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/FieldTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/Formatter.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/ILProcessorTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/ImageReadTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/ImportCecilTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/ImportReflectionTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/Linq.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/MethodBodyTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/MethodTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/ModuleTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/NestedTypesTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/ParameterTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/PropertyTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/ResolveTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/SecurityDeclarationTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/TypeParserTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/TypeTests.cs delete mode 100644 Mono.Cecil/Test/Mono.Cecil.Tests/VariableTests.cs delete mode 100644 Mono.Cecil/Test/Resources/assemblies/boxedoptarg.dll delete mode 100644 Mono.Cecil/Test/Resources/assemblies/catch.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/cppcli.dll delete mode 100644 Mono.Cecil/Test/Resources/assemblies/cscgpbug.dll delete mode 100644 Mono.Cecil/Test/Resources/assemblies/decsec-att.dll delete mode 100644 Mono.Cecil/Test/Resources/assemblies/decsec-xml.dll delete mode 100644 Mono.Cecil/Test/Resources/assemblies/decsec1-xml.dll delete mode 100644 Mono.Cecil/Test/Resources/assemblies/delay-signed.dll delete mode 100644 Mono.Cecil/Test/Resources/assemblies/empty-decsec-att.dll delete mode 100644 Mono.Cecil/Test/Resources/assemblies/fptr.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/gifaceref.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/hello.anycpu.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/hello.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/hello.ia64.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/hello.x64.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/hello.x86.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/hello1.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/hellow.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/iterator.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/libhello.dll delete mode 100644 Mono.Cecil/Test/Resources/assemblies/libres.dll delete mode 100644 Mono.Cecil/Test/Resources/assemblies/marshal.dll delete mode 100644 Mono.Cecil/Test/Resources/assemblies/metro.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/mma.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/moda.netmodule delete mode 100644 Mono.Cecil/Test/Resources/assemblies/modb.netmodule delete mode 100644 Mono.Cecil/Test/Resources/assemblies/noblob.dll delete mode 100644 Mono.Cecil/Test/Resources/assemblies/pinvoke.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/switch.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/text_file.txt delete mode 100644 Mono.Cecil/Test/Resources/assemblies/varargs.exe delete mode 100644 Mono.Cecil/Test/Resources/assemblies/wp7.dll delete mode 100644 Mono.Cecil/Test/Resources/cs/CustomAttributes.cs delete mode 100644 Mono.Cecil/Test/Resources/cs/Events.cs delete mode 100644 Mono.Cecil/Test/Resources/cs/Fields.cs delete mode 100644 Mono.Cecil/Test/Resources/cs/Generics.cs delete mode 100644 Mono.Cecil/Test/Resources/cs/Interfaces.cs delete mode 100644 Mono.Cecil/Test/Resources/cs/Layouts.cs delete mode 100644 Mono.Cecil/Test/Resources/cs/Methods.cs delete mode 100644 Mono.Cecil/Test/Resources/cs/NestedTypes.cs delete mode 100644 Mono.Cecil/Test/Resources/cs/Properties.cs delete mode 100644 Mono.Cecil/Test/Resources/il/explicitthis.il delete mode 100644 Mono.Cecil/Test/Resources/il/hello.il delete mode 100644 Mono.Cecil/Test/Resources/il/methodspecs.il delete mode 100644 Mono.Cecil/Test/Resources/il/others.il delete mode 100644 Mono.Cecil/Test/Resources/il/types.il delete mode 100644 Mono.Cecil/Test/libs/nunit-2.4.8/license.txt delete mode 100755 Mono.Cecil/Test/libs/nunit-2.5.10/nunit.core.dll delete mode 100755 Mono.Cecil/Test/libs/nunit-2.5.10/nunit.core.interfaces.dll delete mode 100755 Mono.Cecil/Test/libs/nunit-2.5.10/nunit.framework.dll delete mode 100644 Mono.Cecil/dbg/Program.cs delete mode 100644 Mono.Cecil/dbg/Properties/AssemblyInfo.cs delete mode 100644 Mono.Cecil/dbg/dbg.csproj delete mode 100644 Mono.Cecil/mono.snk delete mode 100644 Mono.Cecil/rocks/.gitignore delete mode 100644 Mono.Cecil/rocks/Mono.Cecil.Rocks.csproj delete mode 100644 Mono.Cecil/rocks/Mono.Cecil.Rocks/AssemblyInfo.cs delete mode 100644 Mono.Cecil/rocks/Mono.Cecil.Rocks/Functional.cs delete mode 100644 Mono.Cecil/rocks/Mono.Cecil.Rocks/ILParser.cs delete mode 100644 Mono.Cecil/rocks/Mono.Cecil.Rocks/MethodBodyRocks.cs delete mode 100644 Mono.Cecil/rocks/Mono.Cecil.Rocks/MethodDefinitionRocks.cs delete mode 100644 Mono.Cecil/rocks/Mono.Cecil.Rocks/ModuleDefinitionRocks.cs delete mode 100644 Mono.Cecil/rocks/Mono.Cecil.Rocks/ParameterReferenceRocks.cs delete mode 100644 Mono.Cecil/rocks/Mono.Cecil.Rocks/SecurityDeclarationRocks.cs delete mode 100644 Mono.Cecil/rocks/Mono.Cecil.Rocks/TypeDefinitionRocks.cs delete mode 100644 Mono.Cecil/rocks/Mono.Cecil.Rocks/TypeReferenceRocks.cs delete mode 100644 Mono.Cecil/rocks/Test/.gitignore delete mode 100644 Mono.Cecil/rocks/Test/Mono.Cecil.Rocks.Tests.csproj delete mode 100644 Mono.Cecil/rocks/Test/Mono.Cecil.Tests/Addin.cs delete mode 100644 Mono.Cecil/rocks/Test/Mono.Cecil.Tests/MethodDefinitionRocksTests.cs delete mode 100644 Mono.Cecil/rocks/Test/Mono.Cecil.Tests/ModuleDefinitionRocksTests.cs delete mode 100644 Mono.Cecil/rocks/Test/Mono.Cecil.Tests/SecurityDeclarationRocksTests.cs delete mode 100644 Mono.Cecil/rocks/Test/Mono.Cecil.Tests/TypeDefinitionRocksTests.cs delete mode 100644 Mono.Cecil/rocks/Test/Mono.Cecil.Tests/TypeReferenceRocksTests.cs delete mode 100644 Mono.Cecil/rocks/Test/Resources/assemblies/decsec-att.dll delete mode 100644 Mono.Cecil/rocks/Test/Resources/assemblies/decsec-xml.dll delete mode 100644 Mono.Cecil/rocks/Test/Resources/cs/Types.cs delete mode 100644 Mono.Cecil/symbols/mdb/.gitignore delete mode 100644 Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb.csproj delete mode 100644 Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/AssemblyInfo.cs delete mode 100644 Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/MdbReader.cs delete mode 100644 Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/MdbWriter.cs delete mode 100644 Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolFile.cs delete mode 100644 Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolTable.cs delete mode 100644 Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolWriter.cs delete mode 100644 Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/SymbolWriterImpl.cs delete mode 100644 Mono.Cecil/symbols/mdb/Test/.gitignore delete mode 100644 Mono.Cecil/symbols/mdb/Test/Mono.Cecil.Mdb.Tests.csproj delete mode 100644 Mono.Cecil/symbols/mdb/Test/Mono.Cecil.Tests/Addin.cs delete mode 100644 Mono.Cecil/symbols/mdb/Test/Mono.Cecil.Tests/MdbTests.cs delete mode 100644 Mono.Cecil/symbols/mdb/Test/Resources/assemblies/hello.exe delete mode 100644 Mono.Cecil/symbols/mdb/Test/Resources/assemblies/hello.exe.mdb delete mode 100644 Mono.Cecil/symbols/pdb/.gitignore delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/BitAccess.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/BitSet.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/CvInfo.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DataStream.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiDbgHdr.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiHeader.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiModuleInfo.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiSecCon.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/IntHashTable.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/Interfaces.cs delete mode 100755 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/LICENSE delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/MsfDirectory.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbConstant.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbDebugException.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbException.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbFile.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbFileHeader.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbFunction.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbLine.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbLines.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbReader.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbScope.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbSlot.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbSource.cs delete mode 100644 Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/SourceLocationProvider.cs delete mode 100644 Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb.csproj delete mode 100644 Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/AssemblyInfo.cs delete mode 100644 Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/ISymUnmanagedDocumentWriter.cs delete mode 100644 Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/ISymUnmanagedWriter2.cs delete mode 100644 Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/ModuleMetadata.cs delete mode 100644 Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/PdbHelper.cs delete mode 100644 Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/PdbReader.cs delete mode 100644 Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/PdbWriter.cs delete mode 100644 Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/SymDocumentWriter.cs delete mode 100644 Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/SymWriter.cs delete mode 100644 Mono.Cecil/symbols/pdb/Test/.gitignore delete mode 100644 Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Pdb.Tests.csproj delete mode 100644 Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Tests/Addin.cs delete mode 100644 Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Tests/Linq.cs delete mode 100644 Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Tests/PdbTests.cs delete mode 100755 Mono.Cecil/symbols/pdb/Test/Resources/assemblies/VBConsApp.exe delete mode 100755 Mono.Cecil/symbols/pdb/Test/Resources/assemblies/VBConsApp.pdb delete mode 100755 Mono.Cecil/symbols/pdb/Test/Resources/assemblies/fsapp.exe delete mode 100755 Mono.Cecil/symbols/pdb/Test/Resources/assemblies/fsapp.pdb delete mode 100644 Mono.Cecil/symbols/pdb/Test/Resources/assemblies/test.exe delete mode 100644 Mono.Cecil/symbols/pdb/Test/Resources/assemblies/test.pdb rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/AssemblyInfo.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/General/UnitTest.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/ICSharpCode.NRefactory.VB.Tests.csproj (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Lexer/CustomLexerTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Lexer/ImplicitLineContinuationTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Lexer/LATextReaderTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Lexer/LexerContextTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Lexer/LexerPositionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Lexer/LexerTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Lexer/LiteralsTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Lexer/TokenTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Lexer/XmlModeLexerTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMParenthesizedExpressionTest.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMPrimitiveExpressionTest.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMTypeReferenceTest.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/InvocationExpressionTest.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Output/SpecialOutputVisitorTest.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Output/VBNet/VBNetOutputTest.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/AddressOfExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ArrayCreateExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/AssignmentExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/BaseReferenceExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/BinaryOperatorExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/CastExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ClassReferenceExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ConditionalExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/GlobalReferenceExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/IdentifierExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/InvocationExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/LambdaExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/MemberReferenceExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ObjectCreateExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ParenthesizedExpressionTest.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/PrimitiveExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/QueryExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ThisReferenceExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeOfExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeOfIsExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeReferenceExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/UnaryOperatorExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/XmlExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/XmlMemberAccessExpressionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/AttributeSectionTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/ImportsStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/NamespaceDeclarationTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/OptionStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/TypeDeclarationTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/ParseUtil.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/SnippetParserTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/AddHandlerStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/BlockStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ContinueStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/DoLoopStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/EndStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/EraseStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ErrorStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ExpressionStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ForNextStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ForeachStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/GotoStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/IfElseStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LabelStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LocalVariableDeclarationTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LockStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/OnErrorStatementTest.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/RaiseEventStatementTest.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ReDimStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/RemoveHandlerStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ResumeStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ReturnStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/StopStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/SwitchStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ThrowStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/TryCatchStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/UsingStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/WithStatementTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/ConstructorDeclarationTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/CustomEventTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/DeclareDeclarationTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/EventDeclarationTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/FieldDeclarationTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/MethodDeclarationTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/OperatorDeclarationTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/PropertyDeclarationTests.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/AstNode.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/AstNodeCollection.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Comment.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Enums.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/AnonymousObjectCreationExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/ArrayCreateExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/ArrayInitializerExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/AssignmentExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/BinaryOperatorExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/CastExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/CollectionRangeVariableDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/ConditionalExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/EmptyExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/Expression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/FieldInitializerExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/GetTypeExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/GetXmlNamespaceExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/IdentifierExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/InstanceExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/InvocationExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/LambdaExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/MemberAccessExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/NamedArgumentExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/ObjectCreationExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/ParenthesizedExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/PrimitiveExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/QueryExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/SimpleNameExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/TypeOfIsExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/TypeReferenceExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/UnaryOperatorExpression.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/VariableInitializer.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/XmlIdentifier.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Expressions/XmlLiteralString.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/General/Attribute.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/General/AttributeBlock.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/General/AttributedNode.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/General/CompilationUnit.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/General/EventMemberSpecifier.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/General/InterfaceMemberSpecifier.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/General/ParameterDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/General/TypeParameterDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Generated.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/GlobalScope/DelegateDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/GlobalScope/EnumDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/GlobalScope/EnumMemberDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/GlobalScope/ImportsClause.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/GlobalScope/ImportsStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/GlobalScope/NamespaceDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/GlobalScope/OptionStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/GlobalScope/TypeDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/INullable.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Identifier.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/AddRemoveHandlerStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/BlockStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/ContinueStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/DoLoopStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/ExitStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/ExpressionStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/ForEachStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/ForStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/GoToStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/IfElseStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/LabelDeclarationStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/LocalDeclarationStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/ReturnStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/SelectStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/Statement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/SyncLockStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/ThrowStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/TryStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/UsingStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/WhileStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/WithStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/Statements/YieldStatement.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeMembers/Accessor.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeMembers/ConstructorDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeMembers/EventDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeMembers/ExternalMethodDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeMembers/FieldDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeMembers/MethodDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeMembers/OperatorDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeMembers/PropertyDeclaration.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeMembers/VariableDeclarator.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeName/AstType.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeName/ComposedType.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeName/PrimitiveType.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeName/QualifiedType.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/TypeName/SimpleType.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/VBModifierToken.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Ast/VBTokenNode.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/IAstVisitor.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/ICSharpCode.NRefactory.VB.csproj (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/Block.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/ExpressionFinder.atg (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/ExpressionFinder.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/ExpressionFinderState.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/Extensions.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/KeywordList.txt (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/Keywords.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/LATextReader.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/LookupTable.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/Parser.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/PushParser.frame (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/SavepointEventArgs.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/Special/BlankLine.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/Special/Comment.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/Special/CommentType.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/Special/ISpecial.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/Special/PreProcessingDirective.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/Special/SpecialTracker.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/Special/TagComment.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/Token.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/Tokens.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/VBLexer.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/VBLexerMemento.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Lexer/XmlModeInfo.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/OutputVisitor/IOutputFormatter.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/OutputVisitor/OutputVisitor.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/OutputVisitor/TextWriterOutputFormatter.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/OutputVisitor/VBFormattingOptions.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Parser/Errors.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Parser/Parser.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Parser/Parser.frame (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Parser/VBParser.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Parser/vb.atg (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/PrettyPrinter/AbstractOutputFormatter.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/PrettyPrinter/AbstractPrettyPrintOptions.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/PrettyPrinter/IOutputAstVisitor.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/PrettyPrinter/SpecialNodesInserter.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/PrettyPrinter/VBNet/VBNetOutputFormatter.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/PrettyPrinter/VBNet/VBNetOutputVisitor.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/PrettyPrinter/VBNet/VBNetPrettyPrintOptions.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Properties/AssemblyInfo.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/VBParser.cs (100%) rename {NRefactory => NRefactory.VB}/ICSharpCode.NRefactory.VB/Visitors/CSharpToVBConverterVisitor.cs (100%) delete mode 100644 NRefactory/.gitattributes delete mode 100644 NRefactory/.gitignore delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/AnnotationNames.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/ControlFlow.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DeclarationSpace/LocalDeclarationSpace.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DeclarationSpace/LocalDeclarationSpaceVisitor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DefiniteAssignmentAnalysis.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/NullValueAnalysis.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/NullValueStatus.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/ReachabilityAnalysis.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/SemanticHighlightingVisitor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstNode.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstNodeCollection.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/CSharpModifierToken.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/CSharpTokenNode.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/CSharpUtil.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ComposedType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/DepthFirstAstVisitor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/DocumentationReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ErrorNode.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AnonymousMethodExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AnonymousTypeCreateExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ArrayCreateExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ArrayInitializerExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AsExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AssignmentExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/BaseReferenceExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/BinaryOperatorExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/CastExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/CheckedExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ConditionalExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/DefaultValueExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/DirectionExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ErrorExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/Expression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/IdentifierExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/IndexerExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/InvocationExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/IsExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/LambdaExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/MemberReferenceExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/NamedArgumentExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/NamedExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/NullReferenceExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ObjectCreateExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ParenthesizedExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/PointerReferenceExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/PrimitiveExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/QueryExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/SizeOfExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/StackAllocExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ThisReferenceExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/TypeOfExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/TypeReferenceExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/UnaryOperatorExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/UncheckedExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/UndocumentedExpression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/Attribute.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/AttributeSection.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/Comment.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/Constraint.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/DelegateDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/ExternAliasDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/NamespaceDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/NewLineNode.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/PreProcessorDirective.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/TextNode.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/TypeDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/TypeParameterDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/UsingAliasDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/UsingDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/WhitespaceNode.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/IAstVisitor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Identifier.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/IdentifierExpressionBackreference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/MemberType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Modifiers.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/NodeType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ObservableAstVisitor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/PrimitiveType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Roles.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SimpleType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/BlockStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/BreakStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/CheckedStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ContinueStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/DoWhileStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/EmptyStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ExpressionStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/FixedStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ForStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ForeachStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/GotoStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/IfElseStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/LabelStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/LockStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ReturnStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/Statement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/SwitchStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ThrowStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/TryCatchStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/UncheckedStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/UnsafeStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/UsingStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/VariableDeclarationStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/WhileStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/YieldBreakStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/YieldReturnStatement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SyntaxExtensions.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SyntaxTree.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TokenRole.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/Accessor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/ConstructorDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/DestructorDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/EntityDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/EnumMemberDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/EventDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/FieldDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/FixedFieldDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/FixedVariableInitializer.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/IndexerDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/MethodDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/OperatorDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/ParameterDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/PropertyDeclaration.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/VariableInitializer.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/CSharpProjectContent.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/CombineQueryExpressions.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngineBase.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpParameterCompletionEngine.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CompletionDataWrapper.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionContextProvider.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionDataFactory.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Completion/IParameterCompletionDataFactory.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/CSharpFormatter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/CSharpFormattingOptions.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/ConstructFixer.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingChanges.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingOptionsFactory.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Expressions.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Global.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Query.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Statements.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_TypeMembers.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/GeneratedCodeSettings.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/Indent.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/TextEditorOptions.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/ICSharpCode.NRefactory.CSharp.csproj delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/CSharpIndentEngine.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/CacheIndentEngine.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IDocumentIndentEngine.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IStateMachineIndentEngine.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IndentState.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/NullIStateMachineIndentEngine.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/TextPasteIndentEngine.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/IntroduceQueryExpressions.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/NameLookupMode.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpAmbience.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CodeDomConvertVisitor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/ITokenWriter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertMissingTokensDecorator.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertParenthesesVisitor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertRequiredSpacesDecorator.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertSpecialsDecorator.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/TextWriterOutputFormatter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/CSharpParser.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/CompilerSettings.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/SeekableStreamReader.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/CryptoConvert.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolFile.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolTable.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolWriter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/SourceMethodBuilder.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/anonymous.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/argument.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assembly.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assign.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/async.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/attribute.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cfold.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/class.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/codegen.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/complete.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/const.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/constant.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/context.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/convert.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.jay delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-tokenizer.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/decl.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/delegate.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/doc.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/driver.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dynamic.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/ecore.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/enum.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/eval.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/expression.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/field.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/flowanalysis.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/generic.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/import.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/iterators.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/lambda.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/linq.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/literal.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/location.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/membercache.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/method.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/modifiers.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/module.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/namespace.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/nullable.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/outline.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/parameter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/pending.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/property.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/reflection.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/report.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/settings.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/statement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/support.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/symbolwriter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/typemanager.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/typespec.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/visit.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/PatternMatching/AnyType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Properties/AssemblyInfo.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/QueryExpressionExpander.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/BaseRefactoringContext.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeAction.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActionProvider.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/RemoveFieldRefactoryActionRefactoringAction.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeGenerationService.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssue.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssueProvider.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/Uncategorized/.DS_Store delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CommonSubIssues.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextActionAttribute.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/DocumentScript.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/FormatStringHelper.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/IssueAttribute.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/LambdaHelper.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/LocalReferenceFinder.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/NamingHelper.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/PatternHelper.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/RefactoringAstHelper.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/RefactoringContext.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Script.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/TypeGuessing.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/TypeSystemAstBuilder.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/UsingHelper.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/VariableReferenceGraph.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/WordParser.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/AliasNamespaceResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/AliasTypeResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/AwaitResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/CSharpAstResolver.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/CSharpConversions.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/CSharpInvocationResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/CSharpOperators.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/CSharpResolver.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/CastResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/CompositeResolveVisitorNavigator.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/DetectSkippableNodesNavigator.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/DynamicInvocationResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/DynamicMemberResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/FindReferenceSearchScope.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/FindReferencedEntities.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/FindReferences.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/IResolveVisitorNavigator.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/LambdaResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/Log.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/MemberLookup.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/MethodGroupResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/NodeListResolveVisitorNavigator.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/OverloadResolution.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/OverloadResolutionErrors.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/ReducedExtensionMethod.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/RenameCallbackArguments.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/ResolveAtLocation.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/ResolveVisitor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/TypeInference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/AliasNamespaceReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/AttributeTypeReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/CSharpAssembly.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/CSharpAttribute.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/CSharpDocumentationComment.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/CSharpTypeResolveContext.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/CSharpUnresolvedFile.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/CSharpUnresolvedTypeDefinition.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/ConstantValues.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/MemberTypeOrNamespaceReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/MethodTypeParameterWithInheritedConstraints.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/ResolvedUsingScope.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/TypeOrNamespaceReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/TypeSystemConvertVisitor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/TypeSystem/UsingScope.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.CSharp/Util/CloneableStack.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/AXmlAttribute.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/AXmlDocument.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/AXmlElement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/AXmlObject.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/AXmlParser.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/AXmlReader.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/AXmlTag.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/AXmlText.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/AXmlVisitor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/DocumentationElement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/ICSharpCode.NRefactory.Xml.csproj delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/IncrementalParserState.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/InternalDocument.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/Log.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/ObjectIterator.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/Properties/AssemblyInfo.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/ReuseEqualityComparer.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/SyntaxError.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/TagMatchingHeuristics.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/TagReader.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/TextType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/TokenReader.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.Xml/XmlSegment.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory.snk delete mode 100644 NRefactory/ICSharpCode.NRefactory/Analysis/AbiComparer.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Analysis/SymbolCollector.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Analysis/TypeGraph.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Analysis/TypeGraphNode.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Completion/CompletionCategory.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Completion/CompletionExtensionMethods.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Completion/DisplayFlags.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Completion/FrameworkLookup.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Completion/ICompletionData.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Completion/IEntityCompletionData.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Completion/IParameterDataProvider.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Completion/IVariableCompletionData.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Documentation/DocumentationComment.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Documentation/GetPotentiallyNestedClassTypeReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Documentation/IDocumentationProvider.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Documentation/IdStringMemberReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Documentation/IdStringProvider.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Documentation/XmlDocumentationProvider.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Editor/IDocument.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Editor/IDocumentLine.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Editor/ISegment.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Editor/ITextAnchor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Editor/ITextPasteHandler.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Editor/ITextSource.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Editor/ReadOnlyDocument.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Editor/StringBuilderDocument.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Editor/StringTextSource.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Editor/TextChangeEventArgs.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Editor/TextSourceVersionProvider.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Editor/UnicodeNewline.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/IAnnotatable.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/ICSharpCode.NRefactory.csproj delete mode 100644 NRefactory/ICSharpCode.NRefactory/PatternMatching/AnyNode.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/PatternMatching/AnyNodeOrNull.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/PatternMatching/Backreference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/PatternMatching/BacktrackingInfo.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/PatternMatching/Choice.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/PatternMatching/INode.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/PatternMatching/Match.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/PatternMatching/NamedNode.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/PatternMatching/OptionalNode.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/PatternMatching/Pattern.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/PatternMatching/Repeat.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Properties/AssemblyInfo.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Properties/GlobalAssemblyInfo.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Refactoring/IssueMarker.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Refactoring/Severity.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Role.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/AmbiguousResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/ArrayAccessResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/ArrayCreateResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/ByReferenceResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/ConstantResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/Conversion.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/ConversionResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/ErrorResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/ForEachResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/InitializedObjectResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/InvocationResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/LocalResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/MemberResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/NamedArgumentResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/NamespaceResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/OperatorResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/ResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/SizeOfResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/ThisResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/TypeIsResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/TypeOfResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/TypeResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Semantics/UnknownMemberResolveResult.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TextLocation.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Accessibility.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/AnonymousType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ArrayType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/AssemblyLoader.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/AssemblyQualifiedTypeName.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ByReferenceType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ComHelper.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/DefaultSolutionSnapshot.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/DomRegion.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/EntityType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Error.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/FullTypeName.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IAmbience.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IAssembly.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IAttribute.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ICodeContext.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ICompilation.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IConstantValue.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IEntity.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IEvent.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IField.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IFreezable.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IInterningProvider.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IMember.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IMethod.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/INamedElement.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/INamespace.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IParameter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IParameterizedMember.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IProjectContent.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IProperty.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ISolutionSnapshot.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ISupportsInterning.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ISymbol.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ITypeDefinition.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ITypeParameter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ITypeReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IUnresolvedFile.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IVariable.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractFreezable.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractResolvedEntity.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractResolvedMember.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractResolvedTypeParameter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractUnresolvedEntity.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractUnresolvedMember.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/AccessorOwnerMemberReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/BaseTypeCollector.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/BlobReader.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultAssemblyReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultAttribute.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultMemberReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultParameter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultResolvedEvent.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultResolvedField.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultResolvedMethod.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultResolvedProperty.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultResolvedTypeDefinition.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultResolvedTypeParameter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedAssembly.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedAttribute.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedEvent.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedField.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedMethod.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedParameter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedProperty.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedTypeDefinition.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedTypeParameter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultVariable.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DummyTypeParameter.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/ExplicitInterfaceImplementationMemberReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/FullNameAndTypeParameterCount.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/GetClassTypeReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/GetMembersHelper.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/KnownTypeCache.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/MergedNamespace.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/MinimalCorlib.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/NestedTypeReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/ResolvedAttributeBlob.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SimpleCompilation.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SimpleConstantValue.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SimpleInterningProvider.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SpecializedEvent.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SpecializedField.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SpecializedMember.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SpecializedMethod.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SpecializedProperty.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SpecializingMemberReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/TypeParameterReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/TypeWithElementType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/UnknownType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/UnresolvedAttributeBlob.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/UnresolvedSecurityDeclarationBlob.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/VoidTypeDefinition.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/InheritanceHelper.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/IntersectionType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/KnownTypeReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/NullableType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ParameterListComparer.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ParameterizedType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/PointerType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ProjectReference.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ReflectionHelper.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/ReflectionNameParseException.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/SimpleTypeResolveContext.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/SpecialType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/TaskType.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/TopLevelTypeName.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/TypeKind.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/TypeParameterSubstitution.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/TypeSystemExtensions.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/TypeSystem/TypeVisitor.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/7BitEncodedInts.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/BitVector16.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/BusyManager.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/CSharpPrimitiveCast.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/CacheManager.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/CallbackOnDispose.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/ComparableList.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/CompositeFormatStringParser/CompositeFormatStringParser.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/CompositeFormatStringParser/FormatItem.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/CompositeFormatStringParser/FormatStringSegmentBase.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/CompositeFormatStringParser/IFormatStringError.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/CompositeFormatStringParser/IFormatStringSegment.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/CompositeFormatStringParser/TextSegment.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/EmptyList.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/ExtensionMethods.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/FastSerializer.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/GraphVizGraph.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/ImmutableStack.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/KeyComparer.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/LazyInit.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/MultiDictionary.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/Platform.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/ProjectedList.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/ReferenceComparer.cs delete mode 100644 NRefactory/ICSharpCode.NRefactory/Utils/TreeTraversal.cs delete mode 100644 NRefactory/README delete mode 100644 NRefactory/doc/Pattern Matching.html delete mode 100644 NRefactory/doc/TODO delete mode 100644 NRefactory/doc/XML Documentation.html delete mode 100644 NRefactory/doc/copyright.txt delete mode 100644 NRefactory/doc/license.txt diff --git a/AvalonEdit/Documentation/Architecture.aml b/AvalonEdit/Documentation/Architecture.aml deleted file mode 100644 index 31efc1741..000000000 --- a/AvalonEdit/Documentation/Architecture.aml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - As you can see in this dependency graph, AvalonEdit consists of a few - sub-namespaces that have cleanly separated jobs. - Most of the namespaces have a kind of 'main' class. - Here is the visual tree of the TextEditor control: - - It's important to understand that AvalonEdit is a composite control - with the three layers: - T:ICSharpCode.AvalonEdit.TextEditor (main control), - T:ICSharpCode.AvalonEdit.Editing.TextArea (editing), - T:ICSharpCode.AvalonEdit.Rendering.TextView (rendering). - - While the main control provides some convenience methods for common tasks, - for most advanced features you have to work directly with the inner controls. - You can access them using textEditor.TextArea or - textEditor.TextArea.TextView. - - - \ No newline at end of file diff --git a/AvalonEdit/Documentation/Code Completion.aml b/AvalonEdit/Documentation/Code Completion.aml deleted file mode 100644 index 16fae6b56..000000000 --- a/AvalonEdit/Documentation/Code Completion.aml +++ /dev/null @@ -1,133 +0,0 @@ - - - - - - AvalonEdit comes with a code completion drop down window. - You only have to handle the text entering events to determine - when you want to show the window; all the UI is already done for you. - - -
- Usage of the Code Completion Window - - - // in the constructor: - textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; - textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; -} - -CompletionWindow completionWindow; - -void textEditor_TextArea_TextEntered(object sender, TextCompositionEventArgs e) -{ - if (e.Text == ".") { - // Open code completion after the user has pressed dot: - completionWindow = new CompletionWindow(textEditor.TextArea); - IList<ICompletionData> data = completionWindow.CompletionList.CompletionData; - data.Add(new MyCompletionData("Item1")); - data.Add(new MyCompletionData("Item2")); - data.Add(new MyCompletionData("Item3")); - completionWindow.Show(); - completionWindow.Closed += delegate { - completionWindow = null; - }; - } -} - -void textEditor_TextArea_TextEntering(object sender, TextCompositionEventArgs e) -{ - if (e.Text.Length > 0 && completionWindow != null) { - if (!char.IsLetterOrDigit(e.Text[0])) { - // Whenever a non-letter is typed while the completion window is open, - // insert the currently selected element. - completionWindow.CompletionList.RequestInsertion(e); - } - } - // Do not set e.Handled=true. - // We still want to insert the character that was typed. -} - - - This code will open the code completion window whenever '.' is pressed. - By default, the - T:ICSharpCode.AvalonEdit.CodeCompletion.CompletionWindow - only handles key presses like Tab and Enter to insert the currently - selected item. To also make it complete when keys like '.' or ';' are pressed, - we attach another handler to the TextEntering event - and tell the completion window to insert the selected item. - - - The CompletionWindow will actually never have - focus - instead, it hijacks - the WPF keyboard input events on the text area and passes them through its - ListBox. - This allows selecting entries in the completion list using the - keyboard and normal typing in the editor at the same time. - - - Here is the implementation of the MyCompletionData class used in the code above: - -/// Implements AvalonEdit ICompletionData interface to provide the entries in the -/// completion drop down. -public class MyCompletionData : ICompletionData -{ - public MyCompletionData(string text) - { - this.Text = text; - } - - public System.Windows.Media.ImageSource Image { - get { return null; } - } - - public string Text { get; private set; } - - // Use this property if you want to show a fancy UIElement in the list. - public object Content { - get { return this.Text; } - } - - public object Description { - get { return "Description for " + this.Text; } - } - - public void Complete(TextArea textArea, ISegment completionSegment, - EventArgs insertionRequestEventArgs) - { - textArea.Document.Replace(completionSegment, this.Text); - } -} - - Both the content and the description shown may be any content acceptable in WPF, - including custom UIElements. - You may also implement custom logic in the Complete - method if you want to do more than simply inserting the text. - The insertionRequestEventArgs can help decide which - kind of insertion the user wants - depending on how the insertion was triggered, - it is an instance of TextCompositionEventArgs, - KeyEventArgs or MouseEventArgs. - - -
-
- Code Completion for C# - - - Full C# code completion is not in the scope of AvalonEdit. - You will need a C# parser, a C# type system, and the ability - to resolve C# expressions in your type system. - - - If you want to learn how this is handled in SharpDevelop, please - see: - - Code Completion in SharpDevelop - https://github.com/icsharpcode/SharpDevelop/wiki/Code-Completion - _blank - - - -
-
-
\ No newline at end of file diff --git a/AvalonEdit/Documentation/Coordinate Systems.aml b/AvalonEdit/Documentation/Coordinate Systems.aml deleted file mode 100644 index f644c2ab7..000000000 --- a/AvalonEdit/Documentation/Coordinate Systems.aml +++ /dev/null @@ -1,175 +0,0 @@ - - - - - - - - The text editor makes use of several different coordinate systems. - Here's an explanation of them. - - -
- Offset - - In AvalonEdit, an index into the document is called an offset. - - Offsets usually represent the position between two characters. - The first offset at the start of the document is 0; - the offset after the first char in the document is 1. - The last valid offset is document.TextLength, - representing the end of the document. - This is exactly the same as the index parameter - used by methods in the .NET String or StringBuilder classes. - - -
-
- TextLocation - - The - T:ICSharpCode.AvalonEdit.Document.TextLocation - struct represents a Line/Column pair. Line and column are counted from 1. - The document provides the methods - M:ICSharpCode.AvalonEdit.Document.TextDocument.GetLocation(System.Int32) - and - M:ICSharpCode.AvalonEdit.Document.TextDocument.GetOffset(ICSharpCode.AvalonEdit.Document.TextLocation) - to convert between offsets and TextLocations. - -
-
- TextAnchor - - If you are working with the text editor, you will likely run into the problem - that you need to store an offset, but want it to adjust automatically whenever - text is inserted prior to that offset. - Sure, you could listen to the TextDocument.Changed event and call - GetNewOffset on the DocumentChangeEventArgs to translate the offset, - but that gets tedious; especially when your object is short-lived and you - have to deal with deregistering the event handler at the correct point of time. - A text anchor object stores an Offset, but automatically - updates the offset when text is inserted/removed before the offset. - - - A much simpler solution is to use the - T:ICSharpCode.AvalonEdit.Document.TextAnchor - class. - Please take a look at the documentation for that class for more details. - - -
-
- RelativeTextOffset - - An offset in the document, but relative to the start offset of a T:ICSharpCode.AvalonEdit.Rendering.VisualLine. - Relative text offsets are used to store document offsets in visual lines. - You can convert between relative text offsets and document offsets - by adding/subtracting - P:ICSharpCode.AvalonEdit.Rendering.VisualLine.FirstDocumentLine.P:ICSharpCode.AvalonEdit.Document.DocumentLine.Offset. - - -
-
- VisualColumn - - An integer value that specifies a position inside a VisualLine. - - Not only text has a length in the visual line, but also other VisualLineElements. - VisualColumn is counting from 0 for each visual line. - - For example, tab markers take 2 visual columns (the marker and the tab space), - newline markers take 1 visual column; folding markers take just 1 visual column - even though they are longer in the document text. - Use the - M:ICSharpCode.AvalonEdit.Rendering.VisualLine.GetVisualColumn(System.Int32) - and - M:ICSharpCode.AvalonEdit.Rendering.VisualLine.GetRelativeOffset(System.Int32) - methods to convert between - visual columns and relative text offsets. - - Do not confuse VisualColumn with text columns. - VisualColumn starts at 0, text column at 1. Text may have different length - in the two coordinate systems (e.g. tab markers, foldings). - - -
-
- TextViewPosition - - A Line,Column,VisualColumn triple. - The T:ICSharpCode.AvalonEdit.TextViewPosition - struct can be implicitly converted - to T:ICSharpCode.AvalonEdit.Document.TextLocation, - but has the additional VisualColumn information - that is necessary to accurately hold the caret position when - VisualLineElements with DocumentLength 0 are in use. - -
-
- VisualTop - - A double value that specifies the distance from the top of - the document to the top of a line measured in device-independent pixels. - VisualTop is equivalent to the Y component of a VisualPosition. - -
-
- VisualPosition - - A Point value (double X,Y) that specifies the position of an - element from the top left document corner measured in device-independent pixels. - To convert a VisualPosition to or from a (mouse) position inside - the TextView, simply subtract or add - P:ICSharpCode.AvalonEdit.Rendering.TextView.ScrollOffset - to it. - - -
- - - -
-
\ No newline at end of file diff --git a/AvalonEdit/Documentation/Folding.aml b/AvalonEdit/Documentation/Folding.aml deleted file mode 100644 index d5a4296a0..000000000 --- a/AvalonEdit/Documentation/Folding.aml +++ /dev/null @@ -1,58 +0,0 @@ - - - - -
- How to use Folding in your application - - - Folding (code collapsing) is implemented as an extension to the editor. - It could have been implemented in a separate assembly without having to - modify the AvalonEdit code. - A T:ICSharpCode.AvalonEdit.Rendering.VisualLineElementGenerator - takes care of the collapsed sections in the text document; and a custom - margin draws the plus and minus buttons. - - You could use the relevant classes separately; - but, to make it a bit easier to use, the static - M:ICSharpCode.AvalonEdit.Folding.FoldingManager.Install(ICSharpCode.AvalonEdit.Editing.TextArea) - method will create and register the necessary parts automatically. - All that's left for you is to regularly call - M:ICSharpCode.AvalonEdit.Folding.FoldingManager.UpdateFoldings(System.Collections.Generic.IEnumerable{ICSharpCode.AvalonEdit.Folding.NewFolding},System.Int32) - with the list of foldings you want to provide. - You could calculate that list yourself, or you could use a built-in - folding strategy to do it for you. - Here is the full code required to enable folding: -foldingManager = FoldingManager.Install(textEditor.TextArea); -foldingStrategy = new XmlFoldingStrategy(); -foldingStrategy.UpdateFoldings(foldingManager, textEditor.Document); - If you want the folding markers to update when the text is changed, - you have to repeat the foldingStrategy.UpdateFoldings call regularly. - - -
-
- How the FoldingManager works - - - The FoldingManager maintains a list of foldings. The FoldMargin displays those foldings and provides - the UI for collapsing/expanding. - Folded foldings cause the FoldingElementGenerator to produce a line element that spans the whole folded - text section, causing the text generation for the visual line that contains the folding start to - continue after the folding end in another line. - To ensure scrolling works correctly in the presence of foldings, lines inside folded regions must not - be used as start lines for the visual line generation. This is done by setting the line height of all - such lines to 0. To efficiently set the height on a large number of lines and support reverting to the - old height when the folding is uncollapsed, a CollapsedLineSection is used. - - -
- - T:ICSharpCode.AvalonEdit.Folding.FoldingManager - -
-
\ No newline at end of file diff --git a/AvalonEdit/Documentation/ICSharpCode.AvalonEdit.content b/AvalonEdit/Documentation/ICSharpCode.AvalonEdit.content deleted file mode 100644 index b256bcbf5..000000000 --- a/AvalonEdit/Documentation/ICSharpCode.AvalonEdit.content +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/AvalonEdit/Documentation/ICSharpCode.AvalonEdit.shfbproj b/AvalonEdit/Documentation/ICSharpCode.AvalonEdit.shfbproj deleted file mode 100644 index 9b004e6a5..000000000 --- a/AvalonEdit/Documentation/ICSharpCode.AvalonEdit.shfbproj +++ /dev/null @@ -1,182 +0,0 @@ - - - - - Debug - AnyCPU - 2.0 - {850b6602-0a7f-413a-864a-e816b98d7407} - 1.9.9.0 - - Documentation - Documentation - Documentation - - .\Help\ - AvalonEdit Documentation - - - Summary, AutoDocumentCtors, Namespace - InheritedMembers, InheritedFrameworkMembers, Protected, ProtectedInternalAsProtected - - - - - - - - - - - .NET Framework 4.0 - AvalonEdit - Copyright 2008-2014, Daniel Grunwald - Prototype - 4.4.0.0 - - - - - - {@ReferenceLinkNamespaceFiles} - - - - - - - - - {@FrameworkCommentList} - {@CommentFileList} - - - - - - {@HelpFormatOutputPaths} - - - - - - - - - - - - {@ReferenceLinkNamespaceFiles} - - - - - - - {@ReferenceLinkNamespaceFiles} - - - - - - - {@ReferenceLinkNamespaceFiles} - - - - - - - {@ReferenceLinkNamespaceFiles} - - - - -{@TokenFiles} - - - - - - -This is the main AvalonEdit namespace. -This namespace contains classes to show the code completion window. -This namespace contains the document model. -The most important class here is TextDocument, which represents document that can be displayed and edited in the text editor. -This namespace is the home of the TextArea class. It manages user input and handles the caret and the selection. -This namespace contains the folding (code collapsing) implementation. -This namespace contains the engine for highlighting text documents (DocumentHighlighter). -Additionally, the class HighlightingColorizer provides integration of the highlighting engine into the text editor GUI. -This namespace contains a document model for syntax highlighting definitions (.xshd files). -This namespace contains the logic for automatic indentation. -This namespace contains the text rendering infrastructure. -This namespace contains various utility classes. - -Snippets perform automatic text insertion. Snippets can be interactive after they were expanded, for example to allow the user to easily replace fields in the expanded snippet. -This namespace contains the SearchPanel UI that allows the user to search the current document. - True - Standard - Blank - False - False - Guid - en-US - AboveNamespaces - OnlyWarningsAndErrors - HtmlHelp1, Website - False - True - False - False - - - - - - - - - - - - - - - - - - - - - - WelcomeScreenshot - - - VisualTree - Visual Tree - - - RenderingPipeline - - - NamespaceDependencies - Namespace Dependency Graph - - - True - - - - - - - - \ No newline at end of file diff --git a/AvalonEdit/Documentation/License.html b/AvalonEdit/Documentation/License.html deleted file mode 100644 index d7542b775..000000000 --- a/AvalonEdit/Documentation/License.html +++ /dev/null @@ -1,35 +0,0 @@ - - - - License - - - - - -

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. -

- - - diff --git a/AvalonEdit/Documentation/Media/NamespaceDependencies.png b/AvalonEdit/Documentation/Media/NamespaceDependencies.png deleted file mode 100644 index 6655f805eb6b1ea2b2633e39f09eb4a80bd719bf..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 30932 zcmX_`1yEeg6X21M-~_kDAqf^Fc(7oLySuvwcXto&Zej7oT^4tDcMI-t`~9!(s(v+F zZ|e0-PtQzGzu69#mj$9B6CuOEz@SNpizvdtzyV=kU>gzPp*7(Lu)m-`u)h_7LNJx% zfFtO`2eV%?(8`)vlota8=rg&IxS|XUjK>!k7{4GGm?vnJ-ysZ)Gcyd#u|5n8Pbv%y zzI|qk0xt{Ezorx#>o6lP`?W@Qy;XBX$>l;-9_DbLR@%g=|F6@`Tr zMMagx#Z|?{)up91rKPpy&L4V9JP%1UV2R9y|FrM4DITYWv0j)n#(T}@3; zdRkg~T3h?t+Mqx>I-m?rCnry*rp~0N&tzuKWM|K&r_W_(&Sqy%=jBZo6igQt&FAJ$ zmz7PImoF9+EEX0n6&J6Rm93PQuT)elR#mN5RIFB3PFGjY)YnfpHBEPPELT^rG&ZhR zS8vqUFEuxBHa2dzwCr?r>~?l`bq#iR5BKy8_x6tV^+6ejK*k3KCI<$l2L~qy2d9UJ zq0EksLYW^Qhq5@`*EbD;ER2sY4-8CAO-)Zv&rMCu&d$!y&reP+PEIaQPeWOqon4uo zg_i5{^Xuy~GmDFh%gf8FtE=nl>kA8;i;GaUmzSaJuC7AaUtfoExHT}a*WJC}*S80O z91aW|4h|j;43R@9&>qY;PYPTpS)A9v>f{o}Qkc zLo5Fs9zwY~KE6IVxj8+(Jw3fUKfgaef4JJ(y58Bj+1tB5JG(tRygfd?y|{QdKfk=Z zyt=x&y}rJ=xw*T$`}gnh-@m7;tLLk$mz$f{$E&NS+uMh`yN8E|r>CcvhliJ!m$$dK z_xE=q=`a9vlMpzGsyiv!nL4=|IGVu78(7#neU}wgCU^Pq{Rcbm2E{3k5++`f_+wT1mK*Lfyu)_BA4xbY>XwkyZy+o7_OI zyK;E6FYmw4+kf0UjJF@~eWXRfU{<C7 z(Y_ubfZ0PI1!!=ytxBxLwcH~}z*o)9^&~ZsY(gqDlt z2E@-?i%VRwYO$Y7z}OJ7XdwZobOKq3;Xd;I$7Muh8!YF47i;)veOg>kv|Uq2wBWdT z+S=Dg^D||9?$z=(7EzCSs8~|IvWK|)Gg@$)O}T+>Zc=?igAWYc>|?Go-LhqFJCO@i z`7@gyw;OtFOA1E0xbX1vSM2AZr10cQq*|&LBg1?eB0d3y8O7fnroK1fNYRGd;pStH z;Ygoz#n57AY6T?k|P`i8qH_! zI}xUNfXiBI6YHY!R2N*30|(Igwq;KC`JZC%V8=x4{|xS~mw z;prrt;wYB>GjJr!`tL2Rtze$DdQErDj3$Twzot}?fSbBF_I=pwL8aELM<1&Sx58%Q zLXhD5>-zeg>JxR1Qr-NICTGISvl=|=q$#6&+)xvDxQm&DPnBl zq_-S%F{F6mU$v}JU-MZCK3yz-OXzUjA5D92dWimE)=^CQxS#gJ_xbD7(5ze+3@t-rlHg!+oV=%~zZ{$pHzq!bQIr_04Ql@b3hZw#{+A z9g|ImX25-6Nwj-Ke|^@u)j+PA&blBZmFA+}3q5G~EWbrsst5qVi1qSB@x!Z$jC2}L zKI(vgi`{DPeUkzN3B%Y~H5>B-2w&+|o9`8_Rl*B;9^}gf%Ies2d}M;B7CQTVI;z^U ze24EkOohfJ4TIm$Rk50%4~uMj3RJ0L_OXBW-`23YzVLCNXFcjEbG^pTOKqsRqA_5} zR?sNDP*^agEd{N&`+nE(<{Cze)mZpvjr@GPpt5-w`I=MO+WA)YXksENtZ3TQ2i_2< za_!BoU$(F3;IPi{_ep`>Z{2v6Tf8vy*zgKIfBm5)hZI`4n*6QIvAUcUFh;X)Gx203 zZS{T=TIH?zLh*3?qbhma_gV$!NjBx6IZ+wm` z{|G!G>@W>17gCO&B7>Dr-a3}EpN3-u<%kGRL$zWREXMVniX0wwz__-ic)fCC$IkIBrT4S8_2LBPgCSDkvU`m%{-Vzp_$}#E?zVbl#0J z>DyXg|ICe*O(X=l2Xz=!*36OCmG9nAC zdn7z1*=vd@5NC*7O;r7qhb#o?@DTp90If8+&6gO}P^BJPw26m5R|#aElXJ((!2N^J zyXX=C%V(sJLa6Rxg3G)BT*yO3qyz2U+%#OY<-L^YYwjnivnr^918_7eU#87J3*D&C*3FTRYZFs)ZAj)Vq7!Co)HwQXrE6DyMP(y7A_ z#~p8)YU62N4%(v!MimB7l=b8nGQC3ja?}c?+b*vuD9AHSp@*zhnE@w$%mjHmM-#61 zG4&TLODh>2YJvnhTFEDRPWm*`(=7YXpJnMY{HWrgdI&;j1Z2BV6t8`Ec^lNVtiJ4H zNZ{hov_F^NGUE663w{Gx^Tvn}Y0T`%UuYD}UOLZEn|V8$Tj`}7p`l9f)=GvaWIz52 z9?|>bei)s%WDW>tuZ0{GN%<7mzW=Be6u@!~`_nMbO6?F`PfsoRv?oWWEo+S`W?b1b zFg2co20op===()w)uMqIsr%#Dm?GY5?8pKD1{X&(Q>@1+6Dmw6wbpAld+w}oo^MaA zwJIr{iZ^=^e*!D=sPK!NB+L3{Ov$D#m*$5@2Nnq1dEJ<8B?~mYVR@#ZLzN!kV0v^w z&bEqSwSwABD#iLx>!50qjzY4fA;^)#hYu@OyTmt{hvzWf(fu2#yZFk_zd0?W+!~Zz z#7s6WBHOo%M_itVlQoL;@6n^;H7sl{fUF8cJGbYW{6A3RRWp0BF3A z>;1(ZlD?%K7MD_<_$RbFdR`88ZFV&luCLqc?OgXoPsJU=q1z68;uHPR-C?6D)?7TA zd4N7n0MyP}U{UGyMOWC#HHaGJQ80v)(Fpg*8%Mn1y?e&qBY0*T7&bVa37!^y{;gJ9Vo_ zY7>6fHn%ymu(7f2+i4rGj{5CR5=arZq`$VjjW6k@p3kv*{;c353F7bnBmQOt+ z<~CQ%#>$H44vu3gfV8DC!r=y?Mey*@?KH0yL&tq{xGa<>o#%Yr`?RKY0+7Ko@33QQ ze5^gQro?qK`U7Ltd!I!T5WC9fe0*+{_|511+-TsO|96B9OM2M=shgmdV;fUwL5?4O zZR&NP-V^eMRp)A9RD)`O6tYU9Q<5oRle_*^b8_X-P%qZo60fr@f!5q0=Y%Gtdw`r$SXxk;#=8O1Vo`3A;v_As{Q4J}4&U zLE{O#taDXiW7Yx7+Q936>EWD9OE5F)qEdkHA}puE&cnmv$no{OglV8^fN*N*Y0V+? zqYkf6*mP#}!i>pBMn~=tyA37Rtt&jaCQsB zy@lmhG((N`5lPIkf-HmL*TR6HyJ%t-#N;Z>(j;>)jCN)_w&Ct)3G(G5|A@lf)LbM zeU1Fo>7>R1N8z|oy?ux~+zSSiSbVs^_q;?T;Inu6>Dn+ib~Eq&A^D!+vQ+aZ;FTw2yH9Zf!}(GKP?9wg>Qw~#GLNjXyayWC0wncOcD(bZ!1xFHKGnvlXt z5s3xVGStqT`sr0hGsC!+Kl=$brWP675+Ve6hvW^Ing&rwo@y#Xf-C;# zE_?oj&`5g7Axu11wK>MvOm<%U71&B_+=E0!=hnsm+k5JN@j-%SbQ4f4>RGu0dT!}C zn%O4a;}_U#mo=4ieB7q(q3YVz)rMMI=@YNW8XU}WJAaM3Iu|1sIVVyD+=d@m3TNvJ zV7GkmHP*Y@p~wx|dk}EUmeqy&kx?``qKI!2C)LS#P78H|yMQw>^n>$jv;)^!UVrJp zK}CYw+D?BkIeMXi(YTT4K`J&UvGb- zS&#d6{&MVaC5c6rPe`kOITr4Dzr5ciT?lNLUnO@HNB%C^QnZD5m3@9l9gLA?ZNQaY zk@wD*50U*&oABqPU0+!hU@=rdX6J^`#O+E5vmCfOC$94v?9INIr%mpDw)jAocLBON&7U%B8K(AMXBmllBO=TZm zPi2$7NYBZ}n{EdVv8k2ivpK2)bQHf96Q$$00TZ>$$|wdUb$;_lywXn{#@H%igDfn< z6OzvlvDv4t2PIc!j`G<*AVp?HXvJ8rCy+4_$5V>LP&P0jz9bdcfqK6-vKq&x0+bVP zSaizPdE8#Od}10&<;dEc^KOH+8qwEzQhiuosc}eujezux#8bf_u9kcu3dw%Zp#Hkh z7Z{R4<`OQrUhx)JCn_}$DSVQwf}fTxi{{ZkrffNpKvFTsay7dL+@k?Uk0eW?6^R*wTqNdDybz40t$VM|6<*H)FsPvbXuN)WXI8+h4amC;0d+J9;ba=>~jULSt z5!P$Gq;-=AwMGJQZHX8%xuoQT@^}B^(VLH`Kc-WvmxPOpOijr|WOp!qhhjs!kWbl< z%<_Wx>%ql$%~tg=`P5^J6fb0Q?TYS(#4&WqIBQ!PpG);N+b>Sv2Q3olfU8-rSx-rg zVkiufwYrm;=T2Zf5(E@@9vxP-M>Voz+|xHoTtoD){f&&8SAU0|{!?G(X?i}LXd5&Y z5Rt&(%46m-0JvD#7Q8)~Vz@2>gyeOc4YNZo^)f2EGWmDv8(^4TaXSWyY{|bvms9p- z8HgSHhp=Jb9{G!8EsXOj&TIXoKzSC^!H&*6hRXR|=rZdZ8{@%M!QF6-qH> zQ_M^9!oV$5ROib;xF(@^qOtYb7oMDx1v8djCk|7&#U1chj)d$;DmzYQj%wY};tJ>a z0c^sOQg0fM^l|Y`6_Ng5<8QH%rK7YMNK8 z*LEA2EyZ2wqDkN>(0u@F4t<=jQE?b4c*Ozkv@?A9CbezR`;FRq&H%1qXSk zd*(Bw>E7amu?aw4}09As=%U|c)(ZxToq;j^tZJ)mnp751}&`Q*<0bj~eoudNhiMwSrph!C(qn!psR<IEP-s>WHYXtTN`a9kR9y3l5z9lhcq;-o<5bXwV+8?%XD{p2j_pVk6LUxEO~Z; zEZ@$o0#?At2o=OkL#XAgYC z|8QhCf`*p>KyrDkx0sT{xK^dZ$|)YjR!;uH1^`*2s5d*fz54zzX5Qz|6V7KSBSivg zX?4sZrwlphdz;VUmQ<8++3DWw_(7*wM`wQ~@%RriR&Ypxp(1fyA;f@a<>A8qrGHp1 z!a{Bt8Yl=*SXhn7R5^bAmd&A76*$*%UA|U(2;_?t)UuH{pQ#`hr%p%50FLyg6Go46 zjZPDSxXjo2e@iCPTx$1MLl-A^1orR0>f+(jFaXtO&4Of6fnaHYi={$-nKaolfQ%a# z9s1FT(Y-_JN1lACx9RP%JHMFl+QJqpHXEBG%M;ql-=MA!U2FcVb{aP`C}{Rn1jAnG zidl**`JWvUWh~(nPPn8~UaJ1a7Ba3|Pkf5h#Bi8%U&GFZPL)T9kwie1e?bs-;UVi< zsq>VaoF>AuCIUXJUH>M15_KXYVS?TPW&8 zfHeqPUcSPuEzm|GxL)1==D`3q(Yl%Wk?&u!46^R+Q!uDDuH5OPoDu}iGpH~1l@48F z@Mxw)QDS{VQPR?CSsi9h31k_yIbjXN%<7Tce+@Ci)QnJWPO?emqKhfHfgSP}g_^2r zWuw3LJEwjYkswgZhc?gBN@}d~iqT5yH?iZUIN>4F{dHm^!2gb~n=&|}04!o5IQ&~1 zX%0Q_D5@!s%&{Q6;_hQ9^GYg)qT#=-_@HtSqYin_?(_HRW|_D@k-uFFOs;);H7=`_ z))*8^p&iGhtO_?=uMt1?g?$NxcA!&BX|w9@epYDSaDq_O+HF`@Gu z-hu{d0qIgRX%p7kJJj+(2DkplE1=o3LA$V2^csmC*eB@fcpnBR}(_NYB_< z`3;_Xqz^J)U2wxuky;%Ntu_GnPg<=Wj~$ZK3}I5rOPgHa_jO0o0#YP_nrblkDR>^} zE-3V1Y|%)4o=-M*jj+7z{C83Nr!jyrHu)2Ew#+vfv)yBhERqLs=d&hPuifIZ<|p#9 ztyOnciS+_|{MW=drpftq`#S{Gl93lM7Hdp|@b5j?A^wHy`bNi3756HQ|B_Pt8I?eUpa z8r-umf90P@OiCZlYP`?!mY>sbW}Vi?!$6~in0LU-fyogwkF6oRODa{OPcp7|m0_1I zHt{6El0%gFN4$0as%^{4id#@qDot9S`hVgaXZv&pD5u+(!D?Z=)_`u-S!UJ@4Qg8+ zs`1}PlJV?Ilbq<@N=P;!mu9RwJ~I*?6k6F?;vE@eyw}9O=oA;u;?mEGnHgv#P~R+8 z)D$n8UlU!F$;BLE?&O$f2gs?$TGqsla}?gWGx&oKy#~k#5EUp&JCmod9hp`~Ci?o1HC652>*x6^Gcqg-BQjbkoy5EbK=?MRpgMM8V- zQW00qs*K;-F=sTG#!OPDF5h$2xvHxSaZZ@xb97g41YSl^i0NV4fY1y3a?ROc$Y8e4 zknvwjc!8<=hHA;%JK_qdR~d;TG60p{GfJRh~_U3$7+m6$aQpWuml5e)lNJqu0>hC^(>Uv{A%Y>-W6tI&2>f`;A#3@H`TZN=iMMHTN-!DKNn zG&=JqI|$+14(W(@yWDtQ!2!O_kY9eU;ZKA3I~I#f?E96^EtVidF#q&7Kb0-f zacNwTo8idAzW5IY6t!-|r8o#WUAB2+& zN*ytjFyZ*>sx7z|%4ixZ8|mZG={Oqu*G=&54`O&FC0CE1aRm4Y_`XRtyn_Af_|>^2 zv>?w;_4$*`{%TCtuY!)eL9-+$OU4xeW=kdiv`!+a+gp~p*zlSB993s*bE`3_gy0X@ z3#N2|14J}Ip`U`Z09*>@MxiqUr6@R@KxYMzWE_(2EHEYO&0DXXG`xujb<=(#x0apsOhLhH zD>8!2AKael4@;GrOGvhVh#% zcYHhW+V6Fq`7fKfQUo4P(j&dlo+N2#Cg)oQC1g$!KKfhGhfob; z2EyTy)P_!RDV2S2)OHESbW`;z=s>4zvS*C3D}noO{A@x&HF^Rs-R+8`y*90fTSxi6 zvIK&{zSgmSnSn*pn~#zW{>a;irUT`j$vs@UHJ z(#IrVh+~{PZ8q0$CbW?mRV?6a?yYa*$Ex2B8U6|&TEnq3fhM(x5UNm&qP9a$Eg1EU z{CNvH=GL{m?#7d@AVJ1^Vo7jAZ9E2W}DBuD^V3Tyed@3g2j+$rGWBaJ(9S#%#Hq%=#?}JZf_m zE@3B)1&%7;M(n}xk<@_Q(ba^x2k3VAdF20+HX6|}9WtrlD2^2#F-1kJtpKh~{sE(8 zV&_zU0e*dW%<(U%j}?$@qV#BZgm(S7t|CR=88zu6saRkml=xQ>avw#b zR^!MOu>CeCP|V}2)yN}rpbEbjFWN4$9SKYlUR?2Xa$s8Ha&oMZThbvb8>o2_FSKx| zDeIthtnIMir2k!Ac2k(IETeT!Ca zNgYqmXR6Y_v!eEGd;#=gqzr4&Xy37U!o6-ZozFvnv+SqlWn)arw65e%54}OZy+~+* zT;wR-^!FD0mSgq)rT$pcTOq?bmLjzk&xmgkwN?#k;bY_5ec|Ivu@XPWeKA{icb0e@ zK_abE?v{5!(_B)=g2JXba56ueAN@3a5@I%RwZN{`#{v7(rA_i#qkn2b>aY~#xj`a+ z{*z3$Iu9dLndekVaUj_X8$)hWy%H^;tT)~iJkBD4FMS{%nF^v1$ec$BmuaL0R;#UW zuW3YXWDOt9NUq$l$+FRbf#NGpQJc&zzua0x{*o9MF4`&?e%r_canu@obdI6VGXBc9 zvRIaxEhb!#raYNp*7?mm8N3m~lh~)+62)gTBR+9^4X+FRWS)StIUCMseyYNWk@PoA zQ^5n$j_JL^`|J~7Hcop`)Z8G@B+HTwQLso! zaRcCyZmWMn_Z@=f-X zP(*4L@MWk@P|MExTJ;^b2Q!3<1f#r}1^A_B2DzJOCG+5LzED>jt$`>^Nb{d3ftO3Y zXKlv$rU(iJ+En@wQGgPv!J4V2qnqOuuR{J$LBI0FvoC9Cg^>+1_7#z*U8-oyVuAHz zB;?;YH)Pb0ik*oq5BCTh{!;;IWK+LZlxX`4_LSvfDm4bwCXp@6O3D#B<)|^{nbv%T z={z`>6))T$3z^wib`ArPq>kqAS|^C*w3`)|siu%#mBUr}ESA6xyb9%J)D7}URppJv z*e?mt$oR$Na0}NAgO>i!ZoklqqlzzU;N~H;*<1~J8M%L;qQ)VEcrFxF;uzcYJIz6k zD)yc{0TXY+kTe^ot|bI=JJrVKG!>rqJDKTMwGTjLWaYc?IeyIXIIB+y-n>^Y2@=r< zba~1TCMzq9-QDF_H9Puig|;XG!T$wt*$uC zNsw_^6Rx>q!VNYme^Q!e>4z9|-nR`-ZBguD=wLyDa4{WLEu9%uP$_UHp^d55Ns7a> z&UYXUQt|d;qNo;){fDpdRYXa~ExbWydv>r1Xh5=6dS;@d9j~q9QHWBweb|V!VwXw^ z5a=&2RxG)Rn7wHF*V=n(0^2ade>bY&{=WK(zjr>{n~LeIo9XWE>@Qq>*3PfMackC& z#R}V@FGCcxg|ku^J$e#4U9!rs0EMJ5ZbNa}5H!1OJu6R#R@%fHoPtq$m&!4FoS0RBtLa#dIW#a;nB$ODP4 zjmgBj9`I`l4VWVkoZrE}d051EdT`g_ombHmz<%|yDiU)?umWpKS>0425d|K0qqa3i zzYArtJT#Wda?NfmREH?;;qP>f;;D^nd#yp&(`nm!hf6Qm*K2oD5>b$*^!UHjI zOdaT%k!yKsO$K3U(o4{RWlHFaB~FnkB~cMD_c1+n(f@}+EfRBj)8NI+RFLq#p=^>6 zRzaPsl&_T(u}u^XPmFob4^N(S*3dBw>*@+ZdaA7!4JN~GOq1Ar>@~^WJ|A2lHbJs7 z;4H^ne%$E(W4%F!e}R-2z@#V;ax{u2c0dki15S&^1BS#a^kG=XDg9nq zym=)fPRd)8l#!Ae@gKrN@KDDxc~X3l7AyFpV7<+3%73cKR%+^PS#-C)yJJ2mtgizK zZZ^*SAZJNWY%Pq%6SL`OnoM0DYodO2J@$Gv%JufF`dondBc`-62e$ah{ss>p$V|Xu z>YHH1>lkQQLfwov%J*GoK)_&;E5DrGw(oau;zY_HTysTy0%Wh=8)j_)iM;-0H%aU` zJz6=FgERUaWmpwt$e{L8iMnJwTIUO!F;*4k*Hdni>meUe>3M*sSY8g zUH?uPX|o~AIHupd_ylV`<f-M|S~cnCVY<^{uxa zrb!M${lK9dfx{6)KEe^aN6%Mn%AbFZ;+IJB<_lU?Aq2um#nOeIrdfV$jP|xn5g(&O z<2vr{^S7ZqBsVCT}B@`FHNsW<|otQ3G17hb{CRz&&4+uLKW`jJ6}FK z?W@bL=YL4@sh0TP$I3W|5AYlcj-O}zlrs+w^4@P2-nRaJ0VF$6e?k?~b?Y__U{Yfz zpSykAVzCOd;Q&xbXLPeE9^W$ehfQv%mLo~l`~T2t;(9{Gqv|O{->(uTcX%BZco-Al zxcj39Fn}lxqQFvY{e2oUwB=7C5I1!!LMo#kzT;(Pmhz2EDrEB-4)WnkZPTOE2K;(~ z-g1~e(me`3EvI$<)E~9rHMzw4z4j`55bvrJPWS5{#mP&Lx!@i8R}b&Wbx(ny;1 z1j{44hJ?gYQ>sf;eF6MD=brxf-g;9r>?XndtvV&m@8}-B7Lf~o%L3ghK^Q_-Yu}UoQPm_!rSxYR61DuQG^Q8X-cH`8aqw&go)v z@Q(lBNp034oWF3On$_evea_Efp2OS}1s8~TewaEul}er9+-gZkGTAKYExu0U) z3?4)|YD}5Yag;N;p`)kSF*p6?#r!?)D|?0mjzKc@+X!UT+F%>;BUsPDM|Z_fSz9hm zCBawG)`*=ug3#b;9VWq?i|%${n4CD7`chvvF!Ah#`ftV{N1x_TX@EbFgBW8eC%wRO z_>jXo>gk6O&)}ZOM-l<8SMl1sFijJ!ZBr8^Cw0kjZd3SK&r!o8z1r*RK&lBvc>#PR zOyFz)G!NsxtB#O`%QlY#$H_!u-=nzA@%q|nWPb3Go^XV>9NfZjD!>7M51Cg!ACy-n zoE~tyd6Le~JKpsWDB1l3K$DY>8$h@F@hJ_=Kw}i$We?OO5qS z?hyeO2U^XPfh?T5>7y!5Y({s?J}s!UIfRl?S_}BeV%99LYVDUtfDg|;IAswO+k>WB zW38~~PmOJ(On6%}HoDiKm?u%JugE5faWFQ75`ToNN$B}lCJHvlXU8XKJ`DgmF|-g1 z*-Hk`zE^p`SG)=LVH%QN%7{tJ4ZT;YhB);ys+(spE|HV`3oUHZ;ZXtLSI|}jm1K5!sabqn)jYcwUPxd(LNH4Qs?mS0u<2GtdJ}^u>A#X8OtnS z;=*P-4zB~LNu!WoDZl1A?>b<_ifZl?-D`oZgBiqVV5|B(uXk7t;F>P@N&_o@ruOt= z1}&BE4m2aGBx|VXicp!)z!W9JQJa|Hk5$lNi1lmxcA7UQk|D;5Vm0$G6Rv|F^F%^i zrL?ySeE(2id`Yvtm~!Oj1sKfPIT!4$N6MR|krn@ap=6CB2uw=Uh?(6?olVz3Eii1* z19&(f{LmUAn=xY29Q+YLo6rh3VTRRvE!}R%;FULlY*wD!G8gf4F(i~qD!_1ShkH@p z7;BTy;D`QjriyJTa}Gf=AQ4&O+$$cFVPTP-6(->woVVr9o%al`gNxU#?FTrtSdsmA^@VFV(nouh1R2IghtMS92ylUCLxiY}X{Q%tab%Z$J6)yr zS2!o%YKKH1T;IZZhAwJB(>;Te_CdM8Dk-#@e&-VXaQblHw{ohS;9nMlGG7=16j-*J zn)HaFE!_15IgoK3*kgtUEAblv5`(0ijg--v-&D)!c*%o9sHB0(%Jn@ZPF{t#HNG!@ z%|@a5PH3Q*pTZIhbte}Gk#%5tKQs(~QO5{}Q-&cHR7rID3KqS9?xDOr#xI$<)UwNIu75CtyD7(h8qAG#C8JAPFCF8+4duias{N5} zRMY1t!;9%6Z9aTLTW}^d@;w>dc)nN~9&3h?3@od#$y0I?r$j9SchO3AD%<0gk&nVq zaJL)(QFc5dfTKMbpcz8zv3))B;%5N(^VI_XV(Kir3kJ}x_|lc+=!_J9G>9_j6YG{Z z{<(0G9MJ+JnxXcU;#w)@XJo&L5NJ;f`}!oNnZnU${vDSjuBRvd(;edL`8Pb_Fh4aE zE7~Cj5Ho~;fGA_eiDPw(>CQWRgVWWM8QluUWWcTYuXW__%qd_M)SQ3ZYmv5I>2mg*oG9NsA1^Bx3yFbJAF-wY#gwYnm z6!t~5j12?+#u+;4=cp&)z$c%r&tuEFN6!)`;q1y!xy~a=s74xxH|ll6(ozH5jbi@| z%F2Fb3rQ$0XNqzH*&DiZoc^bzGF4!@X=1~pr@Nta<9kx885 z1rt@Cx<6PN6IugmFo0$;Mqt8&&EG?Os4MLQ{=ES$m+5msqR?g-WjbyKhuMkmj zO~T|SX34DD@gG&cNsdhrd%ELMJ%cV(542fujah|1j`us3C?8lUM_0t~AlQ$gOL!og zKFu++R+?l<#<#UoIIE7}(Pk>9{(~vO?OsVyN+ZIdI{Dp$Fi`%ripyeu6dY>(fnxKp z?!xzYm=t7!1rs~o45yej)lFgleQ1|p51KObL-oxRTL%&L;VQ95n{w~mCy(D{SYgHP zl<1p$p@r1#)yJb*p3Ou6K-#gJ`l}Et4|Nzmz`a>Ru~UK@)iYFq;8Lt~_1|ckFKv?> zKT9(GIL31H+qX`nJHu?&-iMbZuiUEN2B+_gQl2BiF4TJmf8cj)r7j(R_FhS<6STQU zd+Gp4tI-9m5Dj}_|0FK8i?ReDeDclGBe=s!s8_sP5+;Z}yh7ePc?s9YwKMj!Qn!9$ zxVGjOH+OsLbcaaeQG##A1yew@Rp56lR>jrnE|X?$fMk>~;xiz2xSDWwQ`QQMs#rirqSTi$V& z1xR2RQSH&%+!J6*JTO+Cjn^d%!0^;6X`6F-BpGGO*}?q?66Zed`ubAPdHwg@<_mYw zmIU^rMFs9nZEyJ7ma?fv69FDScPgodEV7Lo_*o7)np}!gL^!rfghDSdebMcy-=yPn zS0uTFE%+Ns4weogS3XiqAIBT>5vB}3Iu;`W~qc)WcCeJYe6w^y1_dCgv3Z7Ld5_MJ1zyFtLH4l6zSmAQe_r}JrA(#UE_GpiSdR`2Ue{WWk$uqizUxQijD7iBA(dfw3w2E41g&IxmB^nrt|7I;bG6sL_9YKcNg6TQ|Tds?(A)xuQC$_yJ%F5WM zEA+b1#!+L88fypAJd7tfa%WiMRF~Q~*xZ2TruM5fK$19C_hErp=k1@u?Rt=vuLvON zDr^LOB>KS0cHC;U!_hUmuU1yKU#;b%o#W618k!Jc89p!;Gs#>Am+U!z#8(3M((#K71jw6>?YbzH>I%hEH9P6jja#;jqT6`6Jk56bQvg8vq!#A*jnMRItfgzn||#I)Gz-Gy3>eBP`xZ@{L2sHbzCDyiyb%-7ke!gs|F5EPExZq{`)$3@TA!}_Q$ zTT2q%3Xg1e0Y5DnFhsY9Yo=l0e^DD!N4gT+QC_;eu$;Q~UGUrQ4a4vKD7k&csa;lo zLJ_jOB*UDF@0-a`1B*Xmp;yMwCeE8VnD~l?epIYI&RMlD=e1~!F~(&!RdR5$2~Vzz zFDfoB8hS7WdL0?RD()V|j7Uk5kSwI|#E|f~Urpu}oy6BI>S^)>y-S5=LrBr59a%}6 z+ni2!r-zKVTpelGYn*rU36p08=Qbi4qqkNp$$5$~3Xo1p0O0d-RiW80|Gp7^wom z%@$hjMk#&ch({4~PGTZBK!)xJeO@VsB_TL7Xd(}Hjt#&#IgPIomZh)tl{BgkkJ6i~ z+TIXMig+rKxy09X^a)=|KPn`b7=8=$&e<4Kth)n{&lwV-;rDy8iD5Fs$BrjEX(6Zi=jn;UNbar^7N%#z~vytQ8cC4dZxr%PF%hEE>%P? zLi*k`y$_~soF;NE_~-Su0%^q?vrZJo zN;_@gXLmcVh4jUy&)XwFo1y#sTSUu6>+ybNCvA{nvsT(O(!$%BYeEml&>r+T=F95v z+ec31iGzues4FMI1U$>%ehAUw$p~F3>GNE-={i&geCdLY=VOckX!vGWC`~5Hbg0s8a+7BT#SSwgza$gY573-==q$vOoR#OsCDZ5pHf8m^{X)RYv@wl)Q^V zG+N8~tZj;&Rp7IrW1(KvCYIC4ukPY6G#X?${kKISnXlIxM9<-7608UP?V{zLZ2X=g z^k~mw<8x7`R`RY^<6CmQ`~U-luL`-g` z?HPH6jJ(7EGcrP6!Jln=-ru9{;v`_SZDij|zOiGhc*%M@0!;x1q}TmEUb!B|ql9FV z8{x%D(Ib*V-%d|A>Y^HP)tn%HA;ufttGWH`wtY3Xw>510{OxUIA043@ww+TC`Y&(V?vww0 z!nfAdQrrEJ!7JobgC5Mec}7@<00_`qk8K1KA&AZvft7g^2xXgMikge&Sk>KZxRFJZeX*ZOdF$+jU^7r?ojc)%pQDggjzV#-^yk)~87}=Z+mMT%GKwJ7+iC!H09f zPxkB2q>e`)mz1a4#s$($HL|5b8XIF)nl$&IjY@dn1{Vo@7U_Tb)nEP3|If^*I{C5K zTDHm01y|N65$n!r7euXP`stc2v{kdSYQ(N!E8W&F{;R4eub6Q(Vtd&yw3Zd~)D)n# z^&J}x_nq2EwOwsSgF8{W@11i6ls`Is`FsA07QRTe?bI9eSY`7PCfk75$rw~p)Wc9Y3cy@}NjrGvB^zbnG%XfBpRDK47ht{`A~PMs@NP9Y_~P%Ew~Cs z;7wS+`?B(7I2}%$jhyZH^3u|mnVaF4J1!skGIchL*Tb0*|DUE_g>W&1Zy2^gM@yt0 zd+<73>X?9c;+Lr#Bis#9>m+Sp>8!#W5Y<}nV~o^Klw8M_tT-wbXEqc`GmbFgI|&w` z`2VUgeT^4HIhe75twKW50SFbC_!F>VDIg)NGNylAPZ|v{)@bTUFV`2+I;`!T#N8u{ zYKiadQ~K1cNd3{p#Xcn-S1z4|Lv%fkL@vQS8e5UQjAXA8S9UKp;ZS7pD7L>u51xb% z+0n(OI5rmR;V*ruFS1DM#~1f9!afBKh=;UV@x6zX$R+LC_!+UxYd*T9@RhQmVn#g3 zXT0PFE#C&uDd$h%g=9@TB75VmQES#xnx_SY6-@z2am9=;Xz1?oOrk$UW5Mg!qoE@m zeGO%A%!$o+kP3XHO&_uLUZt09U#ufaY_?aqI7@mzJ~7)En~l}Y&c+&NpCYrQosrD)C^(K_ zfnSO!>!2rs4nkzK=hW5fyo69x&-Q)U7i6ZBFo)#C?qqGS+@i2Vg~UotMLI+`sO`@f zJrz(%;$$4+;Bxz+#%9LafTNiiI3Qk}xw=!K4ujNVu#S)z+z4mre-IGrWq6gIpgZtJ zgj*p+2WrStyf1>-enr2gw|fST+(T{UhC~c^%D6sTrSPE!mIE|RDI2pGv{=GYHGzfv z%{fUT9hfKG4KUU=O?FOC$7)Y2$EV+AE{AXv+(|xci@}W$CmN@Z!`U!4J-rjoh)3X{ zNdMC9ozw495zKJ~eqqXy>BbnX3Fk!G1ZsUqj-v@|pH@y&I<*$P99p%@ZhYg24o4*% ziKFwe4qX!^eRAsVRZi5!PXXR<$gHhw4Kwp2_cB-Zkv9^LahCbicD1A*QK3~zpv(*v zksFd0x-!($ZFBJDB#E>tYV&3O;g+U1h_$9$mBw1-g*1UGi==xkNd*Vu4W#*v%Jm3wYb`#WCYB+a0Ue_y6Z^O7E0YrI6a8E$9*YC_@|wWh#^ zCb}}z(`~b9Q3sfYumNZawPGDHt)WJ#+$yPJN!6@RO>I9gHPuR@`1?jJi9V0NQ&Y8X zyd8}mu4U(<+iRmeQ&Z1JNi(G;+bLnR8C2T|Bdw*!Tj}QWQ&Y{PdHVs{L@TL%W9q;4>UGxE#y!uYU>cb*ri_eJ4s+^0_?1@CL2YC~H3waHS&5fe+OW$>n? zT|5l#D_Kf9QlB_dhoduPk7+lbJ{3vB9u@4I#SCSUe%;%fqST(EXyuGc%&gdq);%b) z#Em*hA}!iCdOgf+le981)vVu3Vfc%j*9Gxk5lVnEk<)M_Pbuvf8L|LTo zO1vL4Ny?kekRfb`lQlLqAqi|T?_j2D#Sw!LD>p-N{R-Sj!13s_?_zpEF}y3OT$!NH zdNXO|$RmBRNJ)=A9{Hpy^}>AUBrgC<6WD~r!EIJ-F8M)V2!zr=Q2wY`gb&9zj5u<0 zZYV=eoQ<9{%B*wzgkY`hIR=UMBsCezCAq)|c|wBgM;s)PVqv!dM+EMvHG4+Buy15f z4c*wt5*SA`KblF9vo217WrYVK8Oke53idRjKLLilvPeFnv8@heF&nx_FGDaPagdpa zhpJm;?wNp<20M+Pm-f+(jVuBABNp5G>t=j-38qU$-0tFKwf%y9aHqzR9$6$mQM9lg zb2r2eZbIU~Xp5PJkIMWo!O}k3vR@(R5nKrC{2lOD^~Npxrw*)N1CwG=nYzYbHNnn< zh?_GaA>5xwDUy#UTF~&1^20C~pG0-B_00DhDmb`>c)(E?sks5yRq7M=Y(vyPGQ8Cc zjH7SbL!^5&$XQDzB$qmNAQil_NCoe9XRtTQ6xW7b?H*0~5np%`+tzx((FBGi6-P?L z6W+iOfI2XaVCDKlOQ(66*jUy4=#U(e>_GC$B1x$GEl;yHq$)iayX{!0enjp$1kH#8 z*NSm8QuaS3EtAaExrO9lWp4+PM-~b1 z+S^cpka(KzEN9OtY-tLMe~)9axdHKl%^gSQZ%&ei$(sO?j-$5@OdeLcy}`jZbx<79 z<(loqxW&!ny-6rboQzrZDs~`wW0B<5Yw8tO2g?zT3Q0@WMeB3W#s8=`n3|}?3pO#1 zZfly-XzNrnH8gvBijX%D3^v-@rEK3G#Ld~0gS6eQ)>}USNA^JbZt;5fmslB+@z<~c z$s3F0Ni6~x4X}VOdKq(x7DQ(@-}!2s268cuCN#T|gU4ye>E;XR^b57ej~`59|2W&- zm}2!8@rI&e5z2|zY;}B0Y^;stgdtgv=uT`vqAb$uviI#xoW0UNU>+prlg=wL-`*;Gq+7WBLkTI z3%RSGdK`U^I~Mqx*yxK#{0~OkzW0g)QGh1Wkm&E%DzO)J9FE?#M(l!wHQZ} zo8bX%zvh(Q{r>GnIKhbBG95U*bE+(H5pfrW%`y2Xi}ae5BNAjhGTc17zp;MqBvx=t zHi=pR!XgR%9UaD_jdxt-U9sfM>Jvv0Xa5!l6}~4n#wNJ>1FVmlxmn60eN$#Yf|rn_ z$hm;HBz!opr<_ERG`RMVtg6R)%kv^W{-+*Czr|N@`JdQW*Sac8toiA_5AlOcqQ5!W z+_aEBiqVpB(zXSe*@O!e2V_9eU3+n{=s{HK_)haBv*fcar0}YQAi|M zq;bjk^{XZ6BX^W@^kxX4uoW)Y9B{Ppp7b0rrAyu96Gw0)0NucMQH9P#rH3zx87Z_G)=jYNm#<|J4o ztfkz-kka+O+$}l)iAMXEY{h&n5j$X-@7A)Z!J%=g%k$)OgTaVze3jwk9g*t-4wX+F z!HkWMBdaU1?;C>`q&Q4k-Z<>3EYffPzUWf9ewr51d7Q|5@B?rFl3#_bsL7H%Zhd7u zF__BIuVF~aK%&$cD|7(kvTef>ku#)UpHCcNG7;oMcgrR&eP@o!5|eb9vPiF4&Be>t zQN0JnLHKDV*Fi7(dIuoUP_}MEAEyUI&NixR+iC_5+H?94?5X(z)gTKd+kucm6SC*= zkE7q=BSOltRu)WRe*h|x9MiiLs74XVkyIQB4TN(2nH95{i0j>nSEWAvkVMOq{$f6x z8W_s>GIBaZH$8%sSqjSgu3kw7HnQaa!gJBG(~^NTjm9IQP;;@Ob=B2y<`{<2%b!_{0(P zYa+*=Fhoekn}k0=cCCNNHk{K{wkq6)lExCX!t{^~N5VYgG+&74)jB`KH@m7oQzSd9 zlB1JZU|(It???&O7)W6|DDx%D(fG%aCB07JuwbL5gQQsNEMfm0yVrLn%; zJQ60cmNVU#y+OukvX^b0<(KisG^UmsYeUl}m;q>I!6~)n0coeq(p_`I4zjbp6t<;4 z%V)y;5dI!Zw`StnfAXF-00rv8im?%moG% z>biu0sRkUu@JAe}!8xgz_u+`upwirad*YEbJ@n>}Vbdn?)gI^{;$IXahc}^~sTtvd zf=-sMZn)*9=v3C9;DsO$wq$XOBqSdpM&gzE9FKm)^E=Wn=abX^+17(@Np~M{AUL#t z|9*Z}-$yzH*?u2+#7`RFhyN|@L4}N<{LGe{Q>QZi*x-f)$M@@6*;_yc7cBY2(Wm(M z#ax9SW$nHzo1C@R!{w)ck@c!@(I&NKQ&(l<>Qu&mr$JUM?qgXs;HU_8M4S!H$IN^9 z2i1_bSNa~*cy>Zw+hxtR1_+f`Wnvr!Fn4!{QSjBEaftFc9u<)@hHp4R8~4s>|CO}# zE36K}Zq|uHMwrfQ+(mVMIg=b5OlDThXZd4;$Cw0$_bLIS>cA01f4?W5G99yu@v1#v z4cVW)+`}j8Q;3)lI9C0k15#Pfwh9RKCsG-q^$HgFw%B|Lox| zUQh=lp}LKX&@qybVb2{eh+2d`mlU{-*U5 zZ~wduQK&SkD3X>n=5T|iABY%|(c3ngK!ptUrV=rxsHbNlkt_B#Iymh{ zSixPO(7QPoId}K2x@#z99OdT|V@V|K8=teR=(CvFWPQXqB1fkTf1)qg1B|L;y;g)x zw8O&RD~EKglo9?MQqkXu)2z>tH}AZuM6iMM^2kgtE={0{D36*6B60KnNkw_c-h?TU zy>>c+YsTYhbM$V2qdWDs>mR3!wUtZ?>v_1i@>gT9cNvuQ)aKyG$9UldMpc3%Ec{=0 zWFptSNcG<z5hLSv8yd68mAtu1Dh7rGM~q zot?ySwtrnC#%2@7m~!5EN=oZ?uw$3irnN@Zme}#@^loUu^)2Q2=nxQ;$udq_AdXza zfF$W`$muL^oB_QJPcW(y93euaz}!bimzVG9S}7%bpRyNeF2-4#ee@Fa!n7tU80U85Zu%m9dliKe8q3Se2Ad|4IFefJ%9*rr zRI;uLd+TTH4MtUhBf4O7NnP!sBd#szrB7*Jh(+{0yxB-Qc4A8GXaq;=B1dCV&A%jg`*0pqq#n%?}U06#_~(1x0oO1TR*@ET44KR0Raa` z;-p#pdB7u#ssu;HuemVVSjgC&JVZ0$wNh}MUZs7O5PkPz9Z{6J+1Z%VJKK)`vlnNt zk#=l$&ayw(NF6)J%2TLH>prDCg%h#aPMmm3xya7#!Y^(18fl!3(ch183T+bB#B8H- zv6o&4wPp#8M-7rja*Z{K1oo_oxx8Y26oELBnzTuIiE(h`(cRT6jH(4k-*V46B>!kv zOTh`0r^J2TTr2ng6F`$J+gJL&JtN7?~U>L=P*YI=GSbfm3~ zHiVY0lASX%04Tw!HZnsmNUN}4G{^qaLa#{=0!OAhQqNj&R1_G2QpLZF2dtex^5`t$ z-MY~W-{C4w^{W>t7Jo+~@Q}12)-@B3>gWrnue*@~io!z2QH*q6B^DfYDxLJL*Qxk1 z;b>=DTN?ld*eI+3K%Gh(TE9wSM_vwuqf?fy6}Yrf#lMWZp&du^A0fRHUXps3mtQ3~ zLI`bpNPo+%=Ve20UM)rX?onFPPb#rn=|<&Xx>;#XW1}Y>Bk6Q2en~8S0R(gte;U)r z@&6q{deR4#TDEfw6vshvT#4b>3+dL@Tj>iI(9n}TJv{`ifEs`4RSu$&R&1k2x|Xm* zY@7b4rCB+SYqa8odVO() zOzTn{(fk}ZR>l$Ik6J0>(42-NdN-!hV|!u&iv;zEgb>LtyLL!hYrC``7*z|7ik#G0 zwg(j2=U6DOma?O~5j}wIW>MW1 z9?-mj3eO`8j5&eJY5SMMA3@gO_T(-^vg_9z(r8;R?F&X#gCm$k3Sy2Jo>OuXzUm`$ zQ_F^BhvMB_uN_AM7HM8ah-AZ&2R7RujH(7l@XdCQ@F}!BHNS?dK5`NQM?PwWRpnPW zGr2&}AtOYx;YePZ?Gr{-gCiGHHm#q<5fzLt;;N4%&-=EW^HD3TDm)wsUX6qh$sWc| z+GxZtjEdeR1r7^9|Lgvun+cM3Rk0(y;kMr0$fWb3TP3ob&0063Cjv~hWv`@Q<{y;k@*Dsm-eREXqkiDbi(td0MwRFGXR2xQ)i z3wp|@gWw3JBcfnhrt3@S*{+2$Mr>pw=lNaCXOXB7$uTyc4M&m!lK?Q1`o1>=N5AK0 zI-=c$#Nz+n!_fsn7xNdW5F$C|jIh;`(*y*8QT5=+&DOuv)8e30I>~#cp=1vg1d=`c z;f2(gkJniCH)v22;fU|`LoJbFW zi1HG5ZAG@357*R$wFL9j&PCyn&s}LzOC*QrXI5TCO6(R4MzU^ha#LFn{-}toM-I-} z#v5=`7QJu5(W%?FA6NF^;5mJ5k0U5=p1aL(^rpH?_qC!PIQOO}Fa#j}4PpQCB^^VK z8EmcWkPLei5JpvmBc~{l=5BTf@X82pn8brj!q}~}OiVN=N)(%<0SdG$6BADmrGel8 zehElOl#m-WH4`ml2cdKzC;JJiZ9sWb{GD+at+uE;5UdP3z?WP4sJ6c+zO4q~_N<)j%07xk<4a$y*D}?Ni0x(xdbU%d?z*933 zjZU;En$;>ZJEakZU#$Xz^Lfe zkHGPPgW(9_kHukYZP#@W#2awbeUptZHwk%bvWDE8+)>6+7si?{3{(e{=O%eL+Myf( z{x)Vjy6XJp@)lfT(@2XJ#7$!n3XFwL%~LByX0lit{QxG3)Eu&8s%SBEq}GeD zc4YL7=8f9zT^od>_g%V|w?L&CbGTke=6-PzW`_i$qW|cVoJS9cBUx3geq~WepAoAW zy|4X)&BxO(C{OyT>$Q>^vDTsRSR~{a;u?^c#k9`TT39gRhVF8EDB<~lIP%6I;VuM1 zi*RuCqyo!)@{U(X_@e*7waYn!@48^^ZBZGu+ zHheq3+rHkVtx{`@#NaQo5#^S9Z*y2A!P?)nbaI^53IP&XnD1Chh3Ec|8bv@Hd1a6& zka*gGiRpW-eB|E6JQj(+_BV--oTjz#U=*&pKPaC~!yw5^kkqbEaSSLX?==`rf9#GU zp1C$vv)N*6nWq>BA!LX!3Rg`V7)PENBy@kqZeu!CcIdxHwq$U`dsn=*zsan|fo};D zMxuZO5}yZ;Bz_?fcVmI4asLLFwAx!XX-$YeFtNWEh33770Ec`C*Xo4)T`u>vXjP$9#V?k}xWA z*br)BYc>ZkF4sg{wwooO^bP5Rp^CGE;|L6rV?cJ%^W`laHa&9>AxR!aMf>}=2_uc1 zwTR1JA9eIw@{FRQgsGgDMgz}lG``>WyWOR@g zaM_{5sOTXMh0Nmy#}RChgsHQg?;w+uiFhaT6rs@MlcRxc40$(V=XfBDG+IU)LP7|* z?C@d4VcY_BVsIS6NZU0oo8T66iI4~DKwW`lWMZrm$hPUrmdzZJL3z#RvMT_ikj0R} z`J-Y1scIcFjX1nq+uRlq2!X55Co(b)h~BPak4TRJX{_9aVFk{$QLF@vLKYu|fTJSf zX?azRl>0C-n8G1s)2rqcnb9G|^xP{w6iDgvXB#YbV_2yXr! zjBBm$CYO*+vSUK^GAu0o-aIGN&+e6ZK;&Q*|SmZxV9dD$Pvc;tKKuRr*ltDB9dE((D- zHOYej8e`&y?EKoG{gM@eQPJJg(%XZEfujH`fBj}N;qxTk z`oTsGhC5UwWinZV+_f-|XvmC5g1dHqKTW=s>K_=g$*(E}qmZpeLg9}Bt^D=(x0W0Y zcP0r4BUCQ{N#WfSb;~aEfmEc8l7#*ZKP)8@V*mB`Th@vdgHbVTt}Bf3DA>whf8om& zSa1gf6Oc4ck+dFsAwWY!8tsn2AE69mUek^j=zhXHu~iO6A#3}?8IOus`F|teE2H24 zn8lbRc$0x!Sf8UvnzK(ho?BkQL}p0EMty668x=P2ZSWT+`(kD3))^~27I<#UCn!Ip7wTI}IVRvpO>t|D*X9<&PWJY> zbn@8(Brg*Vju4pbb;%35kmXZD=D|IjW&^dN@-o5awzY)OevLBN2pO5vX1hecIpvW| zWIz8;6*ik4(s+c(wXcRHZdnaqn(V*7X-#$HfV?O0P-#+27qEbXk}aol-(a&%-%n*> z6grz75{{^~zb|7p?i+?Qxgv%@zTuRcOR-gXD(Kv{Zk!z{N3;x-vJY^@%p6r1MxnFW zVd3bvd>gZIUv5@iZ&y<(~`15<9O#eow#IuG!+=Yar!dK3m`Ju!E$dh2{HWzdnk-wTNb3E~P&Hic-7BUzc+a2+H+snRNka|A#;z99c*G{QuvToPZYX31 z$E$jxDVb_F#5qk7aWDp9)-pq z73stlo+#4N5xLQ!>}D?B9{Iz2s<@0tA-mFs${$r^#b!X$YHCn5Ki!n_=qLA7dDOX+ zLRZp;xL#w)k192>v2H2MCz63RTs~3w*Z;s;&T9v5>Kir+!-2PMI-L#w++TNo%uo~5 zXqO6&KPplk+xL9FC&_9nslgB}T_rC{$sWI3Di1`k*%479570voV55WXpDR;Xw~ob? zNZfK>tz9lxBD7gcIcIP6T!a<1HF_)b>c_5FDn9P`XmUAAJ@gJG4G~8$9tq$NDRQ0(haEdJ+F&E+{K993jm3lT@u&7YQk>g$X5St*}M49`~{O3#a8k zca&P}H^$!mPHZPONNl=IIX!(^X`7Cb&UXp@!D0G`9wT(;2ziliQ$k8h>%@SaHXK6f zL|SK*<2YVR(DqJc=XYW;)IP0OV!x=weo@#jy#lVr8Z?#X9eT4e(^{A~Dtv?C=<7Zq z;kR0DEHRX+@C5f_IfGJ+q|-6vcsow8L6dYHC$TgVQl^oRGL6j(_@Ok6s1^SkmB#ct zG35e1nXV=2;~+S$#ISiQ-Q1c^_uK+~PfyR2pi4Irnm&%!2Xzlx)hf}()kFBDh18~R zu{&sG7dMv|9s05|(^{A~D*oiF3`n2(MTGBqtC^v}u}Z3PzgSLJ86{IlcdCFdLjK8S zn#WXmzLeOMkmjh;JVj}c1C`+4)YJzo*(owtGUDb^a#Ss6>J({xo8?DEvQ*kKty-&W zuT`Q*mD;0M(le{}F#d@2Ol_wbRzb_Mutt%F)mXmh(36#!)fdN{LNz{4nyIGMXqkK-dd@yB6@$h-vOz zJvpkHGj*!=!1HQb+i5mcmMRrBnp?{z||aa`Dmm73OMarCnfKPp!a?ce|J%25ia{_?-`ZwH1_aV?ulBtpc}%Ra`V zO|0^=um>wOt;yl&@JAczcC*kO97t#(&#*KfibUY#$M;k@De6FRa<`yeE@L-xawAbh zuXX!i(8tp1=d)u&{mIO7&`Ivp$URj~iMlU*e{B6q5;*#+8}D;-DI^@xX4Z3=(Zt|r zCKtfKyW0$-Jt&X+L)QELs(Gs=9MCIa38}s+2^?M71ZRoA93qftQ)|naWItv(pJ3`S zzemU(6=j>ZcdJr2?D12}Yn>iJ?^TS;mcr5GCiqG?Y8w4w46|Iae=wQJdiICwH7}&d zwo@-PC=K3MSErOc-Ya>p(JSboigDR8IC?~Nl{obn{y+Tl*m~^Yw?0WfY(2-fBC$c=M$v-BG{9xoZ3$6g(J0{TsD(R4)zZxGnt&DeBeB1JZe$8F(zHP0lD>g zAZ9=5D&Yutic-`>C%S;L28u9pqnp&INUMA~&+n$naoI9BI;z@`?~N}-n3+0^kG}+a z^QL&yQe=1h(Ah}*WTd_+z7#*i$Y4mk^mJsmviEvqH!R^{)gCz+!Jnl=O_y=xGTNy} zfu%dGQ@?lb$t7$>mg0Nk5!M1LzY;EBoLkG~GMVI1e66T#K+i-wb#K!xxJkLBh2=g!1TBi=Ex^VXRNn9c9GQ}y{H+ZhR)b$o4uMLGrd~h zMvh08YpvySbD8lZCOowy##b)cadeZANz7-HlRK32hn2&V=XcO~ZSpPac+@@lR(Yh_ zARKYUZTIB8($>f z>5RQd+K!XcwZ}Uf--Si#5i_yvR?~>DKhjfCRoJP%9ZChI>_E9m`b~^T9$vX7x zCgP}cX%>H-A?eLBjtrxtS){wW#oRW3{jYjm4VN7i#H&#@g0qY^6za4A!8nu^0?I zYw2cfZR^2wGw2RBzJT-T+6(E%7t-(4);7O@YG|PchfuQ-PBe|_Cu6PHJorxRV97jG zu;K{qv85Us?H@>{GArP~-zwXQwNfKQh#{E`S`T#>fvs9I4p5^q13<(5?)(d|T>8SD0wEq)B@hW+%i?Om<-s}J=8SMASLQ6?LgbH~xk-sSSaYrG-*hBt=pdZ@3t z;*Hq@jaGP8lflt11s`3!x4>VyZVYHRSGi$v5UcXt8`eiyO@^!789=6`Xb0RfeMvsvJ0$+xx)slJm)+ z23W3Nuse>*HWTEPkv-c+YR)kTU~6RL6*AJG!UJ2>EaH`OHD-Wp`}}31B8^o**(PH; z5vBo>Yah51+_E@6SNZOT<|is7Loo_<>?U^{{Yr`3A*XKd*>-!+`?nw8_tHyyw(Z+@ z`xLpo?qtl zhgA+7%k6z+>WB5w4TwDEj-#@!o9t+*iB6F2C&&)c(xU7jPjr)sXbaozRvMxW`yq(K z5$s=K2Pt1vqjXJlkrr}=Rls2>RV7aXQYnzgv^#xI0m<}4g^hrb#Cq*QiAyF?NZEj+ z2B@=JTB7*FaKv`8MUQl|BRWkPM-5%{;*wa(IdbSc61u30J<=*O->$;DqXAsqm|GM za3mlV!-!17Q&kNd%gq@dC_h|z-bfBdnvU{71JI%3=m0#|4LD-E8jcR@IARA;C))59 z>3XiFJ9?Pm=s@&2B7>uAa`t615D156dgfk1(u{F9S_z(2SFZou$0JR*bYS~b?Hg0- z-{#tAE4H>Dc%v47*e%7P-el=rE9*%0i@Ry^BM z%RRSuD&WW*J+B(~aFfO-%T!!$q+iV)NAKFiuLo;;2$ZpUvFvJUT{DeW5$;WTf2-8K z3@7k5yV1Vthb%92KWF zL3VP>;U#G1)Pt}Msy1$XbD?9ndSQHM0|z6ib$@YU6L2K)Le?~IkLu#aC2qX(B*>yU zSNW@$t{^cU6*nG7lOB4Z#Enz$p^g0rJ>2C6k`^+FaT%w)P;W^FM^hUuJ4yR^#P!?? zR(Hc#-QC}K0*W>xCzK41ipANP*$o?%%n}gKh`PV=ltX5*jbyJ&uSX6?p5Nx?S1{pe z`MwZ8t!ER%8=JqU{F;Aiail-uI$hq4Li{v9C%k1TcmB=)3Vhtba%ylBQ`G;|H{0HRo0RJX*9bj6Pk95_YaOr?_`Z}p40`rKnOEY}6R# zqpE-2%V#sg1Eb*wo%i)sY~je#ZD6D3DIZ0{L?n{Xz0lAj)h6C7F+8r#^5~V5c?}RcpDq@#Nq@GPAOoT(!N=ws0gni~~R5roc{7p*aF{1*7NrhW;L}<3EfgGK{CYTp7QG0A?vSeP zS+3r7z!r}D;mB4Ci$C?PGk#qgv}o)khA&#czFUe4IK5C8qX$9=Nr7*yi3Y{j^64rR;dUN3sY~d)pzPz7X+QQNO{Px3p_AMNR*O&Km zOItX)pWl9X&%TAD@cQz8ZfOfg_w(Bi@7cF-6kcE6&n<1?=zf0t;XV5nj>7B9`?;kp p9No`vKfGt(!clmAc|W)GZvX`Wf&wGl754xD002ovPDHLkV1oP9{x<*s diff --git a/AvalonEdit/Documentation/Media/RenderingPipeline.png b/AvalonEdit/Documentation/Media/RenderingPipeline.png deleted file mode 100644 index 9e7b7e308dd2c022213e8326f12a923a4e8b0753..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 31718 zcmb5WbwE|i7dDK92+~Lk0@CTByIVp)Kw1vc-CfcRQio1Ky1N7pB5(kuyQI63^xb&x zdw*Q-`^WeFrEK=hteIJ})|%&eHleQ+rO{D|QQ_d=&}C&LRN&wqG{eEc^F4wGo`5jz z3W0wfIH*XA!Icd@-2{F>G!a!0g@db%etd0!1pG{HD5IhP2j@-$2j?3A2X_fP^4)-g zb9w;>xAhhdjt>F{M_`-Qq$~jZg3wX&jiaiKv7?KDy%F3i12bz!7DdU||BNG z%hYgi9wM?5qOV=`c3UmtpGemIO#M~67kstk*{r|Ub0xf8#%>a7FCtK_J|VbX*1UI< znXGJk8ilE+gN_8OZmS zG}B$AC4?xe8LBB6*%_ZRx|Fq&GlF}fNIj&l`PhmXw%g58@)s$j5y=U5V!B9AI>SEu zuw$UfO+SBIrXmo^4c`qu{1Qp>yr6!b(;7X@5}OcYMe+{W{>eU7$Gl;*FHSS^2Ao7z zeLVsG%Ey;UzE1>AIG#*V!nyhFh(wXA@)(XheL$7}WGZ-|KY>w0F`W;I@p!`wU9#?x zh#onA%=1}exyrZ84)CEw`a6*s1~c}@YXji~tY;@DpZj)%K4yQ#e^7P4zv=f>G~YIr z=vPYU5CWC4XXSbbN|ML=Q0D&D*87C1Q~w}JZA2NprY3S}R|B$N??cCcw@Q`@(yLP; z>x1dr8ymg}Q-`g8y~W2zE-eH5Ng!WBMh-GWZ%>C56?OJm3K!lD_Vw{Q|ip1vbz>k#@E{t7??4T!}ShP7=j=% zut*}{FYSse2XLW8K4ed!vp(|TvCQy5!->$Rz?eUV{QV&w(dOPpQ^iDA^3V8+DO$yiD&B3 zj1%NC9->N`TM^9&+q;Gm{i}t8bitZN$`>3k*Ay}SL&iQULp9?tI!I3iyp2!ai)u># zK)T|g4w|SD3e?M&Do9+VG=ZTwVcSjWUsuK{I?D?MGvoD4_N#&b)UQ3J>ICwW#?e%b8~%OXRGQt9m1_ zMifO?)y$fkZf;!iJ+-;2mMap;Bs=$(ke~9%PE<$=FYBN*&oy8}inar3Ij(3OCkGGtG@iEE|w&4 zy`e?d$>Fn$A#YfCL$EP_OsmVmTpE;JBl~C6G>|=e5+gDGy*jq3Z;kxHiYvu}OK4TlI&3 zl$#7k^=Y4Rm04xThFoY^KUw|KeYLn(RE*GO*e?|fjqpkTy7T~WIsu-L#>1F34I!^k ztYg(O3VP)#8*vnaVEc3VK^i303kLJ0-7CD++xMFY=PF*PZ_U+Wlj_^@h*JWa2cqQo z$GjZgRGb^}8KdPn>X2X_;?I^g@-6b$Svvmv7?5C?d#@VG!J;FBRzBvSU5eDR6FvI$ zj&{2?P&90KojSouvqIg+@WfYl@%{-4)gl* zDb362o$&UEq%ouFv-r@%Y^3P`hVAvsmxILAYgdWKo&{2kUGJqFcODjUC&w~|q}%^k zW_H!i{SxW#0<&=yefICo+4a5)allc(=XquG1^z=$&`rj8n>RZrN zNdgh&-l29lRQ&HS-c$MiZOvNu-`2;~R`+66mH@~Az2M@Lo%vJf^}FJ`P`Q-~ajKhq zuG`K97F!JKURDsWo)6#=;h;osHA}-jzP>mnB_%y?Ys1H<1!A6Wi-d_%H77p9(w85UL-svbQBsgUalx#XUeMEgy_oW zEhX*;SY%!;K>o9$wB7UKs5g!llT2W8dU|?zczAZUMQEw#8Og-pjk#_P@&ip@9T6#V z))>;S*zbxk&LC^<$m-@j(G!`U8z{Bf`9MpUgMVkKyba#mY>}tr#8`3Dmh9O{787OZ z{4RUYP~7zN^kB?qLh;u>lt#E&Y^LH)>_k||pT`h<#aQ{obxg6vNaE0n3qCs;{j1ji zh-I|H;c|CI1{ryG)Ce2J$GtH%ZYGM9AZ1TomoswEg@Jp)&3mVjB#E`LuJAGDN%FprL?;+Q%7iW~zAJw(>Z z+NjD3=@$j&n@m|@siEo0`fd4P=?+@ztvP+GozzTYePw3QC;aK`;JS2U=f=&juXaOWGfgt5Kwm8+f;>G-h^dSDWiB~a@jtK@F zc2~6AibbmYB6BBNPU?Jj6>(AUL;Yf)6)2+feH>(WS8GmIA@pKb79A;+$g`9ZIskMMV`%cB}YDlVD7XyS~=4afwlJ*netCf*(d3Ji$+c3OLIA9vzeHkI~mU z{C|()mL(l7g({x#;Yap+SN(nAyc3f0ux;e;5_cwnp-k@*EGb+~OhtL%6~SaYS%Iwk zCJEU{!BcpKY&Ty%EuE`<`IUlmoJz*5H5I>I@NVIFq2D7O^8M1-H4yql&$ldWHKcHj zZB}35ecv=z+)4Ob<3fAjeH)HvD!yYDWXa!=lIr%c!F(`$DU-`c^=vG~c<;vd<=!{+ z6Y-F%XtVEqQerS7Pu9Eu(&X0XDukfWXD~>oEt)XOOBQcOzZ1y-+ zw;5m+W6w-FWMMZ~oX*ema^8mFBm*A=*Ve1eN1$k#BUGkN$AxUn=%3M~xv zN1L;Tdvm!LSmgPV)jKDG(^UlQatpI;<^gG#^jH=nk3gq5t%Ynk<)s#T4^^d1peA!EhyWwkxhSbmZZ%QVAe@X}Yy zJssG197;q4(mjKWTgT327)%JYw**t*g>EXs1e-aZRdGxZ(0$=dcFtsb zmtye1+`vklIqRSe9xr~{)ni9XVa8n$ zBi9nkjK%Ro)q||D&%oJjZX5Uf3KoM=>%>tH#TDDDvpH4dps`?Ce3o$U9Q!~$ckY%@ z&N&95DNg6(Iqn1tvm_k0=R>cXUWTiu(1R}YWI~1#HvbAN7>MrC0-d;KIu}L)26sfeJNG-Ms8f3KVeLEeg%T z=|S1}iVe+v)R2=fgN&d7c_Gp>HQNrREuoO0cZbSm`x69Z9KY} zYFGN{xNo>`J@0;i%sub~=lD8XoIlg&A)+EBvO_H?5K`-OV{X`)#_2CucXae?(NuaoSoq8MlRM46M9fX|N`@kM=}B%ddW;5zG(Ek$!Vn7W$y z1F(>w;mBhji@?m7z}641;U_v5GXmhbxn1fqxndu9cXl^lBcd!XCG58cdr_ARg}mF| z_o?@QefnlJu|eR{axgnykg0{-PTgo_aRY?&#!_AJ2V|v_Ej}~cg3bJj9nscZs|5m- zGhZU-MgmBwqhEf0MI3_C)iODSA`!kZPmOi4)7HAwr{r;-Hs8Aav#xZZgf2#ZVXo=p zZ62_Ym!(1PHC8G4SzXJY&Vzzq9tDy_$8Qw?NqW)t3WqB-n0O)f_{OgM3Zl*RS8_<~ z0+K^DC5U^6U-RtDsJqyH26w^y^xS+8~0NKyu`AgSDDdPkaj>OWmq zN*jkRTMR#|Rz*1|0jqczLqoHrdXvy>velQ_ zhWIR}PoP$=!YXofzD>XJlv>S_hbt)tV*Qd}Z@qIIhYNx?;Y_XMdj>X6BS6Pk1P- z_4M__pQfMi_SCCvS|vkJs53

}GH9IVFqim11@2dcSIqdK1;+R~VAk3w?Y)t!*4T zMOvBovAd}d6(epBaH>S{6vzgYBVnOQUwMy}khRnluKJ`?&5?EJi=z7jQg}@*3$5Hh z*3AX)=T;{6>oD&AsHxfUuqIJ7t->^V9y(ogpcv zqz2pd+P-1jPy|~~X1VqDGzxjyKeM4jQ>lt8T$R{#+t_`BV1uXBIpuTkRPSJV)PeUj29+X z8i2^Bh`SCj9H%i}lg|K`nj)hNon9u$cu2~y@Hyy78SJz&J&BMORh?o&j+_6&JJ6Ym zhw>$0I1-50da6EtdC02x)8=FlA6cQS4WezkzJdEY!2UK(bTR}YX5h@vmbmr8i@}fv zrc?dng`SVC8CRJ~vwTZgpn~S1Z-#N!iP?ySs(oZ8OwKOt`=qIsW#ibfus%X!KhDr# zjt(3QOQEdLP`;{6whb>uH>9PB)NfC{@eB2>{R~VxAZP*|^U5;KSsnTvfYCoY?bo?} z7-?%pwer5+WS7DtiLx5KE8cV$i)P`}yQN!`Q@g`bB0>j|QM60y76|F2<+<#`){4se z{H0m>fQqb4zuc|YQw(;I#U5&FC3MaIN#rClPBuO-50N8bhpG$}bzK$QDeJ~b8j~D* z9EzF6ZmJT>ZX7-DJ#7wz*3$)3uvo_lSpiym5F)n!n(Z(v_d<=h4|T7mj5$5lW7vDM zNLD5nMfXb5(cr558d(w8_o7K#%Umg-I;(`=zb5>Q<72HYso+f@Ya_$9rJ1+NjK##a zJ>YlD4fkGJob1j-?P9lH9Wj`jgfyur%SF5&Zs9GogslROHtyjT^|4fpsnT*$7C!1# z#H;=y1!4#hXkwhRGV8oMfrM1;;4d$j^9H;C`zGFxoyq7kZcJ=Vx@ZXRPz5`tH!nut zZeUG#rwBDW<pS_ETluDVP+k)OE5mG%{u-u{j0;wdZG;v?aV2VsyPz^n&Y=sbxo{Og;02MKc5>v7EM4 z#*R=lYa(XEP+y1WM)w5#;3s?UorGTQUq&{^H`4@cNC88*XVTCh%3nVV<^CDe?@&+Z z^#s`E_1|72UKfx+@mx)Htq@eduv^MpBx=Lam`TY+D?M?*zXsY&2~KW>;d(DaP24!0UX=5(lZC__WVO`e~Y& z3+;EOm9Ku^g9z%(f!P)jFjz7y5qoZTJbN3Bf@v9?x#DykRF;(z;^ova{bV)^Ur;bwJgG`S1gz%tp zz4qiMnO$NZR-DtI*DHpldq80NjYZ&r48jP)yHi8?n%aeZhPJn-F@8bl%5B8bD5gI= zXU*~e=HDXnm#LQDU#(Eklq`{OTYFZXUYu*7%Op!j#xq}nPX)3(IvyK(LUYogH3C7Z7XaT~t-NAYg zf^Y|W>@WKb{0%Qis#iI~Q*S*I0qn;*=9@R}tDEoA-BB*rPlwo6Zyv4o(<)^MxE{Q< zu&{Xf@}+~r@g)R<+*n?)JXpDFk^&wJIpiS}krH=;4EHi{o>i}9a%4n2)a~g%T@oJa z`3vU1-WG&*>-nF)3_(G@mTYz2oo;kkS4`viJ~id`^I%E*kW>WrlTR4YF!<45PzT{T z@!FUw04|iQgiqVWe|ipQ7i8Mw%}rx&Dp&iDg_isdr(0@2x82Wnrr1pe)1vm_z+WaV z%n11<-~c=##3k2YK0BD7EgmBH_qqiMCmzm6hNeJNO3!TxJVv)QXla^Ld*>5dy>Iw- zN_`3J081L0g1ilY)jA6@)0y~T*>SLMrUE7t59Nc$GEr08&iJSC1SQSm95*=DWj71zqGK1*eQaZyZUgY~sq$O4MKOkAAoeTSX#~_z0eewK zMv{3Lmam|C#TZMU*wn5~(W|d;+?L80Yu3hseQy3GF5|KE+2?Npev6J|`>!y#N)XF*Ii!;|6k{O{VQq$PPWtf;~=Cc{PXrmdW?1VgP2CSIy zf0{u7TK($(S?%ItUJ-L@?kfvSIEU{UHX3KdTq$=p>yi*n3rv-qxMzrDV!N+o{Pp7Q z0lH&qTF3lp95LaJ>$xkEvo*hIdr)Q_aWH8)g$Ht8lh(bZ6ZM6xyYsh5+_1O4_%%R~ zmG}!i?WV;pJ$ndZq_(-wuDTh{7?p3z41g71W822|8F~qH|zV*Wk#n>PEBonrMCD(p|t-H;{SK3#S z=@1JVoRz8Qo!~sTTfYye;FS_ZC1<_iw3=G?noJU|WG~&w{k&fiwaYJ_zZSXYEu9p` zS7J9|GaaN+`dp9LR%$cV^e;5hwQgwFHX9W=M#y)hp1H>Ra_WE+#c)IE_X8w`$l>o? z%J0XBr0}VCIN;s3(e(T7F#JqUrYKn_~f#k6+~g2q3`6oU$!sItn{ z05sMA92Ic(Yta1%zy$Np$>m1>^OoTKw*o@k7Ulo!DC#F_Eu;A_H7gVD^_j2uFD;skp-*>K-9!W7$udisWe0ENbZj6g)?gv?E zX?d@xmyad{K^N@VAoY7;9t$}tL*^9_2lvGWFGBNX-KdHk!f5jqsmaN0<<_$>=sy!t z&{qUykHhECftaOce2uWH)8Icciwgjjp@d{4gu(&;F_;Ma!H3#IzQ}mSaH~}DRIz$rFw(w@X--n*aiT(lnw)zce6827 zoGlEJ^exnb57q&p?9nUCk9P$0It2e0iA7DLiP#mEjWn&?fx!JwfJF?s0MHO1Rrx~W zT?D@_5#gvt2|U7fn22tr`z{4{&zS(XJ?y#v0E=>MLij94f&^fw{|Wd&)Dk|~lK`^L z{n+sc6wdD>63X+hhj5^F);-%er69)kfz(=6?_#uDD&aR~u4QAbvTmxoLvtWc)Y6nA z?Y2f?i%zT3y{w-6iCs*=WvLZD+i1vZjlh3dT)lgh6TY&q_Gr_T*=H|*U%l)(+Rlru z#`6s|>e=zF!JUob2@-3MR^1BypEI`mv}$~sZIAC89s-$ZXKj*=s`4KlzF9llpUG@B zbdB2RLb+1MY~gquuHQBK?Q!r{?f?$O2th=Sw`oW!zQUO`hU1&T=y>7(V^|?k^tQbnYF7kqp1p^ z->teFQERrcYt_$H3-ohu7}4k$6H*t(2&f;$K(lMMYlq6G++e|yayBuAQ@|t_p~u>z zG(97!Qr?2ZKwKfn_+pWWXupB?zIP&1fa@}tnjSY2+T_J+N{l{=AWjw{M~MnP_FSTr zlmBGpIr&qM*UYrmJa2`wiM^j0X%0Rs(Ze~`K(&NB@oKHQG(XnIMpoAh&!F`kF)Y1l)mQ~!hIj~h4h4zDCb1o z#f5)Dmjo>Fha|V#HpOu&ch>?#?)dE}oCz;SqlXY7Y@w7xpmu7EZQ+MD=3$Bu@q6s% zV593pLfze>KTP7$bByc7

O}s&(!fR zd#t9`-N1Bp|NO#%JiPl%TXYyJQmIyWK43DLsfth1Rm)At(9)Dn+k{{2$4=bTanbeOAxovT`Z z9OK4<4H}yiQ<85DS+v43M7K0*dN0}@K*nZAgzVuMLB&}CSaHQ{FT>tOs;?qrTXe4} zM0%0+`PXtkGbe29J?W^~oR6^pyUEDg-Bz$LDa?Zc`Sh2Sh>TQw_zoW>S^Vn+O2AG9 zCApI&H1j7^K5wp9Ogvu?comn$tHBux{$9l9}-gMjXr*Ygvvy0ts%Jn$csA?r)d~%&^;O58jrj^84$rn6HDBa{7)p$Q&#*=0 zRlw?^p=`D+0GzOfVkTL{g>!V2KJ8&=^QaZgG|l9E{G(N2{%X*a#Cbu)6i#L|cHfAd z8uk6nzyeK>F*fx|$jMhbmw8`B&&H;`)WWWk&l`v=3i89mX0lh~BGpn$`>MO+PkQxI zwOzie)*+IlFl@ejO#OjIDGhasdIB%qLGs0q?440Jx_xYx35I`rp>()~Ig>-s!jU=u z_DLi%Nrq`*BLXKGt7GuLVy?sKcd!+;Pm&w|QHQ5hbJ?LxKk4t^S?a53(L9}gv8qvh+^#}gMWO?gMo-O#=7p{~ zwXUXLv^8Q{Jc}}1=;Xi{1Zn)zy*b?WdFyq5mLZV-=qI{}AzYp4$!?*wJ&{0CJu&vOwW3iwFZ+%pFzhZe1s#%jIexBMN4cYO>t(!x5 zq9uZuqb!qLi;9#+0&=tH^5Kk_Zf-raiTM8QxuC1Wbjaqb$!|Z0N|>GSI8Jxz?D(y% zDesj)@X#Fwmg5-B0HG|Av!H=2St8`i0YoMC(;z7W4ZF3;ApL=5v@P?*_Xfe6kkx>S z5()zj-riq*6+=Lc^-G{Gy^c9o#Db)^4Z>#(IeMCPe$Z7Uc`w-qgf!L^Z?IhG;&!~Y+MfjACvFFe9pmHUiHV78Yip+{ytk7L&U+f$ zI7>_tc;Ls_K|JC$6l+*+vxa@mT+7F3cM?P-cNTnr-_ix79 z-$rM?ikALX%#xxL%LD+Co>H>LJbNvx3z(}?kY>eRuGi`g$UFcoM+UFMnxlQxx{38n zOFjSpnpnU1sE1d{2Z*dVui?`XI1Jhm>c`6T+c7+zy&00_mGT-rbGpKmJ;eXpxI=fH zx8VHONTJET&@Ol`%-=8lCCgB0S@lozq0lGpDs(jd#-Erg`y!l^(8ZkgmgW{a~1&siQJ+zvSNa#5z zE|zxi{l<%Y=w_S}gFzCP*lqUizFJFWvZNTod+LxeOpok47;}3$j z^EDNbhgs3!u-jGhfiRwfaN`)Z=&tBUJll#23WBkYH&htN1*2BzsBN4kb%7$*rIX^hsvwep@BO!G8Q$d0wB7&biZLQXiGvU zRDQff@k6}~jLIndPKFWyNl*X%TO4*xcHY8yN>CgCXsTg2ehZ!Yp8ZiT2GX0-)q92y zjD5`;T3BaMNI+#=wPst@DhZ}x^Z^)5pW;8?y4W>fK79|2^i;7980p>WkSt6*xMuV* zFopxq)bBBbX+fA|qbjU-7B9W?(2jzbv&8il&NgI;R3=e*d_y^#mxUo9*Bs=%cx@nU z3_}$*)>yfupE~b4fhz4I$3RdrzJ)sIhCo6|)BqriYVGz$>kXUXr(v5Kxl+6!4CbFN zQfZ-S*cr4!O*HA0plz47er`4p7{5xcP9%+%mUq%_*dK4R`*IJ;5NA_zx)>V=xjHj5 z=#8L|YgcA4DSaW)8=*D0Q=EHAFK%plW&AFIf|thx_wB>i%*Z;#Ju#g}%9ks?lsPtB zhzi4XSc&y%q*TU&u${b!4q?#gw!^kudV2`>_mucU+5sh6(D~k2C$0!pBh|B7`Fh@T zw)jc?#O(>zdNjp+6Lh4`SHAU7^BN@!~|YOXb6HNI^7v_)MK#!977HR7m5=zOX` z#~847pjD66)YTjdQ6A)}v5FSqfkG_~wFVezK`#5llrf!Na%A&i|z>$;J;@K7YXh}gqql%#)1F22%nvBj56oGNH#(BH1M^#^)ec`c7 zgU+7T;(z$WdNQDBG>(r8Uv*49WO9iyc($9W-C5)d@qb(*t#aBTH{@5*bUWJ7=cRh8 z)$m<5LIig>?bXk~ZUeXe8By>T9*XU}ZGg+A@u~cERqa#GLq-6$Cs1G6C7t0HzPu8Q znn@Z@fLwUL>K=^Cvu#|ToVW9__AsYPgKpHvLHJ!vvwNQ$pWSHyx-4-UW%jSqiq7Hr z{2%YMY&J${3K_i^5Pq%f<(@%W@~&Wq4o%(BBCC8h(E|0m!Q2xZ_Ae-!w7UAu$~p~) zU&U=|VS2fGP4-=euYaPPh0zCRj&7#0TL9dB)OwP}>nJTi@}cFqYoM?bRL6J-!s=;e!s1mvfFJs&yEBoSNa) zw22x0!KA`wChP+m7$besbE1KhE;JmD%G%`03>Q}hR^{Uu#cchaB&nk3+HPBY(z5Tl z@a~+0`FUBccD-k-ClSTkI5S-@dH%uLL%fe6B145Q4cGVk6zBSW-~dQS(??`$9dG`d zb}F~79>-xfwKli7M0ZiJoFAmg4t}07*ac=_fwG^`~4ht}M%y$B@Q{~_0QIPg;<)VoyiKe|TQrf-{8tQirk~?NvfUOFO+p!%1e*u7 znbYTcO+B*}qQ&IT)-O+by)26q1{wTO@lxW)3Y#c+vfj~ZoK(9bQ5i?zRw*{kyR6Xe zM;lyH(R7$3dOr^!S88v_U)cGE{pO6`Hc_wcbFBfv>a5=Q=TEH!GjXd~kp>+t`SnbY zr_OH{NgvTxA8_%>@YEGmEzcTqaa-WMdqA-Uuez%sCO-@nFk?Ym&d3`!$&)L#e}1*0 zG~yapTUthOVoePfRGQlQGBQizCajEA_RjBq%Oo7YWm5x++OSXhUwJQq5SX1X7;-QTf+<^COPvx&i4 z*9^$~J>`hXHB)uLT+T;Sr?N1%bBX?424>_BA8=WP)1f-mTE*lJ_Vu$LQZ0&FW7YN; zVrZ^Iy_eG5z!ZRjrLa~jjC}V{-T3BX)7J7;sg7C4GzsZ)cgoiK37g`dWoE{H) zEh{g@*c9q8XGl!(0&B}&O)R!i@OQ_|uW!#(_RK^tLNO7I%ax_=j)+@F8^e$~QrWIR3)@Q|BA^*;~oPj%3K zsq&we0Qx2v<6#EGwuh$fDDW;vkXr_xP`(4?foKr-%TaK1k9i!dC`yk@zWMNaI^CT1#G_B2e7H zehY1}T@rI~anaVE=}TZtO-aH3cE~*poJ#cg$KDo|8yns@Ej7V zNg7iGu6)G%^4sC+S{Z*&nY*yh3sE8eVytzJT-+d^-RW8f;F}>HyPWFkXA z|D#;HT>Ugws~m7ukTekWExm4U)Wl!qM1AgL9uln?Sf#jHc{C$jH_+mKy44*{Fq9$a zu?9;XF%$fo1@4-CO9|@Aurru3tWRVC6zq8oC0@Y*LO?!v&QU{SOp!wM7Ixe#?q@A99j_Y+Mp*Ky zJEXU1<}ILPo-1z4)tZ3{8fVd`zW)OBAGhNV;j3Hh)RB&`lO5DM^5xI5kwH0vw3VL0 zOES-ueW)9aa{K(zrLdz4x?(kaykpt_+IZGFJX=1FH2+4+fB3rj{e3V>Cn0m9NdVgL zB2&`ISP=EP_b(QU+b94{h7muzUCgr3Wpid zE6(ehF`gY)^eKMwv9bGbfnTVb9;t;6Wcv-rr+4o|Y4bazA8Q+h_C5%&9||cESC5B8 z$J}nP-M> zf)Dg^dQN6RwJORWT!wcc;I!Xm{grL4J~++s`1s3dM%M|3*tdT{;lH_I#t@8VgMess zLl@0UzUsC`<`+geU(8XCLcIJTYrNzUXZ<8gL(E|Ny+-<^N=(NxftoNwOj!VR{-0w| z8uv8n*%+jO`D>lh*cbtxxs|l}smGTf;r%V$9jYGLwM+Q;kovIVU+`= z|1T_7cBZ>>PUL;e9V-HoRMl7868a%|BL0eXb$^0bk8eMzV(TS$H9LKhiQbRYtBSfU zIsY8`MB6CI$IY*9)BbIbz=+2;HDA*y%oDBK*<9Hv1~GZ#bp$#2b27%)r7gqXeuXhi zUL%NHcW+(c>`2O>-`kW&GV*X~57NWmwYwce^a}A9@C%7#BT0}G2gYj_zxv#W9ao>& z`iq#;wc3u_kmE##J3)Zb3hGFgX0tOit)d~Sx)6g?|6`5j-|+###9cRV7}{=yf7%}2%i{~shP76bxE15b{tgnxxm!A!PfMg)fcdBRNgAoCH(3APDC8nt&} zRzTH;GL^rLB>-lOCNU)U8}e1>Y18n|KPORg!{qXssH&*WHQ(AuojT{aIWOak5W);R zV67C7XFc;q;Au`QxJ0Z)D#IJ&_TVVhG=A)uWX|Du`LH&K7FMO;S4SOULbf&dniv2- z`zOw>y?%LE)G;qKi+|(UyYDa_u#wiQ)>S6Ub7HAXBXdM6_QilFTlJ*J2S@L{hbk8a zg0cx9DYZSY)KbOs!3M3m*%uy7+`n9mJE~CX~g zk-hm83ogGrl`(VvD}GXZbqZ=jl1rlt6+jb=K4mwygshsxL(W! zcvI!qKoZT$1t=Wg)odNU@UbNI_dNT%kIhTWE=p zd-Go320e0#{A}l7ynf(gs)=^!Sgi66Reogfr8%9I5qkHuw??xgr6mCUy=Zu#kc5Rx z=c^(FAM8Dibk*1VrPOU@?sRBq{#C8O(co->iKY9JO=+&lE+M;ziKJ%3VMwgek~38}qU7A-LxcY8LbvPQV`F1BrTVC}W}cMgj=EzS;kGT6{urV%k0 zH1#tcReml1+NOT7Hu4yYB9(D%YC ztb6TdrfqX-&d%IsBH2sY`zSF(HAyaXbGB&Hg|`|h{2}}~i1bRZu6C6E2bFO$Szw6l zw2>%W;J8$^j_?lUyjx~s;u|0Oh;R>4@YZ;VHvHvj>#U6@1t^zRzgCbORQ&UCrKJs{ zCD*Se%j56u`(-(9JQ}Mf=9AE<7?;mKSDsQ$E)uV1bP%gON&_>ntBp8&%~uHd;%(~1HLf! z*_n%^#PQo}-%n{XKCY-AA6%$XlgOMv5rLVHq@6fF#rMbfcoJpyDtxJ48XWX&q=G37 z_jtsOglx*g-b4`PWn!|;w89Lir&W#M9{JLpB_H5 zyzaL_!t%Q9mEn;xGBJ=g6B}2kJp7BpdMYoam}yQrinX$59=h-Ljg97=TN8y{MqC($ z8+S402G6ADr|afy9A5hL1k`gW@@(!^3>=+FXG~q2oqD;QRvmrja%J5pE;p#AUqQpE zc0T4$7F;4zoo~4yH!epaZCaQ;&HW?LUZMR(;T&@bi=od~x+8aC{V&p5>bJ($ek^;R z-$p@g9d5_WcV98{Tk>{&*`ueCed0H*-o$;KQdN$3LZ7i%70<s&1r+Q;-QXu$Ci z>O;3ewx4ggPM+qvAa;JbPZ3FkXwF{vCt>YfJL~la#J%2KQ5Tbc*?w9dS6?Saas3jN zJ}-=4Tch^c8FOr*`XWkAM7|mb#i^;QiDEMWz0mjb-!=(Hi8EgGb0JMTV@e9FN33tO z^pI(lMnIXoEV_452tKA<7fkefZ_izMkwiq4 z%qsQUZSE*c*s+4#Y_(9hbv?{WX5lo}`lzgQOHdrF{;c_vb|My_N}&XlVxOWQb(lDO z8FZpp&`({$3|}u4M7rQ_7Tn(=r-MJ@H&|Fny=na{uG)ff{)B?WmNa*f43qMFf>>NH zUj`O~K%B!%WxV@K?6tIfkoXTxyoiX0&r19CZZjy)ZRM@IOxANj33AMDsMqR2kv4o= zLFnk^g846Txxsu)+8(gi4{(J$$S9XOxmL;7dY7GnGU*j3$n5CUE6JN^_uATt2z<1` zPA1u_KS|;tPk_N^Bj#RFi|oj8CMn5S%quhm;;K0M$nWQym7jdl`sNT z;iEuEEj&&85U#g%7xQlb(h&4I{dX&OnxYB6pQH`h z&rm^()cD)DcYk-IrI!(aJNLs_;3Y_Iqy8^TEbJ9*y`COSk}((&5%tYU0_FYchKO&eahrJ9)kx9K7AI6e=q#f%2%~yJmj%!%q@2sHkYQ zx1naBX|WG~!W=^v`fH-G``JJlNH}SDY zSMx!*4h2%@8L5-rxO==9=s2=v zPA?9`=gye@KYxIlrvD|j1cXcKI{PdEMkIny=(2YPP(bVMQ%t*MDy++7iHALgj%`In zgh@vK5|dJ{H5p2BKS+$6{5m!`CR~W|>>@*2t2R0d8nAZ!r8>BX^Moi1Ev;VzJKfK+ zyr_PeI|$m=N-$!a9JGywd>LV5BGg>NoM<{-qA=V#mVT}t6ib||8XtT_wq#!__HUWO z*_-bQG$|UZ2*m4T{dW?Yygr8>Zn)}k74R@lHLBbrP$NTi-lK6-HE;4tb)DwQ${}&L z3a(iDse}Jt3Lp_!Za3%N(HDPor5Zw1=E!;h$V9?An#NbRD_n%2_6GxvMcibs9}fD_ zNF_L_q+OXKlrp@>;EzbsVI@P)CfGZCs%O=2nsO_$@9xqhoYB`ZRMKOP_^+*B+sc*X zHn0VmAG^>8L?74>7Ngg*JEKx+pMu|_p8=2Z8`p5gdrDY9{#LfZ@`ut5 zP!R|2{doWYg>>GVI}q;QRvb%*{a1%^^!z_M3~Yy~Sg>2Npbk+YckvfYRc}uIUyL6O zem*4d;^vp04qg!Q6euMXjit48n4 zow@VA?>&C-qtB^2Rdx2>wX4ors{kY^x*x!#e?x)%_}C5QqV8`JoAaMKIIay-&ukA{ z%%EXFERlIS|AYZacNH<*X#9O0Dv<>};P>cB<$YZX09esU9sj(4C6!?1PTEx){z6lpYpw76(*-t25;ols zi&^FHvq)O34%U<~WbtJ|_wP`q;3&L@43~IzENh(bX1~p=!+u zz@V_C`(`nSW%4__AW-K9uj->Y7`sE!b8~ZmDwHGQrK+PddFoD1>DTwltdA?4@O*00 zvwZw4VkRPCalePq{z!(GtgEB@n#NNdquJRbq?u27-uc_jxGk5e()OtW+d-bwxydW$ zQckP;gm#2#2&-&NhwSsPe7{l=E!)R)Z-`1L4*!O-3>Jf1*Yp~W3!K4hkAC?UkDr}_ zCxww}md<+t0ZIl^jQR&!jq}@oqdtKzn7aQXq)Wo;UlIS; zHkWkwPoum4uG z`GnAjt&*-r?d4qRReczkl-`kf2Rlw3_WcjI(3SRP`1I`C`#Y5Xg8V4Lf~m6P!MeCr zAIE$S;D!Dd-zt<^a-hkyN;wostP^=x_BvpHg(GB^TmZXbI&zp7EkZ`Q+VtR#NsA{T zjj8+B?x>-mp*KJoMrjD6`~Mdz6udaTAv~Kx7DV4bY=%Ze2_Q6IL_f%tF@JX>Fn9*aj#jNQZw(}*^r%9TQDuQK z{QW(}*Ey1u7STYxtoU`wGebHQ&?C^~R;MOSP+ip>DK)a+v6(^y)a->^{`wmkv)_qAzY4DbKmmcQ}@nUYT{NTxKm4rFudRCnU z0Urkb&(R7&W=x&p&PJH}wU0X1;2uHN{AkHr5G^-nXvV$7UXrAUf-*n}v&$Nr#~SYQ7Yg?X7>S`LQ8 z+fBpNO|5t1yHlORbr&HJWLBx!%_Q7W4yfF_c;O#6fW%xIod3)P2$>CI_!4`9&YCHZ zZBmhx_N!5v`D)RC8~Ru!L*Kj@IqYMMy`GgW0j8uT*Zrkf-AgI~@1N;SjQ2=BBtru- zs-vFFb(4VtuwbvXhNlNs+ky+t$5wT|eKAJ7;Wsr5d)*+>O5y=8#m^$F=tzcWNp<2Mro|@>g-E5_U+EB#o+1MmOa)W+zRT1-&m1@v~nzKnJO}!H`i+l&a8@T>a zBZ36VC-&oM1&nz=(m9~Fh~CukrpQ#R>oj!=ggj3-U*nx~@Gdl-dO@M+4vR24Kv+?Gx|8X} zrhMcAb&HNgBPe)`^Y#?;1fNSdb~#YF2@hHIh$&O5+iiyKD-`W?96l_5Z8Vruqsh{p z1l2Pa{_Y_B^n;@Vv)GHi+ywDj{xp=DC1N;ZO+FuFueUp(Y(9vT!Y&*&E%)s#QHV!tf0I~b!1ub(* zR*JMe^F{pNjHr=7;%bI$w|LSY3?(eL{b003iEGU(>iMtq%x0WSSr|C|NEC>v{!S#9T;Y7e7EJUg=5i;j5)Yu&w$CVmh(kZ zK~Kc^tvlTFCr~{Rjl@F`j*1CgnXTyYHOM^LU}!>7_>#(_ z-B1=Pdh>_uK(il2!P{0|ISPD);YE!)OnM~;MHYr20M7*R>*|Mq{3!h%AG}1(N9FWT zi>Fv4>9?L7rmC=dn^#YHd~M2ffSyu5JC!9x#_vJsiYCF%^da@p+SmGsIXh_Hjs;|I zI*!4VrZIbLpBA)y%$?FPTX;zMRj^X_y;+NQc{{~b3atLk8OLT2Qs>JvIY+t5H8_Y2 zGS+#IRiL(Kjs1vq0q0`_&CgCI)S>nHwVSX>RQHxqwAky`LcwFu=@g<@1FE0#l~XsN zX8m|Kshf?7%$c);XbkbG!80)cJz0~fuO(4@OG8RwS@WQk{g=zxr?H;7&;DQc<<`X7@ODB=eYwh` z^EkU&L!a6twbJ2-$UZxZ!gE^%(xiG4$G_%F&Lnn~y}k$aZ83R!FE94cl@rgDv(loN zqh)c1mB;W@?!OUcW!W%)XlB~%jt4I}unbp7!p~`0~<|c@Ype>bc<6E^i83?VYpbmF}PgntUBGZB><(MiY2RCJW~>* z^rz%wMUzBdDRjxFlND(hR!ta6nHI0v#_FT8*%gG4vs{f~TzOBKa|zk8?s2ZlFxfG1 zjGVT)u8V^nwr0{LXVA62ZYX0w(QL}$m$r@bjMy%FvTAsvHTR_5^{Gi$&6u`@3N?Rlzq+QKX>Y7k zexIYU9<|(EvL}_W6%h&YWb^PRaYGB=OkDBp zOXEA@)Ll92-;__9v90b~;>%u_cj|XoYC-vZ)DuVcZmf@sHdl)#Ml%wY6I)sdN9p?r zA}BxlWA`fi0;?`8V}NIS4j4}MwKhI1UBg8>@$fEotVkdC7F{VC^@x94J0A(sFI!h?uE@W&Dm?(ZDln4IqF4Gn3d6{*a zigfGur>OL#u%?;K)_`r}s%&%vdF9*@6;{pFe4)`61PW4?R?!er5Ck#v^+|vG+9%lo zMnk^TLd*A2Yt`~nFj|)?3_X!_alw?-q zRQ>(`?OrO~8?&X)L&-2eCr;M#6OFo-q_Jdw8@VhHs>>d0r$@n0?0Z}_QFvFSADzSfn| ziNzLE3Hzu7iD zuh9A6;jw!-vgmXhRn+^vH&TMhEMPP&^C_9E6}0hW@I~wrNsUY<2I8KOvO^cTU%rHg z9=w(|~#TgGB!}RI7QoWj0LE-gLPWqNfW+ZfaRYKF_(-Y#kN)CVj&sEAn{r#-Q?JuST1SvZ47ac3i_n zeNHyN@}9BQ9V`b=Uv^que%Uix)n;atc5_fq!mLz^qx=eUvp8EeVcV~yW?f()fz73w zCa%AndZ~PRulw{K1c9#7*K-kR$F?Sl6(>pG3u0U#Tj+k-B=~P`a!X3Cr@PAu`ze{)5$uU>bg0E(>vV8Qu=`^bK|ldv$i;)3QdxfhPYfT0a)qMsO9 z3DYnSUxKhuGJq*CHJ`K4tRxztT<7$s91C2K)6A6~lL5HME%tjUEau-$E7LNHnkM+! zh94vwqkzwf=G~i79c*!5=zoZrinfH37^6K*m+RJIK{l(ecxndE=@-FvdI#I%L8=b* zlV4IlcpTsP7^P3_f81^}k~kengCF%77k$JNa$475;`*!c*>%5YYMBnFn`c>^ZXrE= z4l>8EKTq#&*mLN(e(!(sP$9V-`(nJ>l6m-Nwhs9kIFru<;HwY(HXkU#OkFBQm9g!4 zU4I3p_g_7D-(r2R-v2~TL24HQ(fl?GMxbenV^EoGi~pN&SlOfgvW(Kb2`dy=FiQQY zF@DxbIA06delUVV+kEQfOBXr#H`i&()XLkh@!0j>HslYeeqshe6*9tcBZ#GYi40$6 zU(6Uj>JE9c+%ZgW%u9%J4``X#vZkVAF_m)cl+w%yG4V_s(RvMSRyn>%+72+%8~9m@HzAHR=!gMDQ4C>&$-)HeVT1QGj+fyX`;P+PV@b$-G}IMsiLsh4t+!^>MIF^AwyZXP?pbCF(W%k;K9Mef~?v_Rk&nDrRO)HZTQm#1o^Bp0*-E8&|?ltGeyZVO2+^1?yR?QJsWUu4rNY7GTZ?f8#qUi}($%Xg5SYqs z?@K6#QrRDoeu~yE<2uvwyg@7P$Mv1CGk73IOBtTDK;Tgz8|-Q4bFI7ZI|=mk9{zLt zfL5cZdzQ%O>(pR=y@+3YByNY+Ss8cw;&9A?#j?LMT#;=4oY&buFe?Xy!$Vg=ENW*G z32aijTj4g5W#^vJ%+DKWg;8#hZe4oIL11568Nvys?No%x^Xn;_ry>-Fx3ydY;!Y7< zs`SjtK^aX>u~p?;=kGC}AKlKrRy8g5u6dHxbAwCe7Z0HX$E@`uh97~MdgrNzb_3Kc zn5)*M70$`I^48aMo~?|pUiw;mWAjTMPrOE=31ZKL;oqSo&#pz|A_N(|Y}c|$(BCU0 z`+oU#jbQB1L4a&k)8&tYGD)qWq4B9%_er5%0r?>F2&Us0@zJ44Ru)ed`Eky>#SbqT zAFKQ;9*)Qkyr8sUqnATxH4t8=4DKf4U^<_jsQA=!5W4p2U;KU^S=;TN!ca<#zrAB2 zHFU~zk-OymmDfNZ!kTt0zyP2Me=er}S#JD0bi-#J{WDhnHCHMa80u#tS_aRsve+H7 ztork6+6(=+csY%aco3JYKoaFki}cr|!$nZe^Gf{{-AJL0L8U&uH=Ab8hG#R-$;*iT z@;T?~_|u`egPUnNr?qsGNriS`@w3K-Jo7ow|8sN^1?&VSSQl+mLKOf_w{50#=xd_b$&){t`lp5h#~fE?)!v#-+m z1>$=NvjKxa94~dRM!?Ay{by42&we&Mzisa^oYD-!!4-a6Qk!+QvM;fX6+08rAPw{i zywhYDjL=@m4eA#ao2w?MKiBnMnNRhT|FoMFifFD+nlg+i_ov^k zsgre5+|=IwD^+2GLb(ux7=r#`iurx%6= zKTUW)CoEf(K2~zxQYJrhen_xQQZ7!L{M@tdZYqLYbmu@T+5o(2CD?$n_uk*$vcP%9 zpQLy-VBjAn$EWir1>bAi{eAHXNEdMTg*LQFcuO3lL82|C3&(@LaY3ikxXF}xAd~S0 zGuMvsAA9^*@u#5dZnEZR7~cj+ikENwb?O<-1Ljz;eZU5}#l+Q~ zj4)URW&T^dPVqay?)PqfVTh!cg?z=+2%GdJ9yu+i-h(*izuikVm<;3D7G^~aW(#nc zw)^ic^@iXOHGsdmIz9n`7a2#F%#}7i`$p1q6EmPUZ_u1+M?YA?g-yYy^h~5N6zt+g zd7<=W;CPwodV9dP5OMh`Yi+#(_!dOH0hg?nJhzGeUOJ{H4&7+YJ5Mu4yEs#WCxoD8 zr6DkxXDm=+v4Nu#r`LieY88FN#%3 zU>j(OoPu>D1Y^C}(Fz+4p)q z5Anz)3#Za8lZdW(;5$?)OW`$pqz@i+f*!^E&|tmA=XPY~GcsSJUKSg&A1ijXyImu^ zVJk_h5=`*Ig&z*0`Wz#E-gA1(?J}hHA+k$hpI0Ae_j_x%T511yByFyHt6A{|i@6nk zJarGl^-}fG$-$EbR)tF1BaYNf#=M7((=t(aov@;)d=)QK$@XF4n_9*(4_`gKF@`>M zCvAFX5zT*=CpT5B5DZB~kjrRmVfX44zj*NFfqxiBB+sMbYOtO4ZIoSlz@q1m-v87WE}VA20A2;T>f8DjEy@>BAsY#fGg1Rtc#vyR|-0c&E=F?6y7x9y91XOYpv z^(gVXG4e4?mk599vOtgx94|DTcwP)BwTrCpl+QYKmyfLE2`EKQO+{h4sOykN>3@z@ z(yZ`hV2Ll{=LO{J_-kmoQ{~`nOh*QjdU2voEq1WF91q34jNT>f;JG(CQI>b;n^u{M zr>oIKCVCalwZTzmD@;GKy=@tKredQJzzRHYsz(z~tA%dl3e+lGW6 zu_+pMg$dOdfxd}X7{C&Q_|18|cTZI>KR2S{;EBRx6}IWkbm&lWudP!Tcw>7# zTxi#Tnkh`k;?Q1mcAq|F@T*RfMW1k#&uSu?Hrn^LezmpiE>x_#k1#xKDv;-s{wt=O zF|P{s_d|+R9z|-gso$+XN0wC>#Jxg!wtQUfv~3Fa*%4#=i&zeuA7Oh=X!nZecztHK zMXvTOha28dL(FXM@NV}&yy<+Ibtk;r^5r^>R*+#YU%x<4#cs6TGR`%d;3DqPBl~Hm z*c+1u%t5*rtaBOXnGM{iO!Z4Ao+2#fH)dqr5)@wy2P2lhJ8M36F@!Y~SVnYed+22W$#m925wN2k!Oge z>;i#ny)+{~%5y5%EtTi&8c9;hUGLO81{zTA$pu?E#7~TN27z zi+X1GS^#YCF2!y;q2J=$U%9j)mJP$~HM*YW-vszKXViyyrfLngm*!l*ItA9=gWHBv z`#8DX8;IF*5sGT^dO;yuOr&usQuXQx9#nsUM+xS7EldeM%2Ob6s;unr;tGERti&!o z9)EUp^A4lmz*^^QgGg-mzE~V&S`wAEMxnW``80^pc!c5DT?6KmCd37V+o!6qlWY&! zfi!~m+3qw&{J|%4?<*6k`bE8D?e!zMhdr^dTRA>vH4Rr4 zCj=TpQ^_7~O#)H5q3C=p zg4Vo8(=4%B)xM5dnq*3MF1M#>E!L2|FkV0LK6`f>@w&sAbE)d3W?T=$2Bn5O1nH5D zcF&V6X*}I{TdVLxM*)QagSnp8-Cu_%(DdE3SfUb~f2N`A4^{ZBm+ zDHq&xAPd2b70^UO3svq&S?qU_5h~sakU69j5ee3%pKICo(+LE${;2>zd#?XMJ_ky= zx=xrk->SiOJ#IaHdUCVyoy^29(YV2r=B8tMl~2^|DzY7IG9y}2J<~t&1BXZ*O}pTG z>Wdx*v|3N|oSAnEYJ|RGjru z)f}+a1D93kP>N$8@$r9Hs7t-@O(9On%_wuwRXAA4x^v0Mm8-u&r`Czb>Au5|jU(9! zZ6p+nsrbWa+2taHZgHIAxS_;P9i#`X*1qkdt8mqt>OSRcw^IeeJH@e$nx3F5^6K6PGKo9Zag(dq~jZ1k~&^)qf~+!x{~2c%1Xw?9I7Fl8)ch*N?)m3n=(jG#}^*VFhde+br?zy3yClLrT%7{`n%d zRqIz_CjzbVy>9AFAmknFlsf6dSTU<}X>r+ZjMb6dmWS0VCOIJFxS+AVA`?H{>O;<{ zEGnIK^pebDAgA?QH7F{s7X*>;s`UBeo%L+ffQ#5vo|dJiaqg|`iE00X#Ed#;*jKaw zP}`Te@6lJx>R+m_tuIU*ch!6qW5CF~Jgxdl>tpuy`hg=rI2Vuja-9bvEpiiOvUXc*|nk`v&0DJEucXAvG zTlqX5A~8y8^$mW<-ZK}MtC!x;-0u%!i;t+Cb&l2{qtNR@@(0cS4!!QeENf_k&-hwF z5*45?W))4c*A;dZ2s;6yHiusIBRe~T)bY#ju8};xP~TP@@Xh+>Ax;6t6GHHR6?9q? zc{s}L8F>kvR6>K_f1yG0?-Bdqq2V$gaPb?tC>A27UgZAgp!IhPRt^2MHv&zk6=(Cysf(SMQO~itLpd(4*XV;uXy4O1W{JFIG|- zz_MUAUzt4oKF@6dTAk~Pi(A4mI8^4%JKn~l$AvTnhSxD9!1GR`D8Av#UOGUW@BQ#_ zW*!nZ-anm%PkQ6m$&klNVxpmAlF7--Uz4`DKL7YOU8a1k3+^@|Ao056$CyZZb!GC$;C?khV31xw=7G9u)H}A>oAQF=m|z# zHZ`8{*ac_*$o+!0sqaO-Te{%2&T8++1`J+q$7fmC>D-l(giStDTD|#->?5W0?P3D* zWHbayllOf)IB zC9V=aoxBf|Tnv9DwJ#myZT_;-d>u>n5)j;CN^8c=E&#TfBkX~%dzRpRlyIq=Fdqln z?Eq(>l=N3+gf7Me)Qce%{5tn4eSLi&E}uV+ILDQorSm0z!$yOv>tJ4E{AZx3IkP&} zKaGuHbI?A$7Z)*qahJx=Yp`7usqY3W0BcEnOqQAWS+8@n$@<`UeqliZlUN{Rvz6Ao7+g3u|OYHx;@_!g6P@VrUkr@ zbDxO2ieUVEvvIDOcZpp0K0*UieD+MPB>=F?QfC6?HFKJ`Z-T%rfpF??2H=geIPnWc z;&oUifaU?I3xTcW?dxa(^Pk=ebS(Z#EOi#++-J&hZ{T6@2mCUi#k|)%ToN*uguc+R z{Cpa~)^k$RnBkA}^Ppy3rsi%g2@^b7Pco-{k%o6@Rd1p(1hL)J#T}mz_{RGewpf%MvL{v{da3njSJL4ev%z5 zTj#sqTq*QA1`?GLaL(kl_w#Yi;G>x;4t>!h`Sw+|AGilSD2CVwIexcxM;xBK@;C$$ zAtMaG@!ryJFhkG9bJHU=lb49rkruJ@XZn$i1OZsL4P25YZ(9pK}V@ zDmhoKh;%7<5On|Q_dK7~59JxL4kh{)6b8)A6dW(x=oYcgb3@7+g6Yc(F7D)uYhDq1PEf??plZ+hNc&rvY2 z@3F{S{HVU@$`1%~Mg1MVJUDb>Q0!3{ut;iWVmCFm9=_b@gNil!kWK(<<;KuyZ1^n1PQQcp^%Z`SQ+Ei-^PfVK)Wi0x0i!Xb>1a`%6h+IeMV~F z*2S;L=B9`$v|C)hX71Q?VgJ3^hpyg0P@j<~u+^CuNltW*4u5|iz-ZvspmnX7U-xev zB3$G}k0saH<9Ey|jrl)ZsHvxr$pHCE**<)xt zc_7vO*HaD=y@r=}d}6y}xehS?p^LcC*wuA>oK5y1_}@i%BxzpSenU?VmVHzFd*E;yTds&Zr1%Cz_XMJH%0!XzQ?6Xp9rsG0!DRSL#Lu^LEC;dE1xn N%c;s%OFw+_e*k5)Nq+zU diff --git a/AvalonEdit/Documentation/Media/VisualTree.png b/AvalonEdit/Documentation/Media/VisualTree.png deleted file mode 100644 index 616f68a328896640353016db3f36d7098587ce8f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10086 zcmd6NhdZ0!`+pL#SL{uY>Y#Q}Gj>{~Rz%gPy+=_LRazrf1XZI}QCmxiQCrPgu~%)S z_NYC-`MiJs#P3}9InTMrbzbK_*Yn)ZS&_Orn$#5R6aWB#`Vm4+9{>PC2-$*+h#;w$ zw$3CxfL{8VDuAy8oa+PzY_F`XOi;y9URn|pc&If(UmF1M7XSc)Ljizuf++Ye0Pso_ z0N8i|0LZ2Q04yHqKlJ1Q03v|y6GL@^0RR93fdD{41|R_d6bOU_f>1yt5`;n#cq9OX z0s)K&QUDSOK%qcLBM^#ELlQCo0|H@yAS?)p0ig(l1t4(%WHk^~jRas&AdC?Ri$r3O zNF0(N#9#mzEC`DQU~m9TH3(Y`z~DhxJQ9OJVX;Ql)yQf*61R%1CeRv&&@=!j_hVF{R60%1Wo z44|5z!yvK$Qy>XCJO+Trfbdul9*4wNBUf?A)oSEgHR|S6JUBS`{rmS}VUf|%(P(rm z27`%Sy>;Fay};KCZ~M)lwO#gQIwfgf~l^?R##VJs&TmgRlj}vhQZ@8 z_*D%48iT*V;%}-~@wnAh-0B)`^%}Q&gU9@*U#nijW3Ta;8$9+uW%czc?s~Plqocon zbZ%g59{;~IJ~+OB$FJfE<;3F9B!QMjrj|#hmq(|U$9}I&%>J32Bhc#f{2KlSKeMp* zd-3nw()#@J2L5IZe|?R=z9AF~E1OGyww6}6me;md*0%rr-C14VUE3hg-rvo=^{u^) z?fuQ2gRR|vtJl}7H#ggRhr9bny9Y-E?)ql!;NW2I-|@jAflmG%ogN;Z9v+__9iJVa zo*ti`ot&MYo}QhaofFd8`NjFg<;5j|t}ZXHuC58`=D&CB|I@rOgjCVm(k%dhzv_{ivZ0^(c1Cm-=QCuN-1@C&4BzE_ zd|LWK%cIF8%3bVK1R&|6ozNd`2M!tq^>oBA2pvxf+wUp|+E2$J6oseY-&DI1FLHK% z@_kHQizn#0sjU% z#-Z~6w6Q{Wo7)aHdAOFVI+usIm%DY|7Q^Rm_^&T=3+9uXc4Pe;oA@l;xBQ&tt~jb^ z>i@a7XiN$Xr8h#*GzoF%}DEXI8lPPR}-#uZ>D3#*M(W3{nPZ>4Sx@?uRMOd27u+S zrvQ%a!H^KE7emcUGk)81SA{4MnozPOcqqIueHR^e$bG5~*l#ET=v$vPfTl{h(oXzu zZ)nOju6Z}~C%cVqM3ekw} z@gz?w`PCtjT%*1D%rxt-7^f0$s`UL`lI19RlBWgWz4O&Wvzc2*f!;=HTkOD$&R*B%Bu zUEm5S?Ur+Qj@-?Gj{~!-hv$lw@{*90b%B-I^5E|t&*y-tfnVU}zFz*prdK?R`}-$O zBCWqN8*sEB^JQVmPzBO&3yFHr(?T9Hf7A!zY%tuvAQ*t81%^B%hNsnnajMZHLlJ?8 zZ^UU{@A90%{k!ruUGBen85LA8U0<*~B~ZC^gxU2AD6tZ$!e-MtA_}GglrNAO*s#)X zr`jaU-!b)1RreN<7Z9>_ z44jc*)sq@hxW+jpYqhmCHr@T|WjCVh)g^y2{KvnCTp{27MvUDVqkNx6I_Rpe#EL?$Go+h$ZBZSGv>o7OyQ7D(mQUp2hMiuxry$THG9 z`9a}!X%MtHHgI#kuYtrXg+o4WwUP2Po&TI3+}iAT0U@v1vi-e3i#@m z6B{T@k$2MK${h?}fnN{#cg2>IacpM<5lJ#u-42AoSK9Yf$lYQOfG%16YxYNFnh(Ho z{57k3MIzHH4M8#a=r~3)=@yI2I+x%py<*2Q55cXFsF;?urt3%cS#}%gtPd*XPVto&lBI`jxS*A07uogpNaGcZGjX&zs~AjT-GaQbu&JzrdUls4mE811jF(o^);R9Dpj!!(EYeD4N;D?v5!#8>IR4AZM_}MUvX}6}O1Rvoh zDCS4cx8?J)hT%QWZTkL zmIm_s;cI(uz3kbzXC{&cq_&(;8XBcH^@YLhUmp?Yff8n)kQ#Sq6vWyPMLP1^Xw8Nc zqw5-3zgTKTl^_msdSeco)}d zUrt3rKdhmv)Hj>Z*={FZ3J|?sdD7nDP!gEa1D`v}RC5IvM5J9L;5+L#1q}ssM%Q?Z zh}EL$9ES694+J0f(N#7=tf$dNA6<#e+A%dv(BOeqgB4cAkqU{u7xW=LOo7Vb591xD zd;r)&sT}y>uUx&qob|ppt{IzWiILIXtc4T13c+xzX*4MQnH?as*ov{6nn`XluFt%u z8k;hYKIS!lFI(u&3n3Qmp*`W%mb{g;Oz8Eo4b53>cF?f-9Toi16WhCY*iJqhAg7|~ zC9Yc#VJE9>LhnP`FE#XeNMiEOpK^Ww9O82Jv^(cj>Jam=uW~qv_^ag6eR3q+3N8p` z!fr`PeGG$BWaHDlj3`OT?}jYDTVCC@@wEmnRwi!-f;jGOFb-R^B`V!sGw;^v1h#e6 zuBN)5{vPJWp2G9}+2v^;^!ZMR*VUwXV}V3`EyKX1!N?`kE)n{mt;Q@LLK=om3TNq)dnlcw%jY4 zliT(;iE}l18DRN*p(A`P?xj!m(@=0?>3E#{1n9HL9^Vm0*CL!KAen82h4qIhU9QJU zt!Uq?!RBol=A|!>fL9R(Suyv&aff9D%j6<9c-B;umjGrd~Y)bzLUUe~H zSq~@>#ISlM8cW`*CO%y$@pr1CDxc@ogmIzd4@knWYWJ3+?cep z&kXN3$G;U97uDv@If*ssaG$!&LYDod>Yk4UJoD)I$w5QrHz~uO4qRsV{!SItOs=OX z#bf$YEBZ|0iAT4VG%IBe`2%niY!2e6p2Uzp3)k&_e%50`{q{uty+bwKkEJ!IwD)y? z069&3?r$SHhXSR_Ar;dx3y=#T_xEC)z1<}q8G|7;ACFI-cp$dfXB+lIjLDjENyCC} zi;;e^KhCPH9g(Ys@v^SbNer`4FBMp<%X;z-0NZsN+l~)#gV%4U(8=7KR`*v9v`?$~ zb--V@Hr%bP)MK7?Q@&#zRi5jNFAqxdQB|SXQ)=3ZCTXpk3Y5gyAyff++;5pk-wCGE zbLIpw$k+n*iR@j185L=XhU#cS3Pr-!8a>TDKSG7>g4Ou1@}w)wezgaizA^E;42#Si zQiRFL*bqAYRwwuNg0DclT06W9Mvac;r*n+_dfO8EXb4Jz{-RWy+&#zF9CmmSwMSu3 z8X?+Fgi1^mi*Y8uSj^3U%7jv*$sYt#iVag3I*}ycuSQG|L>W#Nl4yYmxJ7Td2+J)c z2>1OBLGe)Tr6t4M3y)FT!;DD}xK$J1*%4$7PQife1T8hB8I-F^!!-st#fiaI1-ihZ z;MyPCo=T39pNa(-Ml=9Q_J^FDpGNonqq}*RVE@iIm!Ox*!f?3{K8`MKIfaAi`^A==`2~720CWmOyOykUwD()+}Yfd=05TNar1^4);UTIIbm_K3MdUWWKM7mq!EG*xre@# z-1kuL2mOke>KU}$Z*11-W#_SVlx_FyJ%!U>X|QTm&ZE!DQwlzi^Gcc6uev_RHk)Y9 zsX@O*7|1PaA}g_vKK(@^`-5odnhrNq7a_Vw-4r{ zm7(W-0nS%}Ht{1E5ohw@dt%o26Eb_@9K3Ob^JLmfJ=Ats-Fe6-v%}IXBcgJMqIEDB z1C3X-0m*X$9vyQi*JGa)cS^Sp3j6yE$>@30j_o#efyg^b`j z_ssD!Seh3}+C^sxN9@ecUQ~)N0ycMToFdsLatap(-C}TtI*nn^mv0-#t0^kpH467&=4u zo`ZRm=jGD4N_H%^D@)zVDUTSgT%#>;%SC`B^tqOD6gvzW2@rdY=;o_J|B{qSwQ&uV zdOD&h2w-Q>9F_AykT7xv9WnHwNT5nHRk-=&Mp4#%XO@H7p zSSC}&kN%co+mRNKAhGV*pYgrn{=M7i0abr-$202-kgfl-MiA2G>f+c87|B}{YzY7U z{6z>e{g}oio8<253oh#f+AM3V(_k2WMvWJWZIGaYx-TjXp#GpEeeoCxAw0y&N#Yt*koLJk7&^9hu9)z zQjqG4=vLp~;o^t@E(5MW8x;Yg*(bJMhblWElkYpL;zc1k8u`hTVCC0 zz(VYdiLt(th(!W-n*vK|D)ki6WvO(cpW7 z?i@`KmAsx+N5@OCHIkeCs2MT;qcA}-mV$JRl8z_1KfaBdjX31x3zZM|$ms+bmoL3T z&+C!2S}csT$ay8xx#p$ob7E5%TQ1r3j&oy%1Pfo@=J?!Mwyvx*`eO?e~ z!H1zhkozM}A&yh9$BnB$xk{@9Bz`+;yKPb+7D0Lg0t~$!)5(U6O#}P#xsIDv3+SEk z($ti&cF&5=-|9YzZ8qOCTV(95ivp&D~zGP?YnQlrI4?2!gz7j7pK}8tBX;n@k}DpsWWNwGmcvSi6H?(pZ+2UyclPIp6KB(Us%-}TI7yHF@M7hCVX z&J(6oRtVKy`sC$~BmS7kBECcrNCEaLUxSswKwW@XjivuXPGtCV5%WaiZ!C?m?APRh z%Kn4vEe=Lo)Ai~le8fcLhgge?W`un>MTCF=p8k_@?8Iq+N7*c#sqWEyn!)vdW*wkM zyLdfI3wS#yJB_~eGytrv;q~=bvhuGnEA?Pj% z@fjCHq!2pSQB3e9!GM-7I&waX5~(ggVuMaELAWvr6EqA&2?67Cav`Gwf0EWo^|>h@ z>J#UUuD|U;O>`{Yqr5w=LO-6?D%+5%m1BeEJ2sU@`E36Z+Ssvp@zR+$O=9IDKCpOV zv1IpFJ8A0UTTy%!{bHpLB$TPC?|iQ%=6k5xbYpQtzoH`fL(@q{>#I#kwk5ZfC!eXy zOIome6K79Blx&St1oSnUAF=s`AQ=5 z%*Wn8TuH(3Lsv_`mNy2TNel%RgF&jI80gZU=KGs^Tq+7bdyIyr@YWg~l93D*`{Ifa zq27Z~iJD`z515cUaSn<|O0`5{Qn>uC>ruw2O^G6eK_r(I-i;KPV(j&#Tq!;{O++Xn ziEN&7DYwD@h8O0b%_2Him~qVXQOQGhh3hA*+$G&YV1Eo|9vAILwDj|jz#ler{1&B zG4OoZHb9(JBGL(9*D*-obX3iwh z+fqxB`c?z90#V_;4m#P4q-u5z^A~o8978yz^9{DtZ)}lyVCfy$Tn7jkC(<#onADTH z5l&C^UMcH_{mI*>crBZMe~huHeeViUn~Gu0N7@3_H138RmY!6SVYB>rjm-Br-T}Wx z`=v!CqaeT5<%?N$ZTbz`k$TflwJS?=DlWwT8~=5Qw;a!Xj%ArL^KHZz==)6*lj%vf z7e$S9hD5d$qmmRKe~0j(4^I8&Wg8GTyqot0A-{kQ>iLvR%%qIn$Uk&r8hHjC?+gc9 zte%{RKBcm#g?;)Ve}{5jnBt@2<7%w2B9b$sGgvY7T_-bp_k$y^maIY5g6S`+Xn>e6 zTlXzuEuLFMi;GtJaK$bfd$wAQ4NUZ=Aw%%Wu*PJ#fbnBu@mBv;MQ>tQcri#H*yE;< z6!xT3CH#b=HF0mzPP~t$$kv*ZHo;S<-GTpU7%m>-TPYvQH>E4OE8I|u~aESC^5>vdz zE0TZ-5^9yQ)2Thf8xQMOFdqooRiyg*egC~);B_907xHMNo0tug?%8Q8yDGEIpec!a zL{#y>_+zp;On^gBQ8bgO@xuM77=%Mo&2@#t;{0&_5cuebV^IiVMJFc7o8;k0ji~7C zg6;85{j01nfhr{y>aFe?M&Td<+^7#-UGyQa^Vk&0k{{R_80(b#xH?>!JYC@U(xsFH zO{R?#8$I_7Hbrv3l@Faq`^1B-j3$m)?eY`_EJf%)#XcyN$K*~V6WM^9;{jw$iRTpl zMz!&Uagjik0tSDqgVZ>5!6xbg>oIb_(;X($X3Y9-_JcLAyg6?WKkw37zEk7|XX9y1 zDNJ09vM0oY?~@_iYVyCmrjIf}%14JBtp+Kfi+_mOGAyq@UQX8grahxK_9mxh`4R|y zG>wRGOP+NVX)2Au43uktGGlI!GV{MCS$3$~FU`{qw=-14s=2l!IQCnUfZsEg76yv6 z_vGd0t;>}|1&H!2I3DV}pa1h+JWWS!BrF>Pk=3=ArAeRY*^h^4T?%5hpsT{l3c#?y@tp=o0?( z43RI@Hf>eLCd~f*_PScttEaw=+7iP+HK;24g#xd*|M&dG(bds>sk z!CQ{9blVUk=k!je>#4mtVID` zq~XB41R6FwC4-3p7VoK_W~FKvWk-2LT_T|Iek^k_LpSejeq3{;kU4?qgUA$Yuc;6I z#nPrPv^DjBeuW0x{CS3?3<>Wvy9o`>GZD8Z{A>-0Oh<`BC%oRsfx*^3 zv8c_=hJN%X{8Bx=U(V2NKMnKei{T1++`QDFA#k+>rJ5PMUCiqGen?pMA6BSt5>zal zdET~>r=gF1ckbj=ajqxaxM3VHls;GqY~NL#v>88aW2+q<*E5|71w zs45-tNoK1kei#%^_b3yKlOsjY*!|7}(GwvF8%Z`b8AX*?Mum1erk*K=n5L;w;G+@M z^YK-##(~u4bSY?&KlwAOj04Qs+7-ww0#k4m1l;87f_dG|lpC9%UiuZ;p29TqU_faRi?Q=6&-6aaR1G20`GE^02pRK8*)Q*Fp&14#JJ3!=IP#= z4e;YMTR53ZX2TKKC@X}L+QDpC9mcA~t9885X_|>_)C$jF)FDCmC$cDnzCmC;aX??1 za2g=l5|J*_?PtODWp4xZ$E~m#GARMb5tj@EKKTHA7xnBd9*QOAu~W6ZHZdHY=6Ipku(lUcoxE&t&p)R9nA^*Z9UnilFcP0tiz;{*2(AEW}=ALwWC{;fH=iR8I9qv#s8R&X|1kI7DdG}wIKxNiwQ+FTH zHMw{+^A3d(P}$J)MQD?pC_Lqg>6wmNyd~3q+mna9P}w;tAm>5_;16Y_7Ya%emSaXk z0;vM7D?#dQ52IHvwW|{$SO>Le7}er;@kW+w$#?7T9Fm`Hs1ARkB6{O8$B+cG;ho*I zgf60)^ZK4$cE1Eyiu$PU=pKlMk4tFzrp9pJEx^QAMNGC>fBbLUH(1F7(Dxhi&WZ$# zOlNI1zO`s%-uXD>tF$F@o7QGhLfG$u0zu_LY~u~Ra#W(Mo{QX4Yz}jn9=vi7`=~bb z@R|Ncnmj=3+mr_NCMr)~#I%%rWoFApHj(HWXywZcw-SeiCbC+X<xqEm>w)Or6Bo9ta|5+p0gX7s({~wPritXth zZ>OJn#|zMI$g(&UgdP6x!a(;Z;V|Fpvsz&gi(tmRe+4=|e97K-4~W)p9=MAM(B6}m z@_r2!{#4TAQAOL@cOMbzls7s@4$JLCtO%iEQme&ju#31RF}1|+EwRKl#?-J|wwljg z^}kB52wstGi*Y5a9?i=Cn|o8!TJk1w=iG4(-+oLhmTwzU$bFFUm^Kn{rt>Ajual^4 zgV&;V`3QR>s!i(O?dxQ5qw*zUvVN55kOwDX=#PFo(R99D@Pa3adx@y%5F1kYU5>DH zUJ$Qp5IdwLF=t%kpyK{v&v`H~s+w-`etmB7hNx10?AZuz)A4`Tj~=P(sC`v=@$UZs D+BCm{ diff --git a/AvalonEdit/Documentation/Media/WelcomeScreenshot.png b/AvalonEdit/Documentation/Media/WelcomeScreenshot.png deleted file mode 100644 index 524f91fd882e538911a0a2b3b8aeae643deca59f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 86390 zcmZU)1yEbx6E;kdLZMjk;_k)WOMz0{U4xY1ZpBNn;O_2Lio3fN2yO)mK?4*C7Wnde z=bd-Hng1k{nor4Yund-YTF|2P@=g0$4<+OA4&A%7-Rpx$ERR2wopvaezj(0U5IwTj3a7-zCm|%QuR!-_2qvgSLUGPxC&n- z+<&6@WX|+2F){b!58fa=CS=kxQndSXZMekNb6C|&Z0rAA?JdkbxDneG$ChfBdY2}Y z5633#wY4tINUaDo7+%{U+Z0Cl*SX*s_xMFNfZ!(nf4*;w3_)_mzC=j4#Bs&F#0??4 z#Eama`J&rw-D1qkhe!Vy`&#HDDf&-#w7Uo5t(V@4AbB{}F&irxiZ9OpUq3%CMWn@L zjb*>d=E&L*^pjoUqVw^w>>W)OETrvXb_vIZk*X;q$thTk(Vpgma~Uok^uPiY&c!|K zjDY{6xBn-skI@AOZy9eJ4}y1&mxKS}!b1OHmsNR}k@x42A8%s)1>=bnePmR#1wXgr z_YLk)?xK%tZ}9tiBI1LBA83!a)n91;Mg_*pwum|7*PeSHq#^5O82_q;R4qND^SJf_SeF*i}ChnlMIGX$l5H7Bx@ zR1~Z}i(R36GN1RYKdJ-NaSN$rB-s9U=@RHvBXFvi_pu%5ay7Cpx6I&kjpb_bPsX3V zeaaaM0o_Fb#}I1o9{U!o>@n=)m!w;pyxcm9w0zFlzt zZqDxNU-nuFdY-3)B&a?IJ;rZKK6`IJsM0NOzbtqYC~n`SQ!_m0zrex>jP*?6g9O`8 z%hWvZJ%N|HBctUfg(UFrVQG+r6qSd=5I}A;j#}YzWxfH&Lvm~xCCJ7KWCi*w@_%m3 z+k26OyVjSdLHL+RjQWDcd7-Ja#1FbwPyqNYN%fX{_5gfE4!fUkzHhi`^&8|7}W zE4v?m2qJ+JG;1&$Yz>6YCwrtK5tVDGrf4Srjl_@a_8cbCV9+M0*D`TIQ@ zLwov@u||3ECD#?)c48747IFprQ3UhI!NNcMlsWd|cSv50JvRJ*C_AYMIk9)S`FA{M z-~4ji0qES>bfTMl@FsB@?R~iL)M~%*t?Z8paiRDQh=ow(q3oo=#0h3aHUoAxtRP?8 zq_7??BcSe1PpU_Q=VW}?``)wWPBFbCBmqHdiJi-5UjBK34`jH{r?0kfvwNQYO+LFg z11_ug`X~=zJfu8+4q#3~+u6h%ciTMp*8?8@?01O)WrdOo-BErNa-{~SRzk%Uzw?jB zBGV(YBl9DReL9lvqG8l~(q&;hTQi}ZmfGy{a*rO?NJOW}XSZ5}i;)`m>%yoF^;<74 znp*BgwzBT&%&kR4I5~9}9RJFj+?Lbrh^XZD>xOOF#A9Z)`*-HAVO6u=vKn|j8l zS8JLJxQkmLq#*+%GI5x?Nb|v(z8fgCf`(sxx_kE~F z_nq;1=-=qAd*(@#tG8MHzq-7kHo-vgN6STSQQZfuGlhyEB{_c5Xa$ciy;+Ng@zL~Ao{%NAAuJtp!s&{w$ zlgBLiT)9|gTA5c*4@3Kv0JyqDj(Oe8z@-SDdLMPhm3%;H?`sFWY$1VAIQxh2^Y!e9 zlU+K_s!6TgQrH=OTyLvHi~<8o&Q@n}S|zTIc3R4%M8FS(cJt2%<&u&1KEU0rAHCee zp5m9!TXCbzr;gTs{%R+HJy?^}!vXYG;j{B8Fz9YkUlVI#a@~l^&(3Iag~ZZ`ilS9# zj?c)D%E!-tGNaeQo=U~f(taIYq5#M`5Ap$A1(Y<9uR$3l@D{vg;pFSkgAQjExCE@m zsUzECxvH%5b1PSMuf3HAJXh#LWoH1*1H33}U3T&OKzGZcbbCh9zg#Ld!@w=Q>?qtj z9`CxE)z|xR5kdxgn)ulJBz$J7(VLOtmtTgfw(){RVDjSn4^A(s)cx|K(pG+(pWgoZ z3@b(<-qg!t3UG2VB2Km-Y_oBD%QL%k>2Gbjj8cDoWbNnfd>&S`C5nL?>Gy~y{^7674PZ<>6Xb{MLX@{8^4pTqetH0M1}1pY+JZ zm%O3oIxV{Tc%7r|6U~2K@<=xSWCd%)(%jf1E^Es-^7wV`Tc!ntq?fdt=_efrCN}Xe z!ry6SJ(eDNz$Pc>A59H1p@G)>nLT=Xxkvtvj%nE^H=YJiq0c9Lk6RlFSk4Yp;X;Z$ z?a)@i{kBo(8TVe5HBHpLR^q;OBdncV$8c^7|DMOqv-=AwJ6rsP$4*RhIxYMK^iHfD z+4(KYJMKDC$$9NBu+3z`eg*%SO=>8sM^IDeZ}?6f9qiM4F2VY9_*pv?*0Mi{x^{3t z0Tau<`g1ld65zZLIBYd&R1zx^uqR}58@qffgbrJ-_HOxmtFn@Iev1h+SqB0m?zu;Po;!fK(RjMm+`2_6ceLPl zD}KZP2W+<;KpB^oM)`%l>)hp++V5x;_a!M`;`NB??paIRX2mr%+ig`fGwpHuS1%hk z-Q#jkax-08yyeAZR#&$wBfj{RQ?PgjsB*WESiF_vzMY#H$iwv}Y`dXJo8z;P)twb9 zxjCYI|Gie`j?NW>9!ZO)<|=l-Qlg$9mh@yT#~-ZK(?rT zJAl#mx&F){=y3n6gqZ2I1*&kFsldks za@uJ)O~fx4&Y-?VkIR9)u+~ta!@tC>QArV;_;(3WS$^~IA&>98??N(>ZM!jSyVa%@ zL&^{GJfx;eWmd;~AjCx&V?Cm^U&mQd`QG&#WIYZaUiYLcvg1wZ(q+_+d-P6}hOVCY zJU(=QdV~c3_MM@r7QNOv_y?r6Chd;7wtq;ALP;WOxw{biSR!?86d3 zyLg4XhVG9ygE7IM`mTT{;r=U^jA|menF1-hOVH28F}P%GvqWpW^wDOm?*&c>4GJ%6 ztqO*@!^YT0XE|V@cc&08W*JkU9v>RRo(pLp8Ost8f5a=}f#x^2{ zuX~$H=j!PsC+$*PjgpI_0^TrgHWGa4IAGB69#&KNAbNQd^t4R)x8N(`;;2?T@#6FX z8mL%XmClsTi7v3{;OF1C|B}c=G5N02FrEgV{2IO@!7my~?DDnGc6f-K_`@cH9w>V8 z5OZ9>e%aZfKbd}3Fp{;e44o%58W_q=qo??t8<`84`?c|XbDbv|_Rp4|ua<}eeU?a; z{00Aqd z;3a)p44)3VH#fUVE`g1|S>L?AyW7N$?`^I=;z=^WqbH?T*w1uyEY6R1?93;`7!v+| zkJ6wqnGL1EkHmfrB9r-`&0T!+F`N&7>hL+(dv_P(e! zxV4@E6J8u^Glq`*47azryoBh8kvz>p&aaXlS5zzI!;H*VWbIZZ`*s)a{`o(32{FZi{D*-K(7bO8dg~wYNiT5DEm4-eYXD9kLA~KIz6~(-A0Vt;d#vEj7g9ccz;i@Hv|8X~0(6Z&K z6$s<^xSg4KnH+?6Oue09 zYm0l&JOP$aYE%>DNxz zHmk?lJAN2HGE6opwiDPgn>Oil@IVz2-YeMZXNXQsM8Wp0in~yW3n}1|+^f}0h zR81*~o~ewHNN9>;XpD>xg=Y?%fY!m%m>n^PN00x#yP@%DZrPikM`3CTn}Cw%Aleb= zD~;N~-0Hn$>oGKjy%(2(Kjb5-=`koAx!GatI?N&=f~Pm-VDbhq4l{XCWOGOGYh#S` zG@agdWbO#SZ=y^}9|1B4ed4xxZG~!GBs-#&f%>1BX{NtUpE^uPR4Oa^5au%eZ;nxx zwNi;Ig(m_;QH>YkpjLU9qVZ6VyO4UZllSh6XNQ#fd}@ZMwpLLJP`d?!#_M+SiDeIG z^}#`?%#bJ@gpzrfw2H>t&&cOF7K+A;1BgA7D21GeCVjSUK4bQ*IuSNFD8BvsOVrGy z;^gy^c05c2+i_FwJm7kDbt!JE3hTz?F2@vATA$~wwifZ{rql3;TP=BkCePHVfKy35 zl{Gut=lSrNkJ^{>_cOcJSGkb1>3UXKL`csh1`DUN1EmFuvNT{)+&JP?xYsZk-(1T< zw?N^-sju-?)CtdGF;HW1@?crFq9eE!qEUMHjmPc?d81rzCK_-#^B4%TrzTzZYjK1G zjW94-w8K@c3M*MU){@HE$0_L-qJbyFYdpKG$1}57_W{Qv7$cE0cRDHG-nn#8B$u-s zVNRG8I(?ekykI|slph~i$KMMqUC9z;gb99XK7hH<|(|CvY=*>~blY)cM&Y-dtC zy|kxQlf^rvhKjB3VfNXBB2m~uk>4zn+=no6p1W^vMWWG~<=ZbrmS3aYiDP`L!ni#) zwpXuqKQ>2O8mleP2Krf>@t4Xq;5gDQ7BHrD+Grgo9gp3Tcm?$zk79O6ZKZBs&D~Ob zZ|KT{wHEOahrJAJ1kbF9)-3*sBMn(OzNT8Ikr%MUQuFFjHcSBD&vy}^T1MOCA6_s0 zsH{}1!X`KwJPlo0_s;@@t+19Nn#KPC9To<;92pnc-_0jYVQa~NN|}TJ0i?%Kq&3(^ z_23`jS!oP-^ceJ;T{TBubyD&|I4mk;Q8W77c1pdhO37PYQ9YiB_kl~q%;m$DVI(<=oMKRhoU?UeS~uOuU7o245b!UT+)O~Fq;UV zL|U5olJ&011(tDpu z#pO;uoH##ibNnrAufSCYFU52Mz!9hMEXPvvPoJjEeQBlgm2=E=DofeqNC{4c$295f zV>txbHkc=4Yg*AYoHekpNP7I)N!NcuhIXvUy~=@WkuZ%(A*iAWe&geHw2HrK{YH}* zrKio}frPED^J;d3%~f8_8G2IERj$O;EBaBaep@ja0-5D-;@P}^f-6RI$Ey)*@uKRA zK$I>463)G1!4)$Lh1xb_KBow!)jFn)bYXUrueYbN!n7-D*-)o(;hPlc_t7%$ytH6%o)KB@8kW|ke{PO{=|DqY>qCYezf>_7~OQ~ z4JBLMsT)$EVyOGEs8jmh5vtj?MC~>h)=FCJe!b#R&DPqdL4+Y7%`^e2~go zh}{>r5f&B2IMOI{kY+N)5XMN&@!%%~P#CGq%2UY<354q0s*Y5KbTMjLbg7c?$S9bU z=;-Q!JLtb)y|uDfgwjCL3YHi;8T^F7ht}ZPLqn`=IRADCV~hcGUr9}l1iDONd_|^a z5SOFJoh4?aEh`VrFu=}i2%KWG79r)9M}zBrSWQX3XfvQhMA^&tyZ~1z_6r4?s}Nqc z3j|pMC5^&-3`6$N!En-b4MNgEuF~FK6p%g4&?UKZR`H(MKHYKBzY3}{16nxj_w<|X7Wwh_`4sD+}VeUx;#S@ zJR!L9KFiiYD2#%BYko17%mTC=qv8CvBRZ+>^&K^#ffIi-{$h+u-=tVPEvUW5++p(8 z1a6n+=+=LhuDQ1^{VkH;VqS3V1_N~#C#RL({G{-%mJcgkHr!xyzHjl zn@V$9kQwVZB@c1~L})p-*=^7xjx=;-utGtwb@NeO86tt}bY!LXB|7{eWIjnA;V3KS zgDd7D)`2IZ6&Kq!u2PE$*jZW!sG;Z8X#+}Ybybveby)t#wlvh8>4V{`PX3^X5Rj4GvCP5`vG zCyQh(A)yvc({M|eynBeMaYv73s|Akb_)R)L%usKfi}O5NmnENfor;HxO6*wMK73El zu~iqTc!HT$uzn&c{-R-h-mUGv15XD|=uCe*5P5C&E&ppT#*odQD-su9!?-jq{}(yi z%BqiDjQhoI+X1VYAz%Dq`)dmXrj-)mU*vOr9*Jys(nuj=)Gv4zQ>DZg>;ixiv$B*$ z_|41nsQBMP#)?_>^8(Y45>Z84fRw6|9>9>A_OYC}T;-RJswCk_K@i!=@FClmjxWI# z=Mq5C2<|0YG=RcxyuV+9F1(W546-{(87GCKphj{=&kT|!eT9iq?=|bHUDVhu%K9)< z5z1cY(=AokBG6g4>0VVQizgwd6~T;_esz4hm6Ba7FYqbfj^($6vvD0t(h0xsMNb9j zZ)<&|XwWc`20Y8uaKUUHs#xdfja4Pu{x`1TDf@ttAKYS_L!oxk)$~5yJ)dFc@eA+b zxQOEJ${t`gzuL~7d9kTO?eM#6KPls`yNADVx$ZaRkJ7bHuGA#q+}>~dbyJyNQS+VU zd>cMuACZIY*%3LZB(f2UKwKtF{df)~aYN9rXWEB0a zBNYL3$tzb9ocJ7E6;pm($3*4n0w$Rw(qVmSn}Z(>UPNM-K*jl6`7X;}uBTVoM6v4| zcYhYhPpF#k@4DN=2ffk-Fg)A{Jfx7Myk6go=RSj!w*n7 zM;I#<21&VO|1ez5Iov|xk>6>B3K(f(?9UKMxRDfKCwjK5q2E&_i{PzpDm_fXM|h>u zNPP=`=RB|Znx^a6?cZYIgiLT^R5;v5x0Z-#So+2?*Nto2Q7 z_FE5O)dw}}^ySUtI|&FkC=X4*S(U#8ZV&Eh)L_p=yy+`gCUHegQ|0R+Od zAT~PdmtM=%fyW#02>aYer?w^E!yhkRBik2dGXz0TuG5Ozm~51(ArlV-N6Z5G+wMZu z1OyhKKc|iU(BrADdu9QHimB{C&Ez;y_$alQTA_nw!aL zL8jBrK~HM_yQ_2+2Ib?XSrQOUMtx$$C#-(Dj5&uo=IVIr52H{=3SN z)Z!a4!v&~h98$_BJn-)wMMvRQW^Cr~zyWyh8&@#qaPsQP(Tru$qnBr(^8sg^1}A%C z_6*yJ^bb=i1T;>D4w7~A&iu(yOC`9~)mduo;i? zbko*FB!xWRJAZtGm+3KDYWjTE0XpM!cwJ&I+9?D-U{Tl;^JkxMU2S@}1vPog*K&?h zPFFd*m-010Htjqqp$p1quPwUply%xK(FbXij%QMzC%5Rmuti()>Q7G8n5Wcy^ z*uaa6Hy0yt+q=zo_B!wHXw$FK14!#a3^L=;o>yiaXc1O+G;!qNxxe*pc~tDutjb4@ z(NqNi5^&lr1Ez@f5ZHt?iUP44m6ku6HX!r34d?^skt{~88PFSM<2)+hgWqI8(Ko(@ z&(bm=bLDDWEm{O3md(Jhgw@t4uxLr2LIrBQlY~JAixE*y8AOrTEm}+#9Er`{G~OT- zG81dx(RAB$h$9z99~XjOGBUl8w6a`FGP71>RYEw<{4-s!5);Bp^o%~JoDEiU$SNCU z5#FAxnXRxuZQ)(tZ%MWW0!vN4s5wOAw*m#v)?xec!7$bmFHlGdwvM8*rc zrv@^jZfxg=oq8{h&IiA^a!=|Wg&=;~Q(Vu}?PSgH^p^t=d_O*?Gw6mM(qs10=XT8y9w7BxYjqphC5VHOq-qadxqA)9V0jHpnhg(BPqq$_+Y8Bh zd9m^ffZ4gd`mq3$uv|;-vy z$ky8H+U|tq`Tg-xg2hix-)25qcV0PrZftch)$fO%^X7>I*LPCM&$C%2&I2Nf58&{b z_Z{=YhC1!l=N>7W?*pROLjFchY>Y5?wl=p)!`3P@S62p5aRi#u|6Hw3ZwCK- zW8g6f-nRfAd)Ox9QM{2SViD-GlZ_Bl(kf>r2*KT-`SkU=ihx#gF(jTcJWfvtIfS{N z7De*AXegh@8#V3LjyS!RYf8ED)4qEqR9N-mDY!rRM85iRkw5>JH znYD-1(4Mln<=QnWN&M|^GCy#vom(C$&SMe{34>TAhC0lc0y5`o7bDP+dA?{w4?lo^ zr<@xC`uS+a!wRF^)@REeF!-YXh#LeN<<%I<@|@#*n8ZNsS$NNK2=5njp& z4?$#r8Hc~ZF>O%n{AE65&XIMJN{k~wx*LL{(wO*HD9{Xxapdxun0H#!+~&|dlC?QV zx<65rkG1r~w#2qmYM{>aL~KdpLxEO>Wt_f`Sh7;QK;n~yWaa8{-dlR|p{7z@g##4> zUK%aThty{P#n|D*>`kT)29GZM{hKImwImH!%w{~ zf2mWH6XL+${NUDe2qz}--#*D`*n+7&4hO%@ZM-&ek%PRFFd zKG*dy?o57oE3$3{J6f<%b@~qM3r`K2GzWE{xg?6+?xjo+6OHK75ll-5L>9$8bwNm* z+Y0CcJMI#NqkW>8aD_}Yjx}!Y+38jCLBrtN#?rDgD`D#Omh$K{I0E;JEuHQY0XyeZx4;? z;KoEmY;vvdSF}hYDQD{u=)hdg%{+0rRNrc-n{i}^C(qwz7}4%ZdzL2Tuixkhj6ab5 zkG%+I`N7{$aw@^NOmaHx_3_^qS2-c>t#KMK>rhN@oz-e+oT&HuBemc*G0|cThd+7E zgdJ@<_sO5~IJ(i3?80^|-s}!uzODG^sz2+UyNfp*-CrsJUrf>j+F=$Fs~+J&-+2)1H7^gLpQ7zS+ z?W}0zrG^-Q0e^%zS%XRY5ybl8?aX3rO;85e_f^j!;Sy|{EX{$89t{o|vU6E^0jt&- z&I{M^!!MKOz_HgTBP;<&T#j}QK|BBFwV!+l*lcB^XHuIGgJF>yE1g92*WFwLFlPalINw<8c#?5VzJOG7fwKN?o5Gy}o;Q+=BAW3C)qFqlh zsp#oyGU~f@!sD}Cebl{ubn2Nc4`UNY)j0K*hQ)_pff`TK-V$!Sqi+jwHZRE` zb7FyK;&Gy`u=-q9*wdQtah{pz0`#89-Z7E6OAon0O<_C!2Czl?7eI07`p~_+T*3=4 zV>-&)2IsV$2nmd;D?lHxodDn6U(R|xp)zMwH%7J`KrtW|o9D9!#JT6bSH(j=kr%x0J)TO8W&MfMT6M2BN_7j20Kbv~~!%dcn z2-T0IVlwU;h65`WXe08o`Z&d9oWWv{sc?Vd>F( zdQ+=1Hx{O(0M+03-R-R+&mg2l-MOV)jmYKXr9hX89^H`2M$};k)p!vdXJp}t5aN!xsnF){j>Ye(drN- z#cF4@S)X-$o#)#bEXbR*YD4^ytW8&7ha0(xonrUoe1jc_>S)uSJ2c#C@?v&25s>2) zbfB8mwS&Id+zge63*^~2^Pr@y0Fnj)hxBt-#-R{M&S_vALm6XgXaL$!g*>Q4*%f>V z{!338l3{nd zv0jl-g^gza{{7nyL6-R!c=K^JGtwVRNRkjqkILX@3S*2gF_J4Fbpz>fgN8399ww*^Qp0cP`P74i_-PtL26g$L0ya5Ou*{fEZ z?Rj>k?T?_0^*>84@)dq<_gpsQY5c}^hKk&GJDK&~w%Q%yEZLCP%G2HC!ATA8_P zn!0ihH0=6%5*2G~=A;-+OQ|H~y$h#?_ik;}lIO0EZj3aY^snc1YCKYPO#A-XS{%uih_zsg8*BY%_(nu>=G!ST1cED7;{V(jG3u4)`)}#J z=5cZ>52J+SuY(}~y?vYn?=Pn3#Kal;3V2C`f+$R!f4)8YdW>?WY2QpV2&T5}(d<#k zr@JPWt>`)Sd}XCGYR1alf+-Nwh9L(ZxkKHBRdCBs|BEWF=tdKmYefTe?Xc%l7=Pyh z+RKDV4Vs@$RIB|S`W=$fux>jQ(RncY!=Gd}m}j!QZ$%*gcp-%iv@dcMY=sG+jOLT) zPV2ns`8Zm8=+F#HeHTm#M-JI_JkTs8Ptz#q&y2D!6Bdicvi{ysoWCc$N7NcK`Iv(Y zpr+C15vnnA86>ows+1uKAsH}!Zh4HMZ2gATeikr{q1vWuEm_7odBg4X-eM{_y*1Vx zv{AoBH;hj}!QC-CpP$)&sJi$SN8ek123=zVUIZI5KkY&Wpz2RsU-#>17R2BU>0|Og z{Ao0oetK5|FR`zJH1I@Z~Na_nyAL?qc~v z+Cn4}IfFR7LLFOIS7Lzt6Y!$P2AUQ&K7I%tBsEcq;uZ{vhP@f7k#-oj`=a6ntW*sB z>C4<<_B%x1vURD44lk02lt3D^7-bNgaS)wJcpQVr6pEnFNzi$+)RM}XYNbIm2yVR} zK|JCBye!y%yCwcfG5NwR4<7?-$HQb<~^A^hzE6YfQ7*uRN_{vD3^M>-^SlN8Y z6po#r`cy+p{~v4NZlw8$wS_EOO|Nt|*v@(5X+@WCpDRCJB*U?o$Xd%1>ikaWPbpHS zTR7wSS*fvg)Q3!Jn&S7ox>9AgRC@?#!6vJxCy%}*xz2r#&?t_lR2u(a+$&{!m9)~- z96i6x<0#fFQ@#SmR#KnKQgsH!-2hkPuCXV*tXS4cSy(&iF6$!llsMU(r;K{8l;18- zY?ASm5OvNAku|&Nt=X{Gt|d1Z)K5*18xS!wKi_o*gm-#@hhqK5+T*V`WM@z+WGn7S zsN9$e-kE*-?fb73J-1xlu3r3)a?sf;+k+Ea;YM|jY}iAXK+!)l>X>*9XP?wCSffsE z|MF+VY1+xr|B;0Eg;@YD$x~3!vjqenECUYgco}h@0cUv5hy`ApN%E0C!cx{$Q9vrX z7N>GurQ?H@-Ds`^5r|@^B_C3r%5$PQnop^9>hSybsrxm6%s@L|j=P}rP(Rw4;X<1}f)9T_PBm6k z0V#cZ%jhFb>8tExQ0=rmdn-EN(1#~t8hwOYMX}y@Aq5lE;K;@;U#W-#*c9-!=eK?P zmfHr22YU){Z03Btd+`#IwkRTJU40(M=HAs#v=Diikh`5-EWYj5vk!Kt;q%YdOe}pn z(y}#seDaej_V}oadntTog)+{)l|#|ahDM%E%YuX4;*_t3OqSH1EoQPHhC6qG;4wUuqnL)7i zM3!SKDE^?>I0D=B&Cu8zf=$H#BbaoVm+pB*EK9=21GqT)-oy$hyp;hN^PGQ6rku@c zw=h+xK`9pkT3c@3zyRLxwp#_ozmbXL^8Zw?&-{l=DDjF38AU8nEh$FY$mQ)6i^-Wn zS8A2I>qz_cY5Fh^ZaxR|0J>MD|8RhPIZ;gQ$cDg*T{0Y8r;zS3P&oW=0(QxdDWIxS zF`xX0OjlE-J%&9?1Pi~AmUd;B^(s>?Y$e3lQBlC45Sc7{J*nVreGQ`M)!Ow3KKd2e z1;HJvu*G>geEaAA+WMo#i+VZd(Qc)lWJV99*_+wAj7XROpq8`Va;d&Ea)XY!TrZ_v zQspxEAZzLdEBOM zS|Pe+1*~hVx{&$NcB14Y5Ulr&yYAq(5f_+(@+Fin@abv>ReSf&b%uaoL_|xye2Wr- zC?+XWK&BqdbNFC`t}{=#`POU?7i6{#RY|z{l^WMIdel1sI%qyd7jtb{;@YFrv~T%`N{rrlU;=@ZEOcjPEHtJx7sR&BdnH^uU0x;=MyyW9O<~8$v`ic&>XUGxc*hi?R8^&G4@08 zV(1|1Li<$g?a2FM{E-Tqx48`?KVBamevL>=vvGbUCHlcfz*@Y6OS@0)j6suJ)20+a zEuf#c=tIQ}opL;O*%$K6v6ulnPA*jFa`dK_qRjOd^3#=3G^B9^otebB!A}lB8V~qd ziQ0Yf++Kw@*AAy7p#nw`$M%PzNXixmo5y|p^!_=S5$hGSFeTS^-hY|oUP#p5Z(yC5 zACc>{-_O1}r`FbtiRg`FD;;f>PbSyRMc~NI2xE^COiH1~4sO)$V+!Qj#JNh&n&%i` zKVH@6seQ`=&tHV~g|&gsy^Zf_*~s%pVW1g(uZ4S?hC}L@C->Gr!#F{P7$UXZzNp5A z4-JiM_KX9hx0S_BR{nd*I#~&^`4?ql-+S}~LhGoH|ubklYj((`r$w(rx*hZG9`($lWdEzhARKA^CSc^$I~0$Bx6 zYwgeEGzJCbYJ$Nxy&{nfM$PKm)RFk#U3nB7?{DezY_%Z5E&ChL2L~{;b=i2-X|Cj!j-p}3xMO}?LWW9Ir zT05?;%je9JrkvfYW|O1RMauGwoGRd&mXe%^nC7KGS);&Nxyt^jaDeV&@ocQr=Ejy$ z>||-?QBEV@wDH*yBuDpnXt^s(baynsGaOA|xU*$3rDz7aX6PQcOw4>VkjFXWraf#b zC*Yc$d8~d@_5Rk`D;g;Nv$X88PuGlc2y*LOYbU)}jJW7Ui`#Zf)C$-x$1^!Mr#muj$|%MEGhtKAM?8F z*RR@UA|qpdUeXvft}><)e;%|J>g*CKO@9z0H0$q}#|Agnqnby4Au&!(1$Fa_mO{^7 z*}c`dxqalswKXd48o+^QE|3XMS>xV8hv^?8C-U$ndTUinXUoNjt7VLIwMo3V5Y;5V z38VtE)(9XngQ{Vv@h^J&&A%7ro9D(izPyD_VEP$v2g>_)Rd_%12tG!ov5 z8u2yA$^FYzf#rH_a1(Gvor=cBt65G)E01Ea7nXIi9aU?@J&`+i=#YiQUb(&0MVGxj zHv7>ax#!~~^0UX9(LZkcFtVz5H=5l=Wc~`CJ-e7+Apa9QonK~Cbj{%P*DQ8{L9RS) zAvGm$^=~vK+s(J0`XN4F+dy36a{w&hY58nT*#Vk0cmKLSgACywzA`oBlnqdbVof}$ z>ene5hlk5J+j7d2z#qUNpMJ@DTr5PBHsEh0>y-){_lSRFcU$QtZBku4>Cz8_QpQ!H zWDJWE^d+G^?+&6 zHb2UEwSebEBQfUiDznhOS4WE1HObZWfdQI87IHegDN!b1<&{17UMtOuiHwAqRLFgN zYCg^8>^}z4d2OD%zH|}cjy(0&KkbxE9XV51A%B`DeRmg2}ku! zrwjf1ZR=(^EGLE@b!8$q(`qCRotJSDaZj*%C-G@HM=p>S0r*I9gHd`GReEbNeNzuCq6y zwZgwA{-OWHeG?W|Z32T|n3=#{4$Vx8U(VhyAHLkh*-r(1o4x4^DtbP7tZR^Z?l~!> ze(AgUtrl2utWXyb^pC!a>#(;QHoALNg6?w9BlTQpe;owx^Lz;k-1el7^W{3u3wn$@ zfl>#odqQyQT{lD4nIt^Va35_XUG!vqO^kGPj!6ROM0wc2Pg;i9GY_9r~e=?1!cWLqHcsfol25; zZH=h z?Rca&etYyNlbO#|a)l9&Y@$I{Bg6^b-r&Ud9u4Ja>3S|r9; z$rIx4sCbV)-aNM?gIvNuy9P-VEEu0F-34F36h5E(;FPojbbJP4%jhL3B-W7Kk7x%< zDXX(A>~S_sLITA^--;kYV`d1cfO~+A(jH2QG|dPt0{PVA6Udz2GR|~@>=f}wJZR*l znJi9mf=nLn?fdz^W0QcQ1Q2!H5+fT(9B~Lp^oAheGSJE^`aag(aP4eqRx6DTlu2}( zy_gsUA8S)8Tl}wtn>lT7cbrtIXY|i5WlA$mTkS_JSJxTWZ_fe65i>-yq|b#X!ph%< zYq4gQbK;K?rYmQPMzwaUXAK}wkiCE5H5I)E7jMVf{9!_-Kon)oEr~7AoCm&j*&^?g z4dB#s(kf?}V$-mRsvb;@FktEy-SoZd2x^#0iJ35a>sSCD&0W!)__E^kWt`WQOcdY4 zLL`Cm66v0Q%92hJ4dCcCrr&IZh_>ipsXhPE6zlZz8q1*g0m}wiIkl`V@PV5UkC2Qr@zsH zBtn0z_L?zFRrTJga?~jYY40I=iT4dNHO85+%=|D5DX?xKfZ}C?lq_+NnJWY1O8<8u zD{-McQAX~MTa4?0vR>Op_Ph^U`hjKVi`GX0^}k8@>Tw(0hA@UIbRE1jVQmJZo%y-G zMKChAq0gum`IJY2#|wAR-WAuuyVPW7sMDw*@mYLVLo3{3zPfXLRPzzDG+Ykrr0N{4 zf!Jf%@MpLjy}gBnvXWuQiUj+yz<<2gC%FfCp{Y@Pf=!;CzyfWnihA5KEy1rdq$=qQ z$Ck>u3?4_!-cwM9y{EJ02N4wWnHVZ5oYf0u)4yH=%G{s9K zUGQ+t6=!!RC8=RJ@R;}RmLwEmeo2>-R$oqHynQJ%c`Mue#SwizYdkpCs8*OMtii;< zHQtO{l4mCJ@))Ae;AXQ_!Bt_&yico`^RK!kM@CI^!{c!)M16=QHU8eGU^PkTQmFhfu*+nb5CW%M)44??UaPZ(5CyZw-eI} z?z&ErN!|Y+Szj5}X3%YmLve})r=>tCmf)_17PsOWf)pvm-L*iF;>C))1&X@`cXxL$ zRp15o?9SGjfKO7|*# z{Qb5?4pTv3olX2_evi*fo*SCM&Wx|ZnPx1AZ6f`*T2;l(qG#f9A}*>_E_I65=K2Z0tOMVC7v-$fuH=RJx|9 z`w$b-%j7RctF^b7)*$Xw`y?*X|FLC9ukmSPfQNN~dW zg73otiUbhqQ4G}n=O;ylH=QY^i6+o>1)|~G)x9x~ujqTWYMyvmBF391$rPU(EoM7j zPEQ`|eH$$f*}+0*#UdnpJsV3LZ+xU{Jpa)@w0?dl;ywD746cqqOHsWNuFm@}CP>|k z{!lDlXSxj)PJ999QrjhZj3`BfwI?aBQ-xhBR{M%}pVw2|=Jz4ERCr+1&=?tqOn=*Q2I2f4q9p8C_35Y3@~CT+Xq(#UU)Zu>ITF z6V5>mq*cWcz(AjCWa`|Tmy-19{+kC42(QP!P0omc&(3Bm=nW(9flGIfn5pTP6og0$ z4c44A1K~vM7CYn63P6MbOuwyU;;N9-=8D%8*~GRXpIzEz0LAr)z%lNk^AwTx!$WXY zaArWem)yb=L0MVb&s5Y%V(8Kr!lOz|U0^&^Un$pY=DDjn+ScD{D2uWOn`KB+N&h!1 zJM1asFnZ%k-VPn1k1ZQNioVNZgPou^LN?1#s&` zKsQ5m9I$PGEQ{8-BBHk`Ve?l=6phxY(l=)ZUrs+d!c$v;vh;{u<1VjJ%&nhbgpQ-; zTq;R{8f-l_shDn0xsqZ&{N161Fz}N0HMH#Y&Zef90m?Km3-p;$?4|_&OdkuGuuprZ z=Zi-z%GrZF`fId)a|7MlhB1S|X9hxK6e8?3Vq&R6Nwl1+wpOW+uT`bknON2%x{`=e z2|rsczIxeQGE*AjZXB>}Ey7fy{*I^snD|kmSEhmtk?GC1sN5^J$29iES70Y*nBrt+Sz4t(snc=t_VjwGbV7^V)eQoeLVDo6k<&!;W!U0 z<^##@0dK9u;N>A!=2yOlI9KE^#scKIl41#?4@^=Nm3`R7Pa&!w z>PoZDQ1AQR1k8`VE}?U3@1y2Q-0d2A)G1CfpX z3zW6b;!xqBT)icPvMW|jOyXBZE{OG>{pm!m1;$ zuB3oSUQ+k8bxglO=z>9x2p zflwfjCni_w*zXu_$5SeVSI-xv8dh4eaHX42jcXC-zz}<9<0IMHkC23z(jg@A?G@J{ z*yacfqPd80we(=XoNMz_>V8epyM~Xyajlw6dR5<^mE+6%r5IsQmdFeSw0XQd#{qQDu87oos+ z+0G?&&+r0HsZR7dFaT6nRvpb0$Q4Yqy9-nWkLO@*>?&YJ6RGz6mzaE?nor#Ed7n_Lj!Un6N;5BLVN?K)=P zkX`vgvv}oZKHxU>-wmEUeEwjxhAI4enHVzAHRjS@&rZ%X?i~-(^*Jjme91zoc* zI4gJg!`U-KVTS=0qYovl1GEQ6(erWUBV4FHlxr8{fxrT3Lm|Sga@MlRI5e=U83IJ}mK8z`fNHhTPKUudMyO?mQ|1pf07a|aguq_yg?^f!! zCn~^^6M#OHw$p3^4-gh50QD2qWOVj_WE1-2#RY+5v*!W zv_aTFO`-8N|EOwok3AF?PJKOp5J_4l?9tDBA}02xs5y14ZD@Kr9ZWQKwt6^IWWQoe1K;x&Eq zUni7ZXy*2@YszPg{i90^10XGa`JpV4LDmjIy9t^`u+E0i&tCL=C?ddj5mkPzecXy_ z7}G{G_l#xrxLOgmwmg?F0A{jFnIM`n7A$TsT_!@<0t8K0S)#A(0F?xnd*2*@R9OGQ z((EP^izB=wZVPH=TV-AUOf%_;@-_F`{Q02a`4}iQ7sy;rLY6nYC3JY0@p3MbEkO=0 zm_V@tf*|CSR#wL!ELs*FLy`X-=}v<$R)vyfv(H^`zQ}!H?k}#MqEFJ(PT>t-(Uk&9 zo50n571_+gBV=xWx*YWhaajvAGo~Rg2&0)L)S1!T)g+X%T?2P#5w@`61aF*&AO(c{ zpUd&?k>qBIG&!K64!0?q%~o4~QAsy0$U=Ai%qySq2W{u{_a}i|X2*2cD6Lx*1yoH# z-4>qOIejoNeR{d~OP_#)xMUqS+9np04(G7vfz0}|o2C0s7ox@w_n#I~m!>J0ZkhIp z`Nz=RP)2CuP47P*{N~VqWgE<FllkovsUc;1tWH!U$!G>t0LznXBnjO?bTlukO~p7k3($KkHffu#@Z z0r#B~Y}jSVl-DX6AsG*enbwN){CL858f!eZYJome%O%s#R?}4Fa+);{CLY{3AG<65 zrlu}qRuQC@h&AKA#hRLH3NfTJ*Qb-8B5(23J!?XA@qC0MFcn+`v;dzz%{4Qa&1^Q2y(>FdwbH(u zF>Jm%?C8s8sm$@IPjnp8ze!=K#GWg*UD8mU8U3WQ(pcC~M>SS@+Um|R(by2?dB5Q? zO!~p+c{)kV3w5>5y(%#}%YvZXhG|w~Jf`TPPI>2#;MPy!S>=x;zI?2yqL{_?*~$Wj zluAF~p7dO5l^=I5Ili?~MZa~lStCBYMfY(Vcl#*Cdt*-`BT8!}&&QNb^nPE|1D8(Y z@5g7u5Ye}y5mni|tC>Ys-Ma5T2`+7*DK{tQX<&-MS=Q2>ZQSwZgb%ilrrZZp2I~@@ z6My;0SaZt%)IU2K^sPD5=oY(N{ozezD}4A&wHkEW`sb9h6*IjTqx~pq@`>yXMB|(! z!@iC*)dAhIJ)6Rwq}EH_8Syw$k|9kZWB|6MCEb3=V|los`A;!FlaHgwD6qq%Hc8SbirKOA-pA17J#+V%a%d&=Yj8R$ zM>5Xg;h}9Y!aj-#ftRu~2r3B@EGZiB0bRN7@*e&1E-;VPzul>}gbmTc0|hw`j`&h` zcB;9Iep3Tx_xz_0(3)RnfVNtazGFdn@Lr;Vgb^RScoQr2gu*6dj2*vM5jdcsW_;o= z9nSJ9hV)Qu+*A4@*Lu0V(aXjJ;oPQc<+URJ<p+6(|ILDXvICILek$%+bMWpZ8L24>x6)QJjOO;F)IC~@*qpg7v3VM7( z)ue<@G?QfBy0x!GStd6f8?UC}JP<3_^o=OF;0{kZ{oWXG+qF1+opGYmV+o5n{=nPu%+FVgJYd@x9nDcxVud9T+HhKCNIJ}yZ`zZYNvmZx zzdVVJ28oQ(l7uLHRo&7(@pG_3PZu^WFRsZI{^O8#-kP|L(y-iFNo6*C`zEQIxzsVc zN!hRE-eKxOAivwqNC-KaoU7wPolF2u8#1?-0iVA{uQj&Q7EfpY8pNIdB{pRa_s;yw zxFnKob>)?}Lg^js+--Gu-T?DwrCZmB(vtO+eMfhQ8byo1Et?2;E{Xn6@=jDb@(xkD z?XIF13+ILW-0QcMdEJ$n3L!s5L;lhe-7we!EiNx9_npA^_a+4_K?`H_ZDCTL#+}EJ z27E?+8PuYv}^u%3E;puPTzAAWAM_V+dA;!{WF0-vRwFpkeJ z@k2V$yHrtJcthC@|9BXznT5PbpDX*(n|6AJUs~U$u%OzBaa=VC=?m$HtoAY5lbq|`Ei zG<-diH9TTi61{vESyL)L8dHrQ1*V|~`4)xK( ziH;$J!>I#VY@A-*?0ftfW$*$(zbBor&C-yUJ_&zc!eW_0`Y?7Q+FVNA*=ked<9bR-ZmBzhzxw_plMGlZl}o}sre} z$rcz_t<|u(>a(6=fF7+~z0s)>mynRxWav0t(O|?KVxC|oiV2iNTYDE1_Vdhv0>kFmufffQT8za1lGTqOmHFOzd)V$ZX-~i zYs0Nk*MBnd8K@}0bzW|k2S5F!wp}B6;%;%lotg=lC0;g)Dz@GAp z=CGJfy$9zftr^TGhVzBrJa7Bf{@^V{6nuRbC#g$QQl%;J*Sv zeKm!hpn9CP%Vg>G24;L}Is+44Qw=T4+_XKMmapF7*AOg7w6KF8N{7yBqZT7$xN^#p zS=sMHd<;`GV`r~yY?_*>>~4VhFE0mSL-*yyW|8s5jnD!Ke_JDuy;751`rpC4B9Yl-lieLM#7w$sg^m09TW;`p=@vib&UEUpv2R9BnMjFxEx0 z3g2|mAt!ZbcaZ%ZN*ASS8BTmrLo*1$H*Z3=O;=dFV*(F9gRq$@9Caz?utYIA3>uJJ z&CwxfW<-evw%rG@-X>*Jd1EOTS?6DsyDyKDl|pU~^VxXi=v_^Ya0`6W3cFA7G+w!$ zkXL!^6jp%``l>u9-sp&(q3Uow_~`I#iOw+AJkO2vI>PrA{EVD&*^JtV_|CqC-A(9& z4+F0YVhOQ6iW#M&$$aLqSJF+!p|M_!lNyx7WgeZG`;Lx;j{)JJo)03&DtcG0IvJ5* z#P}_*sb1`jcpxl^uX2jy^Uu2@JG4r%U{G8k_6on_5Q2=s8r=<>eF@L}h|;%rjcwAZ zF=(fYJ=x`fiwz$ntdO5L8T?#FU73!gh*Z5|74=FO(%LX)xc}MJndM+$*Ofmo1t*$T z6#J~@5X<-{kd(A{nYAfO{VUzt&M!1BVIamb1r;Hb z=<|W(FpeHCA-}BiYRj$5=#P<0xu6b{q~xK+=a$7MgQ1-~R{n%N30+-^`I++om|ZXo zCy-m~^vB$13JS`U4>An7eg!%gK@%g(MoY-|s~= zpD5B%&fcFDj4+Tc(`A@pLk^27>6 zrAyg51{ZreUsJgxY^|-E6Pl{nT0CD)#cn<~!3s(%sa}z4I?`$+7JdqY8gR*Lq_*(; z?cwFKc-b2ZJGAfx!z{|A5q!k;tUiUnm*obcqaM%fvVyQqorw_Tc~1eAe{Z0G$pp=j zR#p3L26u=y-lrYgKqB{RX<9MuokBIXAdr4v2~C`stR)+I2267wx}f*ryq3!n5@k%i zA0OwrhkF8K{32JZSYtl(1x^2==gmwd@bRtS5fCV$qAL-Mqb>}j5;=J}$9xF59osa!OD9>cYAqsq{(afO?^)wJA*m2^!>S!syK$iG zLH{%_XP06bF{_BYs>R8-i|HLzgnvZso+JR_eJCZ~QnfJQy-0u8&+hMcm+S|2$kX>M z6W)6RMZc!N-MxI5oR~!yzSpr(W7$~&1g-cZx_Wgy4gpHdLuQ!d!wJ`e_0V9ueMTgasA#PZ`VO-zn|e6p~y{TsJXzx z9nR!O?3ZH`{E_z6I14zbU!4 z*uy}jw;g?UA1ur0B+J?h-)l@XGNHkIi>yxirW14CsXK}D>)j>6Q;$yi>OJgaykz~^}QQ1=1Q5b`$Cmo zdKx-8Nc;BPSs+R}Ls7<_WvP-o!evTAgeQIzyILqW% zKv$Pk6)P)(J&FVZoECyWD3p?qk=owTr+&N-(x3Z%3F^wzkS(KgrM3QGbj{ZwS<;3) zYurk$!PLe*)-gUWUf>i(-Kl*1`zY_eeRI~m9m8}4=SM7F6fh~>8~ORF5Kz{wCQ(*Y zgoQI_hzqaiHm1!ixH5S+Xe)w&5qfLx-NKMfP3;C|MMp#FI}y%?!EnGPm^LEvA-k{( z@{S;@Vu`JDL?P-oWXj}$Oo1SIeLcA#P$XjAzEpPIPDU0_Dcj;@msI@<=uG*MiUoHh zf}^zfdA8OQ9xX;6n;r^BR`soYjlpRm?4Q5f!7}56R}(vxI_wKPKQlUy_w!0yLXlHP z=5I|0?cK0Z7AVlF@v)EvM5CM36LA|eGu>tMZdE*N44lfPij2?@L4kY}U^d+l z5LI7dWBg-`p^TL#w=53&+g0X<>PDrum4CNNsvq58Lw^HqvJ*WsGv=|iK-av1b8pIU zI>?dn`18co?JLYFrlmP0%(qWi^r#wfg?$oh;lf#$=XBZTx7VuecX~y7*V6qNcQL@b zM!F7GPLb%7*XM&RNK3#j9RmZ5dNR?$9y zDgmvcbjY~+BI`QZ%fE=~=mZNz_}`IvHW?z{W_;aSiQ(&BI{P|)wQ=R+UqEF$fI9!) z#cV(6yKo(TEhQ)K7SQ6F_D{nXO*t&N{PDHW(SVXJb>|vF_&cJOkEBWwgH#XMk|CgW zP+uL{2{XRr5;(o&#f-ku?t|DxgNu2gq%g{lgQHLg<=b7Y2kA4vbhzwvAzzP*j}LMS1h>RbSd*u>Vpnd)xB0~bDN(6DjMXoc3hs@ z{zkxwFW;=Ul)2d6*r#kJ+#`E9CI45ml3w(4pso=I)$*P!TmjBHIT`?k;tmHcOflj? zM3k&t{dZMR_T!~0P9%sGEK@Haq-?$KCBaKrk~?~${P+!9uc zJrgRh?LxJV`@_jrm8A;E>7VR`XxXGwM?-_(;G!=Ix1(rbKS)El<^i%MI*b(6xk$$k ztREhIPGjf3xHLqlLGrV}WrCRZnxrIx6wn{V_}S2Okl(|KW-KZ@LI6n1O-L+Jx@Qae zwdrUWBDk-mE3I4vigsy{!RkGU>h4~VIvc~@M zUN~Pf4E(vcXkySWJ>q~&;8!V^G91E>W69IgpVl`;Uav+}5^w^9*Mxu0L=|&6!I!6P zUgsoO#=VVt#Cx>rsXZUE@k9H2_f)#E zr0s+Ae2}(=xSIODns93-^VKq3 zwAu8`wfUUTnI0_}TJ>=>6gVIRI1yE15S+`+10>Lr(Epo%veOdYb_Ud8&@g5 zpHNTET%CK2^kbv#Fh*Izt%Tb|@>v!x-C4!xK8tJ}o%#NH5e@M~5P8ZQGN#Ud0f&Sr z3&>~)Of7E{DHa?m0lB?)mfl*R8P_R!%U_A25og!n|4zfDtrIWL`jcw~N^($f+pN|; z8~ZQnDdpjjo3PctM>QH*IT)4zK(Nm!M_J!NjHeVO>+~(*ux}U+!ciJ#l1zi;O)-aO zvGmLCU*L~<%gwpPvL!gZholtrS$mnH^ovtIGrd1ed)8r#jchRKIS#@fUC@ytywxn; z4AOcGJU;3TZ{!3`#2ohes+=hBpTvZa*7Xo0{0aXsi6_tCB1=9JVPMj0f*>ZzFgIMTh;wg$L>w zad;j0Bo9G6J!qyH8U)tm#eU!x#;Je+3S!@JM=5Pp{QY`+du=HUN9NHxc=B_4u)mef zlAW|>UKR`Rn=2?AmEA2Yd=PX!rb%0=puy9HH^jS2MY?XHPSfLmjj4cN>vBT_Byp8w*v(Xew=FHIy3kez>^XI~)=>l0$4?{anpc;L{FKFYMe zDpy%R(qQ5Y^pRQF9h%AS2xW0sUWa9fc!<8ycrt6fU%odp*-7Yqs3JNy)A>~iXj<^0 zu56(CnTZ-teiF3#&iw9r;78ThXotpk9~Xe=Oj9~Mr=OOi7aDA9epT{BtM^zvPSqtB zo(2tgm54TyiT!+Jq<(wSoUX!qw`z{Y@dNAAr%w_tF1*t-GaI%nQFSu4a=g5}s+yX; z7H&i`odd(e!MZgT8*IR@-A9$}9Hf$d2J& ze)Lu%t3wJp^)AV?U-4oTl#9M7C|wk!W_+MfEU)pW_7_4=5r9g9g5II09?r~RAj97m zaYx&r!UagU?B8JVoSS#9Qv9JcrLXN)R^8^}Lg7N`euc7usD2BxnkwiF!6DCTZ}$@j z-l$&uAjE{WX6$oKN-gR+jRP^S_|bs=L5}nsNv7V<_qPEE+cVdK59I05`EK zWk48rFRA1~IuL0$!RqLchEIq)(4mRL4ZxsnTTQC^ot19^ds=>iG|l#fb)9(j@X1T+ zYE$&_mOkyXj}FNZt!-jtric|IOa~!%d|sAGgMdketcM+HP$6CSvbRt{Q)5~rt8WWp z4BLT-X}|tAZAZhw!NIKhdh$j4CV}GqNJ$kH0)&jaX6@}MG@}8D`#oaD+1yD+JGv=a zcsLD+(;5Q9x@$0;1;PzLr98Qt5xV)DKUgh(v_WHogw2|>o1FI}bj=OJY_+#T&Ctxy zLf`!R8u=g(5!%na2Wxq+`7yR*)v$Fl(taxJ=MJloGs7~br3Zk@s6y^$u zL`qkqP*`6GlI?r7|Ri9f!9hhl|%2A{QaM!ijN21LBvK5g6 z+LrOZ{5Qur+*0Gn%+m76e;6Mc?lXkV_v)LVSP%pcZ#?U8-V)2=)-Di*>S<*D-kADQ z$eAZJ>N@Zs!?lr}wM)mRnH3dmi?1!8Z)s=tkF}A^ z+MeYTf0Y;yWF`F%{(PPs;=6YC-kyr>ZD5L07tZ=U#PQUWkRCvANdO!n+0|5#8+^cV zY&k)GoWuc`q?PwmQd-MN%)4N0_)@SF~z2{qOy)Prp+ctsw#>s z$7N~D0_1OvG1ZQUU&ZC{>6|G=b6*i*X(Nk|%qVui6V6!#P9p+Do^=|O{!Amg^=@xC zzBu=o79}LUY~+u+^FYxT=iH@rp26aH+Z#T#{iYp&ED)u%M`M2?_FJTJ$IXACl&MR+_tB_|KMC;%R&X=Zj|PdU8koblaBdMoI^G zDQnU9sQc4jJwM9xb+{ad=_h^xS_kJvX?Kr2$kSi_^rD7zYn~TiabL@wuYLmiF}0(I z@7B=Wwb9hs0g!qem(_K|`?A;m(vLmZv#k>RF*baunBquWMxzLz%KMXa`d3h3b|D1T zDKIviLtWv}?eKml<@q%s2jJ-NFmQ5GyGy?S@y$AAEw%D%o`i() zt+#(n_@mTNn3Gu`gsKTiOx?fL@KZikGIEA3Lkv`OM>kTinh$E@hfES6By1`- zr}5SJ@+;a7YoV7u@~nS1$=gjNZi46@{RPwDx6*wdgJ7<17V;sMV&o&eGzjK52&i=; z2?)wJ*oW?%qxkam<$-r+4FP7h~L`SI193 zzAQD5C>)55h9oW)X?~TfxHOl}djmOJvodAj_>#8Fduc~dnMiaaXFmgtPGiRejyJr6 z_KsdRMTTCb-90bm;WA|mzOXJDJhG5MCkYE?^t?=kY{hTm+xcV z7cI(-oxKN4amJH~zC^ZVrjl+kep69TEU97``gN?iOhD|5w6_6PNJvQ4r6{AO;P;d6 z9Y!Hp1gfpbGAfx~Hc|`jOlf}IOqNs}0bknR<#6M0f=>^$K_DT5Ou58_<-rISXCfJK zKw5(-PoOhA@TrcnBY53+Dw*ja`vFGg_fgXy4D_$itT|LuTeNu>M&(%{=>q?}`tcM} zy!5KiWw~n*Pbg&7Jg?Rm4q$l$YLxlL|GJmdl<*bR6;>g`G(er24b!Jch zo9O6v2U37jZ1V>Pt~`vVv&z5a4@<`STd7?sD4Irl-=jBXR#W*g*wDIjxCd^hjHw@E zhWzCO=#GUU&to+bd#FqJL3TpzcMmzY#Osf>Zl?YDuMszWASgAaIx9;;c6|VXm0l%r9FD86|7hgEA8uTP!X9a zqmJLgY9{m3ayS>R`1)>63_9VflVRz)ne`YHkp9USQ>TCh^LFTHGm4A@kSoY?N#x7} zo_K;)+D%;=wyL)IFcrUP z&W=Q8_-9$xW%@QgdY^4=Dad-<_JWX2Yo7>jbeI1soQu&g;K7BK7v|?PDVJGGoP9_U z@2r!OK?hH*cY&mDf?*;P6p_sH>VI{>VyGO({Uy*3m?P`yEFBi7Dd?!$TuR}^iKv%s z%xHb&;LM%i^-q=-yb}#G$$4_E@v7auCjL*r$WyYFJ-=ta;e=Xys>4K|dscj_rGSVb znOiBPM3|}Hk?3z@=A96coxqTF4qRZR3^#n79R7G(xwghx`m{qX`X?MU%H{>+YnQ{R zD<$=af9y6nybO-V3B8Nq#N?~_RTK=13{wee-a#BzCnxUh-CfEAR6)U*f?M%a2@+w3~)(GIVlU^Lq8=*s0iMZ#Yjoi$Q zGAuQXXv*FYC0GIB0Se7%>W!Z2pmq|#Ws`+j^a0%#x2*@PUwk@d!JGhs+8{r9Hk0g& zkM(dtn*E-w$ny57{tMQht*9l7k8t(i)lv@9@fs&yno1ju+3N-4pSKo;Sw$TpEHQe2~Y_vwg z!Q?>gh5&o<>zdQT-@74=TSiYu&O9C#7k584(ey@huR>8k5;Nf?Nx0bS3y zjn<&WNoP#pm69AVln_H91<^&1VTj_$L32k)w3Mhv>(#gNoCh85q)Mf*ywVrkfr;6* zGR`7cOsT2xUquYvG3n0mW52Ut-^9GXrJPS^0VwjTf$pG_Fio)DQqKfI>?3j17$aJ z-lcFHdg#NEr9t-jninXjKGv|b{0@lJ>5RTo^`_d~vJXI>e%&TevZg% z?bo95*7xjl0F=f0p*X4!Aqm@9 zntOgl24*8ihAz5;)X2mCjvj=4`;k_i+h>?)90t@n(j5u`Y5_@zLli989*y5S;`~>D zk?e%lg$(I~b@<+29k3}KI1A;!24YOlLJlVLt1QQ8@!-|zRf?Ywz`L@!Bnx>q!uo)g z5`eRdvsvv54}6hepd~BuUn5dNzyyjR?s@gr$?z>66R8IxI+v#3y>S18I8tDiSw|A1 zqHiTZq(tbD4AIlWE{rjZ0#6w%NXR5b{F=r81U%iMh+6`-L7O~e^*50xpOwyLOS?!f z+^MM&$_6-+0hHd_lFUr*a8P0+CSewf=>9MfH#GR)ZGu(*{T6n1c6wfK(+-oeZp{u( ztvnnuBDfYJOucTfj-V1ri?B9~I5Y%(S)tDW-H9^&ci;v*W*}4s=+|1421}DTzwipe z^g@G7Gom2d@@o6il!fyEoRX%!_~Nk!KYm%EJ%Gym)+TIja(vZ8>iXk2-_d2Kt3m3h zl$9JFa8QEkK6cGQ1wPF2@pp=&7VbN2dmy zojEFIL9}a_ncZU90RHQ(Q}}+9jwg^E)-0BWAC5|noIa11#2Zs^=DB1i9%J#5$Izvt3BYG!tFt0P|c>5hGrx7_a%Pj3668>;2grGiT0WeMfwF~ zD=9BPEx>@PX6{K)b1q8ZGOa7mg+>6m(Xf698?Kx#fNb$EQyGg-D^g^2d%9BPacPku z<*~M*7bXbFsCW(W@kYR*C6BrZnxX0K1!e1_9bkc?$2RwE{XJMiLMcNaz0q`c~22hed^)ZU8%fk>}}hsc~qkc#{-G6!(~Gb|Y`}C7T?RPNXSZ~YG)7C83U?BGOtzHClCBp%P`8+HD)u=* z)PzsdSD`3OBYtp47D~l03IW^_; zJ`3JC?5WP2AAvg-{k*ZQN|@ zXlxxZUb6r&G(a~K#px)1Op>c>DaWTbwopZm{f#43h=@~VB_6941qaGYwrKZ za?Dd(0kyo^C|qAdv;8G?^E2v2k;W4x8#3u+KX(eBg$* zRmD*yimN%2M$`DYK*2~ndLOGM1|7^ghj+BxXzWhX&~llI`E8d0fraWneE|x{7cvi; z{oqKnP!K2mcYV!#0o{FHb1q9o`*Fg|k`yYY23xd%9AUU*RCfwX!whI$1HP+FK{o|R zN0}F#R{2HK&Ea-NN=9RUpwh|YG605d+0nZjRL)j7SSq@V2tbQjlzzI6 zEQ12YdtELadOxEdK+&HX6IuJQ434pI8KDz(*x1+r=ma}5UKq@<*%djTLc3fqY>Z_z z=>mj_i%>OJq{NjN1mgc_6qY^0$AB_2F!O_N)YS4ibyh+w=AE(^a$kUtThu!$QIcgI>p4c(0RQRXX0O2DeR^n zOr=y?uzjm6MmAtP;P#nc~P5#T7CQeVy;tBP1=JL^@ zb$6EHZj*En>}FVi1C$l#xqWTk=2cuV)}dBLr;(h%3vnGKLF`qD9vPFj;Nz=9p>f@BB{U%lo)C%2*%w@NMW{NP8Hv(mc%Uv# zqp$tJJ}o&;I&uHt@?Hh&*MQcYFA;=;n~Po|@1PstnVH~&4B*%M?{o3JsEmwvKig_U zRF~sLPyZOa_i=b+LRew&wsi?aEOkeYV0j~5&22x9j>{H2n^f>+;Y-nd+Oa^Rvv(Jv`lmos1{ri{sWj40NrlO+Xg z39oj9{$T}jQIzi}5L5>^*6?K2DD?f-_{qx_u6Vn!*Gg9PvEn)4vLT;msYpvsVhbdg z2rEaI$?%Hm%%Pax%%NZx0ttzc0GTpikVkwp)50c?c?E>fg=} zsX4GoRjpE?uiI`qa;Ar`@Z@rn^_$mN-&^lO)hOd`Nr;zpR8IhvoViyPZ^+K;U79)G z>Pl#iWTJk@fJDuFAv9h&oIu>>AQB+iuv-u!Y!6TRzj(?2HSiOVtmxoKA_H{l|DB2t zUlKYO6RvGCDgMq%*qN8HRk?LUDg^Ydf6t#3%1u@boL${&Q(eHoY#jF%B0=o6BkK~Y zTk5IlL%~p>mf*kN1G+P3`ENjjXu)ZK3*ff7r&PpCA(c?81Udd|BS#gpS~|Zsd~B_- z<@sD7y$Q6?tonN6jn=K>p-DweR^yN0Pkc@bQnhYh1jF99m>=%DXyg4`3FL(T4Ydq# zE!hl|jCGB<6g6K$i4t^qy`KvG?wK*noT(6AZxBjn%6`NJA6Y^LPf1>0@QF6!E6@XV zM3T(2_h*Ue{xf~oIPg8O((6?6lcW`ThgMdoBWrw z5?2*R?Vpw(P1sThvYg?m^mpB75}!ViOhuLA5j$ZL4`(Hn2ld2=`9l-EtljB?h}R!7hi~U*-N`O? zjwT&oLVjPO=ni4~W5Ek!zIeO&VL}r2N7veCA)r4i=ht_-o#g_@NvC0lt&nrC^COeJ za{T{nG1dUUOhi6==cZ4s{~DX2T-aqKXIs@y1iB-#?#$Nj3o7AqJv++@oj#ba{|{Mj z8P!(Qb&cY##e!RLOK^8+af(wckOD=DYjH0Spe+`xP$an1LU9d6N?RO?7AaQTir&NX zyzjl=`0mJ$48|bI&dJ$p&o$RvbHR1maoo&|v8--y!|x66h``;U0sBk%|KurraGS*r z#xL2WoY*XVjibBGj+k0>u$jXY8dy6l;2XvFfs8e;x$r=J#Ag#n-1C^tmS@uKFm%{Q z`0l+NR%CULoE!2-AyZxv@M0~iKZwDL;NwkL*m^7kr z<0a2O{6r+E{P=Wa5=VgQojVmXGyCX`+LtzQ(rnu$joZLOaj!keQV`A8eV@ztq4-T? z{Req}t&lbuD}B0NGe9dRPun7?z;W-zGJBkrW01$aAjxQ8FZ<0nD?F7u<{Tg%h2Yzg zS~sk0++~L0cKQ+U9_D)u{J)pP!_SFijm-=$oa!zTBaFG-se1Y!p(N{Kglp_qT)U^C zOu(c_9*4IgR3?A?@q@~9`B*!QQ*S?E!_a?M?v+j{a02bklO7G4 zZ!)|M=P!5ap7-Ox%PZ-^9-nPzODOsXcc)BHa(^>qIFZu&wynw|KULj!ov3q&Q*s+T zuDam6Qmb=vS5Udz8PsH?lS075Nfl6)S4lQFFf@{GRMn~wD_Q~xHMJ4g6H>55f;Yn~ z8!w#(QT<2jwNASqF@32L4kW_lX4jAa#nw$9VZ$Ymv2eIP>W>f!ipm_p&`MxtYkWr{SZKNrWpS#9g63F}j27#n2#EchnH z^f=?GToJ!!PQ4CeIM`j-(Fq`6$7%<9Hw>bFAWZE@gBOU)R=u zSGJs~(QVwLV%w7j0sa-+{O7PZ-GO(UbT(F*GsQ=~M^7&DiX=a0-x*GCC_-@pX4}Qq zJ+nSV-W#I#ap`O)C4GiNs9ZPT|L9G8Rd4@P>MP- zZq5WLef9-wr~-AJfr^o1m?pF1uFtEjKeP$}Nwg|ep%8}2D6yf18m4Vru<1GyQ{-0Q zl1dvFOh1VE`F-pRo!kawSis@DCts!{^lqo1GdWNqbhPqNOyE--nXrg6fB(lRWFF0L zf9_v@cxOeV2~f^&QOOAy0kENxK6_b760HNCeDBYC&d#Z*l2^RfDngI?L-GVFT~kpP zz1a;l4RWvZq(T_FXB$W|KHSXr?F0me;R*{Xe6Ij=Bp&_fFy454ii%s}6Qs}u5gt48 zmkr?V1k738dqqHoFF($uZKlh}H9)JrFHTQxkExT5u>B0lW*Z`e;XTV1Gr>RlSwRt7 zN~LGZ`D1UTy=JtIKdxnK)(pV7XU{|h8R+0V3aWUP*-<4eJesd4?v+dzsPbT(u1lwb z+PKUZ@N&WU8g)%8lYgrwVWU`2{y1+QmN`8p!J1FWK^IkRc{Zq@n}?n}vQ!IzF6{tD zMQXj(LDPQ&7n#T=I#c`x3e&#K9D zbM0r(2Ut%}M!9sH7Pz_wb>flBq9q%ijmfna0joh0=3NTJhCXS9qQTL(y&w#N9>N~t z+WG|Lr;mD`M$l9INpz1(vc-UHbp{Tyf=&e2bn2-f92E$~`e3i4arVSl6%Y5Q%4^-YUK;^3xm=(0UJDyWwO>H6w>BZ521VB>zNy1;n z&pY#pp?__g(tnbWO%KRQMI;u6$f{bGuPv5KgTv_I8N;Z`HJB60({b?=m_;#F77~#t znD~z>VpG9^7wYkq!nXGyrF9Dl}X}jTJG+D=E-gwo>YQ0(LVa2JRw}LL6Zu zkm2qMo`-4`#J5gR9PR|M#yqheOq7Nz?vQHwx~1Np@B_00Rb&_&Ew2WXSxI`j5gEuA zEG3dAt>4SdydBUb=9}N}z&$TU2m_5)4m!#dJsL-$qow;J7NlE*nbgaUP0Nv~1B%Y! z4;75;UIzM7N#6x*B3uC3d=tp*xFm;yV>e8b^7gfLtUinaXULMge~^~MI?plqtVNap z?zuAVl{h?=n((ir8!;os?yY@qCWFPlI5cy@1k#k7zfE=0%mE{jq=8oH8JqY%F$EdD zryXoRh)`*sQU#!dg4O z_dD$g4~9hhjQ*h7U|cDyIe|e^Ni&Oe1n#-@foO~Jygbjg4F}^W;SFX|<)nMO+U0Z4 zR(%=&vnj*XlR%sDa_t@k!=6F2?t_aKT3G+?)s`!M8uA5YVKFSErm%??H#B)(?z`xv zm}K4X_Fsk0(6tr+u&I<}wcxo*I+h&ElI_~?e1jC(zoo4z^AdUbjwSqSIvU4Jc1yle z{p8yLgs0{g{%fs!6*?j43b_1TV0D$$A`YZ(Okto4NW}6@w;)J=XR*n>$U!OK5-ecHG3`C;GEV&E-t;rdJ{;a*A1h>VQ zEqI_Uzo=isrwkvIYmA1~R}9n^p`o_I4#AfWMF&gupn>I9`C1+l(6tWAF3^34B!7l# z{v<@$%_g8L^s`F{Z961}ox0lloG5J*lJdo!D1`9$H`vS1ddj?mqOsG1YQ#bo-9Gs~ zZSF_bw+s@#(37-JpLG-li5VFtFuaZeQ+-;Ny(bUuvinW_>HbM^MKWe)G*j51qqG;5 zcu~tKF^BTLu+D2|S^ALQ>jO0TCrXwx$Cj(*S|3{1V$Pp;q+f_s!yWI;7?#_t)*9~Q zmrKtTPKdH}i-zctDwc}pgHNL#7@YB zP4Q}QDnAD|_1UkNGUQ{oU+`dBpj5EBlV(+ndofV~(oHYA$1K0Cv3k(3ck(X}r!D*J z=Erada3Gv~1Dt!h=AE~YDh;zwmMl$LG!65ah&MZi?Cr5)HLwC+8@?j_?Ot0R9z5Mh zs%$wh5aO=sZ4S{X*Q2#w=pekG=74K}456b_#rEiJ5Q;Ym{6L?MS!P?B3a#%3^8;TE z;|8+XLXOOIa=_>pcog701r~>TIK5QSVhj195S|9;sM;9f+SP)lVo*iVMB3>8m)1qo zqh{48&?(2Vxurgb&8~~Vw%}syZ>UlOsKE~h;ndX9E-M+#`5?xCekDZ&dGPs_?VL#;XSf$=ciZ<EQM(?P*HagT8B-Trj0ui)gl?* zPgCE?Phr9Q?)C&79jmlFvyd;s4^+|H{YGyVIl}N}8=p+Mpnc;^JhD&D>Hv8vxu6AH z^9HL>pv|+p{W+B}YQg9nB&>8_#`t6P?sHd6-S41hV4eZ+#?XkcMCA3xvM>IPwB7NgrB!XhS4C64N=-WQXYv(7tBPi< zver(k9;qoJy-}C#siRrPx;Xn2r^Y#%2Din#(f?Rrem_=Mx`EaTg6`mO)eMQ5%^*!+%n4*aNX-#y`jD{og{sxV2oR&bf6@sLVugXSF2li zXV*pmWpi>wZ|`dSdfVB!nA&fvokP?a^v8^gse0Mq2P1XWY2OnXc=^L_*2jF ze76`3;WuidEeP+yM&4kOeTPU$T-)pPlA{^+iQ{rW(*i!;HDV1QiZ z(Oo<5?{N4fJjZo^055&?FJS?j;sY0-F1^`PshT!ws0u^(CzP*eBFAp~?m{cNqUiM2 zCkq8k&=VeQ-^ItQDMJgAt4TkEQ4sAV$|$@z1u}huka zE%7Pj9hjP1IrD6{4;vNWdG{?blUME5h-MQPMHyh22l*5WSMdMRX3GZh235Lxa#fA` zbVa`Q)!}S!6(_V#lm(4kM1laBlpb3YWNI-XN$u#3l4_E-w7Fn;J&qu&;3S!s z_^x(GFJFy&-Y=6b9A%3-z2CO)yEz-_1x7OTh1T*Lw^ZOUCa7 zQA}&@&TASRubirY;lQY`P-%MD2jpY2wKW`j_4F$2mOwehlpW~yAGF@U`xcSuwOz03 zTYR@POOZ3N*EhQFUkjJ7adeizYoj0woY;qX6vK#Cdris~3!92|6YUYZ?8a}BF^O|h z7Pv=3R^^KC^q!O11pUh)a-cMg&$vaB8fEo@q9}Vj*;g)+5*%L@;YtMur>d=!j?7_J zi~e0}yl+JbK9;Bab&rtHp~XYpBqzeC_~Q;FDWSz7rnzGF`d!y9xa1DuY(JyjL6H8x2*~18I??b_q#AF52IvIopaa#$Y2t5|hsS9xUT9hPc1A|5`GMdKQeAdvzMb_#99~&*DXrOK;@E z!_Bc`F;Jp$!-dOc-P6=Kj)^7Q+s-|TU{nqF`X?CTw`JAmzPHsvO+FreX9G(|u@~LqBUE%N|Lyt$W;CSI6PEy%ab4N}7Bi>saWy?1yxiAyt2M;En}!d|Gk2q~ zj~8P#wqC#H@T8{boOZ36H{cshm}`*(JgQ(b7XNl=>(j_02SslEQeH^6!z|ZL$9ox!3FLyC{pC(W1;^E#2ifRJOFiRL zE?HG}1Z=JhyPqG8<{f8dpP=*k_T8b3^JGiZwKeMJYiJ4Ux)3>&f<6U=Xu)=NpSt{X z`OQTfxHL2W3cn+UWnQEwV`7>I)t~g5+1wn9UTA6arUCqlZz~}_O7hLXi?-zor!$6` z=N5IXkPiuyGr>IJC7pl`aG=6T>r7P3`}gW~yFjw~C_*FdJN?3bDi22gD+D~8>!L8<$^|ZLzNMGsge|y;!eJ90Z_4%~L9BDSy801t(Qa#_rIv`o8% zNt(WEt(2_t^Y2wOw3P~mE>p9+OP=XE^wu*3m$xaEC67EupIMBru(j{#|2r?A~a z>~%9M*;p5fI2fFabw3SQdbxku&e<;3c-Hj#bt)u@ksZGKD=|AiZwd#@-{`RAS>-bdK@iK9h&2}Ud~@aZ znE{&HB$t;zZI45@UWk0a9o{lotN6Y=Be5BwiirnfpH-O z=ToTqdE@MN?I&K#fL7{N4=X!6yCV5ppuY~Vw~&vlr!j(X1N(BCiYp9MpI84um( z&re%s#}G#@s=Wx`xSQ3RbPEFmj2G;2D)I4VgburU)fPZMk3+ek1#BorP#vr3w1R)V z3$&WD^-2>!(nx98lTPWsq1ITyHmN_GOJG-L`7Azid!^rF2F_m@p#u~vlVA&Rc6Q9^ zY75*y-}9M`80CXO57o-iLRNoMK*<8FV<&S0i_abiJwg>duX}pCCI;Kk33)=3@29}^ z&`f1k+7=E4#!g9(zX$8^g-14N^I19;$;A-(|4&;Urw1pV*k8Gb0b{-wQek&K&o+ieCeee+Nwnm#laxBNj_ z;~A&-V&lU@K|~+xF+Ap87Q_Ue_J5(25R{Ae;vFt*fl7tU!WZfO70R!l52=0?`{Q}v z-j~CCXD`Cl1jUvD9?P{@J`yj>hlL!f0t*TF&6_OE53MRc_pZw>8=7UVVcpg6JX?%Ee{UI~H4Ja|nGq(Jr`sjeeQbt(Q4c=kf(>Lxa zWwbKF2b8kx|GknjVa6HPV)8Z<2}Bno#?>DJNMM?4(=XrDimFHIq3L=*8@J);Po#(t z3GXXU6J9f)FcSe0uES}YpQgsr-vbvVAU4)X3?F7oP{r^dL}Dq%BO(RyMcK16g1yYM zR^?EA0fPZ=9KR=As1U@2mRugW#uBTs_c%@{x%M)kA|onU!|SOpR=@BZivB0KM%Hsi zL-ya0zY+NE(PcE%Ypabe=xv&~nLVjOhbckm?+VU^NIL<30!R4xp3iWMns3-g$(me4 z|J;$<7fG>MLV0`4QPzZ0+|Z0X)2KQwLB#UQG-oB z6R9UN3x(5=njoO?&!tKqFkX+~D8l+MQCB42<+nrCu^vuy8lbbi-rjLV?GbQqXNjQ3 z;XldfUBv&s!*C9^^H|~0T5EdhT;T;Q3m>L(_{yY(JY(tDQ4 Ff;cp>`{0H`nbbA zmN=u6k$?XsASI1k!5h-~3fxmzEDABbm@iGrE4s(IL-A;add%Z>Tm_ zJ%{509?T6LRcE5j&ZENHV4$JId-j62iMT-on9)_6z9Xk7E5|dD7NI-9Vj~d+@O%!d zp@CK+_%J1P3qe7kcuBU2rz#JBmSCWxcBS~983fzUxR7|)m`<`qL;{MF=h$${pdN_& zNN<|YW)=IRtVDEbW9x9PoOYr>Q)Y=R9RFesh5r^sBVG*gq`en=xs(d5@e7_E1K`J; zC-6KRGRwA>^}6+e~;f~_YcArdnqJi8lWA@=Xc zouv(&(rqQgcsf;xQFWLKZSRH4gBWoCgQS_10gVG*|I2JNZ9^ueg!taukc_|6kpLh; z1iM?FE}rU$@Op3pZRnf2u_HYXf&bsqhS|gYv6`Z&+J`8o;6M^Y=@}ZRn!f^B(`BHkz;C+&~=%ZLghVIA{$@Mo4O zx#TPOJK*kB1qDU0?2Y(;(3RuKFPj(3}JS! z*#1gqkW@B6$tbq4lMR74gU%kuaamg)l!n{PaE*FUA?tmy1uC_kz1|%_@Nsn_>1Xs( zM0};@*H(WDz=E1?h444*6 z$h;k(UUOY)r_IjE!8Hb4;p$+6$sY-_7m^=7JzAaRy)D183iYWQF)m0Yb$ctb^varL z+8lvI`_E}A2>;^$#U?A9kf1z$`r6;OSnA5BDL1Bm^ z1V|fkgfdLniAh1biKSjuYNeDX@eB_Kehi|pn1Q!>{|Bv%D5cXdRF@o}^(X|sRQ(Sz zg{B4^f|uW;R?%T@0Q}&gXxTDaK6xRp#sL4R>q(XqME8M-7X$==ONGb(hd%bKGJBCZQ%V19`g8&hek_XR@&4-xh&9?=Y* zDjggM_{3I30WOKd)TX@#xj`~laEur0|9OX2@68f)-4ENLucwEskqH?eBkC1R4d?$I zYJnOlN>&@SVdGdW2{rp)oCMNNiSlnVf_NW7WEOy;#6?#qvYs%9_kqs!bPCFu)3ajr z%R_|Jnc#U|YwKAAZ@y`JDa1GpM^!oSi%kETG|q`KP}m^PVbXYc!+Yv8@TG6y?2On3 zlTotmt-b#j#b2qlq`FviDSENkLe;T_V`L~7?Z}IoPW)+Vf0eMXFg(n!#{X59p8f~J z?L8=tKUWOo)k*)lO+b4gq{;wnc1Kf{ZfxW&QkD{H25=}~a&~j1!A<3R= z&v0OV)|Q;PxFI+;(|x$W>)q^j+XYscIzIdNqojjsPvt!K;uEc5va(2r`ZrtV;y+X6 z?=P=zd}Thq1p^t37wrR_VPRvj)dtLx>eC$;YHPIpyBc`utvTcP0Xb2gPBI9$zMN|{ z{@6jpaTLv_@T6o+g*K;q5$qZ1xpB7+On;;o(AIStq|E^+i-UG6GsAvXZNMUQS@Sb> z39@!4I5my;#c#gf?Wx{1*wab*a(XBF)`U6RklR&nV$q+HzJ~|k8W-4F$?oc(29r_s zf_1is*y6{|V!LP8jS$W(mi&Xf59DwPl-Da+WOs3ws&{am%IcgkaXjtN)mK-f_5_Qw zn|lHwtn;Z41^k~R43+lS1Ef^|uz|^wXi0r$7~Uh4XcXuI9%O%&GZr^6+@A@4R8`E| zqR$iPU`MvvkQSV9v^a>ew#%2AMcONG-S5x>Q6yX(ej$CPOR-U2n@sY=5) zggU7hi<_bOKaTB|f0w)sBe#I=1ude>D+a6xc(jMkHV8af??Z6e>WH^%8iZFJd;&6U zuRgq9#G_z9B%7{Z_C2bmmT+zRY5FV?_VuW_2<74Rb<2U)u*Po>LbgM-P2^s1uwpt;VGq7J_LlzM8y|(Ci`>D-PQnR-@}%JR>K> z1$E_o3PnsXyq^SQ{-ox~B4ii6@L)I;!_2#Vo)6()u}LlO22r#=_!ltN?CGVP$scJb z3t`slrL-}({n(qUr8>-MwY&LSiH5SU09Bk&p{-R5otheq;{h$HK6F;mGoO@$t&3}? zQ;w|42b6DdqcQF*+~cC8mX1Rq-^#tG_S&iNVSa^=Gv5JM437LlP!NG&O*QZr4=ZO);|H)ar63|L4qL_P0kkhV0@)>>kd^pU@=a82whsue-%xjXBZ z2ykN{JQUm*B!j8{Uo6&fBp%|+rSEJ2r)S31}2W|I+l$dKQC|ezEjfWB1n1r!2J<5Z*IuDXs$xdr@ zM9E&l4ls0biJF_q&>tv-RjD8?p;I`Z%Sm8(wa01Vx~{<{9foaIrrYYR9!V*$AmA3iK|KeHs*@nP2k5GUaQ z;$%OXG=TFP$CnSx{H!NHASqeL(2PdOg9riRjra0vM}+9Wru3sK^YAUXyEOk)L6&gx z1RmuHuzZ3^Jd`{1hUq<}JZqVyJz8vUfpfT{zI6Mi#QA4gZMv?m+tmgna3VtGgC7BD z@&75EB-;jB^WTpzMbfkr`r0W+$am}ui~_2QQ|jYHU+8F$Fub(g%}b5TX3QPE%fQ89 zAFej`g{zo{3Pcgk4^(q%s)csb8P8JMDJ|{~E8DV}LSN}!tKh*rRo)>1q2qdPotNH! z4?DpDJR)3BVzeJM=3?AaIe%dK&p&P;a~1`S1ba4~yvzJNt)TrnFlbHX58dmy$2zp5 zJph3CKbumBXdGP&SSay#pX|(WcF+Fga5{XTQE*}3tAxVVvxtpJ<(h~7{W$rxgZkjI z1-!WUgL&pkD2E0PZx0WLgArWtl``sZ=jz+zP{6Ik79RZQ2tB(rqcM_l{KNGwnA62aA1I}Q3W%} z;^|YObq|cA(SSFf!y&*x>h0XH;mf_V+6=;Di-2>KaH+&{&0Z|b8V98XQa z$j+Deus1M|^?&Z&dB27gj}b`}x`M(F#aVhf;HNh#pOb$xHfvhC`j4Y@f$pu^W4K)V zRc};ERdsN?s)%eWP3Y;$8&M;$GL&32KRRU>10ml(2joPh;%^ z=}O;u`_!Ip4;jpQ+`bsQdAkUYLsL44G!>%K1)bSL}%2cXsE%OG@Wx8wbd@? zT5H7JYA#YNSo^m2Lm4K)EkewVwsl{7cS(OJ0Gn~mePq8jXB~dEc8F>|J?Z+nanS50 zOL$qatWdr0vhE-`GgI4Y$!>cRcv=y#I1|U4Th251E(ez!Re)Al>(~9lT$cI+CreCi1$VeLeceDVvHJJG|7Ls z0yNwcD`{Ads!M=?3l8jtF?t71PPEwaxnDx9T=$C)Md!4N?rd~rx97z36&&g`yPmF1 zI8Q+lKfs^Rp^VDBCEJtfcX^`gKzOKL-^Wt$qin%}4LVIwWmFNOA`MJk!_Ggr0YGT# zJ8xUbZZoyYKZm`d0p|~S9a|hfP{A+ZTKh1-LAubkzJO?>&P?hIG9S1d_+<4OB;wnw zJ^sE*m!DdA049`Ie;D>C_8)aDC90)S4b23GAWSWJg#X?MS1YEhC$c_g+U_=ctNjdD z-ec7d1zZey9IyCQMs$4GszPWVI%?Qr;mIaD+>?bp?ja^3OJvr@Vq!=aIxqLOp4oip zxF@0Pon?aP3=y2fD2If;^u@l`$HxEJl6%yk0qm?hyZN zTY$h+ZD&Qx_nWIUY#8ATlx~)re9F!xy=uBoci~E`RhLZ4JX(g+O1&e?FGyBbN_pJl zs*m3f+um&_-7IDTR|WRs0TXp@P@FP88eVvhxfo>KZL>7)|Kg74qLJY%+ar|QeZvc) zh}kmifllxy4U(7j0~)-!i%d!TrOWE8l#kPh@}KE|)=lnP?8OyBuaB>-#8z!Ck(f?- z_q+P={6Q_OYCBf!p?uTvc!>~MdX()e8h=z;VQ{cc^{U;)CyX#(E3tupn|pIamjSP` zO}IEM8M+g1g;38nCdEHmJSZ z!Nk`Z9-rql)#{^pPRTWLPCS_o(?e|JHYSVDy*H49x(D9RNNVHrMwPZb1 z4$sqG*Z*n;=z0~hy^&A~fXo3Xy}}b&Ce^zHo6khU7z|SElrhq}Ke(RW1bBd6x&muS z1@7nv-~ov6=e-@)+c9upVcF?@;Z=35hM7pBE9ji15>Q3L;yxa+?V zNQFM)X)FXI_Z{2Rn~xA_{n)`m5o!+xSBtepB6Lug_67M?Q&Z6~LT(bBsVB>yX#R7< zaubWcS~L+XZINNf zQaE&1PM4rxpl=439!+% zQppqOfB!pip{?b(QpRs6yWS&I?rS|e7Y6ZL1`%S0)S2FTNjOSWyGEpxcgudxnE5(oimi1Sgp7Dnmz``v$_O9 zv!N%{HzWpg5_{tm=r*hEp2dqU-hjET!iBRqWV}&!gX#8GiRKvd7(u*S$8$>mmj5VXXlh z2jS$%0tnG}J`!DZ?(rpdTp}t-^@E7tim9)U!DX;5TkRlnlN3cW5!YsMdAd8TB!Rdu ziKMO(P`)3#n36)yzgLv@o=C_ThC!Ze@`snLak6wgS_negUsu?G|Zo}W-g=Jp}7d~e}jM{akg?}4JKZ-HW#D~YM zeVwNl(bpmhS?!!c^w~)lYvH3#4@+=GPQS8be1Ue7fEX3+tvb8`uoT2h^JTJ|&11h? zR$E2){3o$zjO07XxF&2cXZCpduvhH|Bkv62a*3q^8{u# z35HpfyB(<&`JwIWho)qoeuICo-Q6E&6{&>3SJU@Pf17R4vsu*dt<0+%VC69>Iulpz zep7Gy*^|oqW(&s5P}CzhHTF!zvB*%wLLmi0Dx?h3T^+vL%IJH3W*yyBi~dHP zmITu#r&O>KDdstjs~z$>laXZ1tU%A<(wYT@Js)5cq7%9oU(@Smynn2Tu5yCOL5u@r>3{G0KL8~NiB0JN= zY(pDx!ZUVfkCt-akMre_`(fjSSEI(#w(Y@lZR_A61|xjT=6$9j_t-5fW#my+dUxx< z(neY}Tg%T~3j@pMN%0e@ zy{sfc>CzEGmR9=#qaqteq8`@^@kMc}AA|~kpw>8Az_#sAdaI}nnW63Y;ZKu-uW!AK znOzi1P%#SU7`9L#mFR5nT$3CY-nn!7lfV=@aA8Oxfy2-!5_SDvSlXU*j5bQbn0Bj9 z?#-D4&|x1lM}SH@E%tOkt9^Y0yU=+G0E{woK3SqIC zj=8EGU7tN!?IGqpN}!GQO*VO$wCbv8Y>{|>^pM$XqO~HT2Xy_;!Q+X-lG(VT+98%7 z(v7}$paES6FsXD;EVYlrLsdQxXk6IaZ zxQoK{rmyBB>Nn!hbwo0HSC3nvM`X?R#Bg&F=EWvevxLL*&#b=NL4F`Zs~xH+hR&*P zb;hrVhT~Qi@$octsJ4$$`?VYhJYCd7;9UuH3&iu7%aAY=#%_sbGZ>#0q7$RVNx{zy zpD9FAm++Qk*9af}oJ^cLzXY+^o;!*g11=3K9;3k|{63a?8`o$?PGCW<9| zvxB?bJXBKVeB-9fPX;lw92~*`cZzONA97GIXw69@&Kv-=LvD&>Z8$dH*L__$Npkdv zZh(#gKULFFqB>0y0h~cEtonajY4&{EIvM*!Mqme@-Yv%^{<9Y*lR`)d9g?!Gs;vo! zB|0%fN9`yIkr@XMsCE=BG3xSqT1IQ>xtMOgY_;=rd+)-~u?~4c&!d8haRhSxU<&Z& zuyE&0u2@FSNq&@sEnSI)B;~N`41K4faO5u*<+ztq#>+{pndPS%o}HL{1Z!H!E;qFU zET)JT{g-~cax#;I>GUz8w5=eaZ>K6B2VN5#Icp?-27R>F2Sf}Xuc1~A7Q&Rjb_p*r zi+OZ%Aqfc&3?w;~-3Svn^&95NIf}5eX@QihUaH;UBGyo=IwqnBU`#e3!2a3n$Htc>^}&L3cWGCh({;1`QE0NJyF(ETkE}Tak23?3{@L__Nvqt z!zcEl|6-=8dpQ6-#_wG;xF$)IW0R*ESa&e`v)AJhES#-&@WHJ>O`VE?>&B@{Vf$?1 zo8_%Xs90VdS|kkkvS4fz5?~}w8u{Uuh96-&uH62Ay_Pe=B=+spOX+gjVofBd_pG%* zgyMERLP7xl*k=ZgvwTPiwFH5e`H&y}>$$MlQ}DUwXntYP&8(r+<9q{o>G^CJk{k92 z)k|w-zqg73vtjU7=u!Iw>#K3#w~RB8hOH)4F_@}Dx!IuxH_X}+*B=+AMqDl4?ZSC* z3-ia*VZYl=Rby8#pMnTg^odpIZ28?7@^uu$WbE8DF8xt;*!AHyy|XOQHqx*tGF7SQ z{}i>l?WrTa#zL09j}Qu6ZNG_>GP|Q|!P#lj`-LB3QR8 z_B{q-xBN?B%F6$MKPWrdKQO26Z^pegicDrA5aBDE$8Z3%MdW_*vijeD(vk(LZd+)- zd{Kb~X*3S(+dgJKM+@_x_fDEYM@LTbIF@ig%#3y zN0039Ew3J>%=hW_0e|;9-ch$!tw{zi2Lt53+4@)>4+cx{hrYCp=tVX~+G$%i1ZEm5 zmLptIJNG6BX5f*QRjah-d5BYQM6JR46g3y=4G5en7*lThwSN0Tez=hTf*TQl+O zb)SyOmk3GH?Uui}Nzu#fw=w0SqLH5%r={<-@xWX%_*N+Laqa#LqY}ZcFxA{P4EpD?1>W$ST1}a#HJq^+1YF zhH+aa5fqY1mg?P)tK7{p^YV$tFeG6&lFo;la&@aQ^(z4X%i|AxmG5y+(fOCumL&sQ zLSH|=9lo<}JTXrnL*#K2f42vLI$jguMD#SFUBqe)ZiNOMIcGxE?Q`dw~;; z)>hNw^Y6hpG#JotKfjQv6j%QUA=8VVy&6;gG|mqj2`Qny!QFZfj4lh_?jb6DWnbWs z%Wa9DC#+YpRra$HC}`aEw^Gj3Mb~>nJUUEfSX#_>P9&;$F$ON#%DTfA$<55A+}M16 zUd=bW=1M-_h&A@CgQH--I?+w=&*}Up(`Nd8b65g@i%CoLXY4xohY6iY60P))UGG>R z1t;_BH@1j89rtuWBC!DS^qd-h_bG05JM2)pN#1F=y>`Vyc@MKhCS(c6yL_~O8<#qS zouG98nOI&Mu!h}>JZG#oMdQB@-GS-$KAS%o*DbvBY{8NyS1;z!J} zmb*RIHi4Oueoqc+UQm2%RCsMgFG7GMeEdiD5G&X!KtS`C&4J(CHTiiETAYu*X~$$P zB!hEuDl#6tshBNQ3DPLg9(dgRxF7gqXqg zQhZaB?D<{7@__ki9-&?K#P{e`Kl#9M+J{>67dQ_b@{}Apc!@yI!q9Zsz4p$28Hk-m z8UE;_MudP+cs#5Tf?XyeKdqL3{#`G7GN73M;-VowN@%n}$nh71C=KZoj^P-1IMwX2 zAOrho>62u%1!!#t8hV09wE@Xrh10g+fZT4alE+mmj>7Hj9G(#gb{gJWBgdpy85y;! zPMRsLoo{Q3|CVoS{D~M`aj~l~(6L!+u6!h0=<>uLW_3|;MUpDg! zu zZ~t-}^|6WcLiGl|_?skPsY5#lHklYtmA8Any4ZEeb|F}Evy*JKd^?v^|JyJ+5H1SK-N-g~UY2(as$muh47 zMJ|bnNITx86iwYZA3UQW?6C0X0UA9U<;dVi7|1w zz|L$W(J!bV(;QeFad7%ONlY85(uxIz%hT}!CM@xdulF`AsaTKVuJYn~+ zcbGPv(T6Aey~g=NV>uXa-;bYExBcGb^M&yzY0#hn?TRmH?L*j!ApVKt(M;}|_3GNj zR}m0s?e=belYfyi(=wC)&(mLj&Rp%BMb@LF%J?)v^phUhB;pLvJ>|xrE;AAJ3-$^J zeinEZP-zV?QkF#rxxZqKMAQq!Vi(WJ=>XSN!l2JxiVy8r0m>uCQl;e@qMmIv%RgB>O5LE0P$#FS`*umOi&b_u=n!YE zRl9>G=7yu4uVvhKt;grIWZMLn#5|fwyLb(gK1B+kzQ14(ip0}_L_81XCPJM39Q?*X zIzf^Gxl((a%8)@cUCgx#KwbkuP^$pKDpkk5D<^D!&n%#>xaKij$qPVWw z-I|;*W9HPnqsx~P%Q^`-tWzwUn}Ji-_% z^be$WN^^95-4xvS-zhEO;3`n&lPu&Nd=LmcJXZccM&8_TIYQ%T|A~gIl@w8K{X+#( z7kE=@?WXmH|MGsq7?l5E(MjQ8Y6)G1O0;}(X#c|d!vnZ2VLO1*5cxl@y-`hmwC%5A z^MA1_w0cEF(V@HkjLGcB+@*CmkIUnl-F>{L_;KuslQ)efP||zmu4GsFZ9}MefQ?(; z_lZq7-=}E;<~|<#-_JH`_qp3WN}98_2U}?{8JnI-+FWHV#h7LeGfa7rXl`$K-;B-mMD1m~3NZ zjH@WPgIK2D>i>lYpYu-My=r`gU3^kb266RvxQAOqOh7Dn@ZqvGuu95g>}e|INwv(b zOJ6p}Y^_dM?Ul8+kO+9t5^l_aC!7c4?4jVkRB~agwZIUashuY)hre}T%%xnTNECPQ zA;k@MqK9r(y#EZ~XEVl?@NOlettze68Axa+@3Q?x4FjH*%gO}t8pUn!3cUh=t2`UH zNsD}PsD_qg&f&)v!m!rhYjqE?c5jo6MI{$-z7QZY3i@U>XUjja|LNWjp6x*3pS1a0 zIX+I_i-R5TV<3vFMxjNlK&5&jf+gHlKdReO%G`-dO8rf#2T0VaKwnGn})js zSrnq8hb%@)wN*p2_X`?w#O ztauf6;zsi3n<)$RqLRQBLnaV*<|N0xBeM-lor7l7`1pR*>$Bgz4{chtg$YXe+@;c=s9dwk$0FZczByep65 z6ob;nNU^yOgg-Do7^MU;;5A^D{cDFaa*0yq5F^63QAEp<9>@&iRnm;a1{Z(HLm*d) z9I*q`22aM?j{MUV1*mpCt7rC{4bZbT75}M+lg+m<_;G{*jl8;N&x@e~^!?cVafWi+ z%**Yz#uzs3RNgZ)^J@fij>>+xKk>7p&5RqQBDv^ieHfK99}5M3-(N7Je)cW>D#4)# zyL}#Ww6tq@IPV1Putz!z4?GXaeRd5ICsr^k5KU8YN;=F%75$qYYo$T@t{Z>(r#IPX zpGMBzY1A*=*9P;ajZ43BKH0>71$%irP_pG-EY#oF>Yx5#u8cm4DKWA%HvE~1244H@ z%WW05ZGRdsI)hgBtTfdu zG@9m+MkUx{gB-f5DZT-VyEUJDZUlup;X%HI{B@)O^R58X?Wht5GRVx>=)aPKlu4z; zL07pz12gF*Oi7c#L8#MEViy;NUD+2$IEQu5Y>D+5csr?n_s$5#qK62EeNK-=lEckR zE9KG|{+s>Z9D>`A#Y%z9S*ruztsvhSeJcPRb)~F4upeBuNJh`a3c_DBjB(%zZz~mr z?X_Nem|AV=3;E*fAsZezF82p#oDnw?-b}ggL&6W*w%Mic+=pFV&tCb>JYOsdpuKWl}+?1Y&`alL(K)_Jp%hmFSiwH zyIait%OHEQkEfr2x1t{fPoU-9`k{$#t%3GX5cXY)%x7B_KompE8-`ZzVUM?;SP;D+ z34D?stdCYMjZa0)w*Lq6`R14)5cXSvF_*c-=cqK6Bt$NNq17*kVnAU#Ht7^ha}=w? zJ!M2bF&9~kN`HyiSEf8v=XJiKznMkl0Lwh&>Hd;IpA`Vr(cJC1s#TWyGLIp|UM(ei?J78F6bs1ca`kbv1 zXkc@ybQ-{Plet|M40SKg*bQiv|*FZrVI*6-cCy zddQu>(wTu^gdOGuKJGWaQv1 z6b$@;ivk{Md|rtFhZJ`LK1p>w#0LO)%E)+%iE$E8`yufK-45*~^3E4+=NTYlFKVFR zzh;U0JZa;55ZnDsp^rGci|SEAa4QJfyIQ@u_m94#W@2Y1x{cM9#w3h{N5f8V{{DU8 zX8})x@Hzm!7kmvzdAW>uJDVLFLRts8gQ}%!u9NXHv93;%^-9UY#FTuqO<0(){X2C5 z{I}vs-7#Ndfe{azT04tX`M5nWF)v$>(8IWt z28gnRZ-e?8AFx8mAn=jMNG!7zmsnsciYi1fiir-8q0upo5<+J5>;8ha6M8_O>1Brf z%%iL_b@=490sLo|6O`m>1ri@j{Osf{=Kb_nrM1uuLcE)4#9YF;pj(+iWTu3*jF43= znFsHL&wVBPas=;l8|E#-(g*4UVDGO|9T7MFi27!Ur`v<6bq zB(MB3Gi%T6^i}mFHT#-U0#9cm->DytXz?sD)rz;t@6te-9NM<<(QDdASV81ZwtN;V zveTT)Is6p)-{Qh5D+qt4@^C3Z33U6n_NY23t*?nT_T$A$~pnT z6%xotJ?BOsTct@pj5zl_S#t4&n4SJ4ZknDUbX1aTh=X z0HN%_KI-?W&}ZTUM|zQBclwaKWwq!2Gn)&kEPfXPuTW8#j6q9SVI9#v%b2sMJjh%I zT66HM27Kdiu^qhPGOQM<;NKQMY=dD0m_P~!iIJMo>K09FY+MwECPjVuVH7TM`JT+hYKu5Hclv^0xh zUY8EgI2RbG+$`PA74><4ij=1%c#pqatcQ5k{O=E@8?4N}?T-sElk30M%4BO|R@g_Z zus0)mK+a;GYGSz!37J3RdP(#|=l0A}G-{e~431~R{ZsY`2h9u)zs*M2v=5N;4`0^A z0{KN*=2|Doa`>?*$2VLrLb}6U;oT&`{nC_kiMGMd+H7q<+J4R^ZQhnL zt^R1gy=kf~Otxbl$-z^fI8oFOYvAwB*(IP?IlSZO6Hh(FOhqi-1bHMlLvyiM z1)ym^+`9(uDMbDYjH>Qjmjmf{|J;VVuB(m;6$7w&)hPM@TavSHgP4=MUUIRgRlX`Qg8K=#9(&X$*sh zw}0A!JO_CVuFk8nHpa4cG~3U62YZ1X?s4;;+2sK>G^|a9|7+L}AqbU+_dk)A+HrnPHg30{{XU}W+4xM$i|@dzukrJ@HE`Z zh4nX-h68vz2D;PZK;k}tlA=iF-5b6ACy#ittQ zx(_Z+sw=nOOV$*2(5-ir{D}S;Zd&1G72KWOJCfMa2=B61&hVb{HhAYarXUI{$C5CW zJD#fKkDaY>o+X-tHNAzis8Wfs_X!AH3w*CbbU%ex1EncHvDaXX9%SD;qEQ@n6~EZ) zhT{K`rW!r<)0yy`G=qGKn}b|y%AZuB;D6~H`{yk zF>>$bYM>=c$bC2cs{Ly8%y(DxKvdaBNb~tmwp3)b&6RM9jxQn@r-I%$5Ax8hH?pXH z!^EdqvbCxCK5lkQn|jc|GdSjDVo$k-J9X%K&oSu|LB~@tu5J#9(Rf zVHFCrisTBEj$w^8E~?;oc4@OI`jeQWp8YWyC9(goU@m=IeHn^t?XRsf0N}j!J|N8B zH<*<;1_iEwf~tsl3V4a@8)ORC0?D7JCV*>75^VUKJ~GX&kJ|l3@d9F?jTLR!b+hr# zHnohc@#A~ym!epL1KOtgQlg}Wu|^4qI^ub^Q+}rLwMdg#adQd=IQY5tM$u7i(2d)g zt(|)}l#{UD<5|%FTIZuy&9qtw8o_ooIHUMxX~{Ng3tRqh8=}?A5+OKEQA`J*a6t+s zX_E+uo8CR%3@gU0o=H^BAEHIDuQk-go(v^nZ9H^SLF^T@$9biFG0SN$?eQLGJfBnoX9ecB$b>`eaJowyn|q$b}xL@CJKY z@`)9@0uZ({J#q1S^Y$Eb%McApASSk^VrQ5+K9MDc`u;mWOj(R)T`232UZDM;aZ;}{$bf3t*OCnlR(namo$zN9Lutz~{hS8DNIa*S zJ9Q-i%Q>YSeF+1y7{s|%<2B1i zOrO>V3pID61WACu+KA&NiLU1ihb2ITro(&0;&?Yc^^p8f8HJ#wZoup;Ly(BK@7@~eVnW2CK**-VHrVQ z4Ciu&a`QWo;X?8m&fh)RMp0D+a4~kU&C%p}yI9#ESrWi@z96S|=-sSgP}X>JQiVNw^Z%8?bdw*Q84m& z=z1$pYGJD@5B;^NR2EG;1f7q{+papT=e=6ifTlg5f?vP-O80vwQDK35Ln$o%hCC-- z$ogKnJ9+4A%Ix-CBKAmaV@FytP;}4u)kgTKwU70VUf&CJgU4w!_+#Q zQb9heKaumz{0j#78=W6ro#~TQU2ZMYO_f`XN4LmJUD9q`(VHv_f5tOqcHg{t+N<3{ zeIY$Lz;q_$Y{w-%`d;o=tEkCrN81UlWOB7CW{E~=svkT)OjKgvHIdC?dzJeh+j(vL z@2!6H*s_j91PJP_eY}X+u+I)DBwe-<=e!zGDfkB4jGLI}Iq-|i?&t^ij`&b6RSAO> ztZ*){vXdn?!ftzYaW0NbikuLgh;n)kFtvBwiGd$v$wp}MTYM2YssOze^xj)M35ol! zTEU+IYyX}&uACMl%9Tplu$N)S`;+O_eX-Z zI>doXC9+uI?IfH2Aw7bR+bRpl$B4I*BDW#!T#}_Jwt{1~2w>?*6r9-+ieg?FX#IG8 z50v6|WmuPvx)}Z{&|jc}E!i->UogP`6~TW4cqe(<4fW2hcJWE=8%qJ&H2x#OUWM+8`{F}1VV~tyd zzJN@23*VGpB(7-eDi6f+2Y=DJFj!x-vc1LJvb;|?AJz@|{Z zt2rf@#!GKCzbB?tEBmHCTK>18V?>`25Zl$&8yd56yT=y-o=^$Ko@7T5iIjd*L8ut7bGnZ6WcD^`ARc7vL6{*{TLRG*J8lSxjpI)?4nqpmqc}J=0r1*9_Hfpaf|rXz-*o z_%x#MIQ!D&a4Y(myN>Do4DMUnystti{yt*1QlLz-RUTiE$`>ON{{v?S^RZgCH)22& z5bL+{b(z_7*f5y;a@Ph*3t)Xx)N7(^+i;M6hvS$vO8#|MGR)qj+1{vlTb>Lywb^$r zeu)TU!GJkY)l}X&ZX5d9d$N6>BU3{8zwz8+M7O0-VMzX_!U&EIEYXGB+1xioks9at zt^A9c*Roa*&z$utI)-cPq?H|V9R^duOkN9~eYYJ|GZoD%uoWN)_B$LG|D&j?s1ZD8 zXHn16=`@2QYvXN-`r-N_v--PbNsO|(b#KL+jhdG57-a(>f8zi~PV=A9&hUTOPN>!er_`6n*rC+WJ|++hLbhv;~Ima^K(W`y@oRW`GT85bGZg3QeL7gi0@5Fj9T@9 zDa|Y!9&7~2@UTXqah?1|gFY_H?ZfHS?(sY&T**je)4xtDhjM+sT6;xF37~6Zw95TiErLPjiR7}VEYvGRUof&gKP$a@9 zJRUC@T599Ti+-lqp3F}>FMK_QF0LcWwAAODGR<_P`G6F0tV`D{aJeuGtt8m?FFT>Z z%lCW8>{;YrszFj@(*7<#ZGH{itmQK0BW8dBB8OUr+O|4X0%?1<8QToJKxKKOeIstWLSi;r z^iWz1AN^~`@~Sj`R(MKqJEfwWpEMZZOWa>GK3Bu%ZFB86gquWEx{l+%1=74npW;Z1>0GXk1On>sXSoXR z-hQn10q&YI8F`=Lf}2(AVj4A;@+Hc*yCPOoc#12=JRqD-EwnJDc`3RqRR;L+xBzwT1o>Q4`0YVQZ`P16Vl@Wv=6I78^E96~SF z;nPzn`UMR1+T)$vXGtyJgk>)O_HDamzaV_qtNG@Ui;@5rcHF{Tu=mB%fJ_Muc8%YX z%f^sQ=A7?C%!o?67QpRY?Rdz82csrZ3t5S1;nPKc?FvmCQyH)TtzcyEKA?DIzYPXz z2wp7lXOK~D4^!rr&Gum*N1+z=))7NZ{);58ZltPh?TIB*N5#w!j_w3hi+ zWOFd@n#;_lOm-Mm6;$Lbs&<%dDCMmJBda`S=%N>Qqk;Lo(pMzFb(T7(yvNYxvm<}vJn=6pOu9xT? z<49AIMxY6gYy?XRaV+yIOLANtnA=9CmmW6l8~k9D-=8rQH`0W_v>?U%{cN6+I8S8B zUX-8@D%^=FCpWNidd`tAsn7Z-mLn^#$Hk)Wxv}jUF6hn~^B_gyDx!n8-%x^rE!p^` zX!7F!;k@^B+G9|%*JMn)$Lf2H~t`T4Zx#g3B;tovUChC%?*um%M5t^YWxa4 zrCS#9wYD3?;&ELaQK)e%g1GOgNPD|2j{N3_palB1mInJT%Y+DmbBHvGYI$xxBY~~n zww0NpdbJ0A&V{5eZ#IeGuTM9O4aOpYrKRkpLJ6I4GIM-U!Qp~3{s5QMKct*})UAE6 z=N2V+;Q0PMnnadN zZ)Pm-^^3<*D4|;wxZ`SztXLqxAq(64)zsmz|Id*VW8=pt;HTa2=b#ZENTIjg4pmY^ zhfn2mcd1*Zq{NTy^Ap{&NLbt}4a=+D)uuo7);2C3w_~D*rdedExWMu(5XCNcRy?iVhIz9}{QPB<6tlNoZw?PWMF%S7CNJ-DI|pXD1k&@=o4-MqUx zx=V9^p|;evG}spx9NBz?%5_zT_6|cO(vP8Q1fjH3ycHLjc$O9bY8osDKdITLP@VCe&?^>a; zpCmKLiV32{WdIAKISySp@1%{1e|yI9#v^0u4V5LAoxno@1TnSs%kL&u{9NJ!9kRSp zl$2`brRd_RVwte^NA6Z9$U9d{Hhh4RD6j1p&Iht(z87oUk#COXZKNO`qeo`D+A@O zqvyi5ba+ZQ%Lx)vMka&rxhdQKK$dPeq^&}K?T))c3>iduL85IMpopK@o5Yg0f@(C* z@?kj93W4jnNoqLv;}mt4AEo!}(tR5C*1W_e`=9eL zgPhq{xcrwz*t=b35lmZl!nou)a~o@d_hJ1!To08THi}7^y}d!WL|%{PRcUJcj!VpS|)>gsErd zmPV*XicjO3z#Mr}9a{zZx=MOH=i58{QREwQeqyY%kM^-e0<&T!9ok!~KjkgjRR)%} z9UquzXg^*Not#S8!<*Nbeh1F0w8&7pzbxnfq7VIPr_^`y-JsJVbed+ZGTA<@=;_Na z9~*I>M60ofAMY?w=PJ7K7KU_j--?oef~P5oFn^dv*`Xz>Dm$B_w{Xao^YvF!_`>Dj z>{hJFzEYDZ-^)_MU#51KCgfynFtZ516Z*p|Fv72=&}yjW1_#M0yYG(4*Y%oebr$B+ z^c&kw(2zwdY*~={jZJ=^@p!TMhHX@JRZ!U)zV&UOs&X!W;Bp4s6>~$%AFS_^Ixd;Y z23fsz?3|)((pjF`dVK%=qxa{2Y25?WotD~i95aX5`<(;Mm|@1b&!3{PQpoEM>7|)7JhqFIsqk+st>&8hJT;%$pPvgv+ z^xd4^E8Ux)`*w~LC8h>VGSXIhhHG&n>&hYc3cW7VHJYk}btE%?%`c5~JZ zWXl?xm!ZZZMeJ`&olF1))yWBhDn!>g^vU8njK!<2km}MlM5oIuH?A$-Z5@BZuNr3} zYSyhkGZ{_=i#q_K&|8_8Gl}MKlY#_2rWqmNY0wyH0`^Odpd728U->W79P{4W>TqQW z4Hywbe`xj>ZZEFLDhG8PXoS$|SX8gov}mSyNr5w3^WesFJ|g1XGf3Idp2h8Bhh6P( z?*z}t_&VP0msYzq8U{>zdAn)ZLMP+Djm|zArD`y4LRAh8*}m+%I86MRk3k>tylzNm zDcxCcCXN_MF^m&emYpkIGa(T%c|XY9wVbW*j@G^}I+vQ>_u#@bZuAb9c_74;QtL_M zUkCqg_I@k-JGndfAk^mcHx0)Kk9A!_2j4>j2Lo zOv?7)w&^NJYQK@f2+?};CzW51H2XXVQR^&gQ8$7SBNr{pOf2oO&)P#u*uPP)2KQNO zXkJlFGf!1im$d+VY;1IH^Aj3>A*=BeU^b$j%7({dCKr~0-bm@fW34F)DA+Cx8lEui zde}O7`1|%tK0Jk`)@)Sg$f%OVuqNcvaD<^}y*vuha3-+x()P8Z|@%`S%O2SuN zcPLg3H-y>3tiaOj>->BEP{Z$KuOe?X<(1oSOYNkFpiO_;iHBx;dtVQ?-fS z17Qk0jE=+Kbz?apdN!XD#YHfo5WJnKz1}q8{Z>wIy~&1ZzRDGhRHlS}*Q8u;9%QsbUtu+{z2 ztq$Bx3DOdH*3sXqzlNg9EhxEx6p?;P1WAplH@syKp$m!4?nt8;B8y^PodQEZ*9cTnYvz``$8cD)~4IUsfER{}EdE(%C@N80Qkh|wR23huV0!Wf#N!Ty*h?*@xxFtWr`(PK=~lBqI3VLfmQZ6F7|YsZi7|=yZVC+>Xjxe z`H$6ZX8IMQIHYMtB&VdoPRsfrO3KQuoz+^I@%#u_M4amJ`->1&OP)f5r*u|nQ4Y72 ze61 ztbwZp4_+3C>;jy82+K?_bY6Qe39ho&{KifV2uRx7MZi2q?S`gbQ}ao!lXnQ%uIXuX z6FVJC7$i@`A$&E1G{<9T%QbOzicf#bd@agi2zS#+%I`TZ`kKpex7Arevw4aMFDi_9 z=>G_U1XRexM z&{Os-#S_E0-gTMYoSf?Z&PczSZxLT48G82^#>248r`thT*t6xD)Z17d@z6P>z-^rn7p<18W{hZ2cy;AA!t?nrcch+wLs;~%^5w(u32Xh)rrzMBH5bdTx5Tr9vdbwp5T&hhhNEDdlJFs5T9WU zGB{c=Ed@SEu+Q<|o+$gg;cZ|g6j3f5kE^AW1)*Q`iniUqe@n5aXz0nvFvH(8;Xodl z!UECO(y}0d8Cibz`s<>Ay|0JmW_(Zzo4hUeMr$Aqoq)@Jltf)dQTN?qwiuu=*c{IC;qnkOkFRiT+*WkoCX5!K9mcOYe&3?v|` z#Tu~aVu`WVRt8Gth9Y=VaPAwTw{KF`#*g;Y+eW2o zB~QvDuf0}^+tkT^ST8Sg$-3LjGS;q9WvlAdHj!1V*VY+4{@fS-j5#;|y`sO?Gg$(N zhBhr^q0kM*F{o`T6vpayU`l##$!at-sK~523U*&u0VyY#r;+^s6>;szgr(_ZQ_2Ab zwYY$!-*FIG#T$>;a7!?d~W> z(y?<}YeHm778U3fCMZJCSR{V>-tSAl;AcD2-B%C=!GLcu6)jl)3~ur>sU$;z4547m zh*K1ANB(iGjy#!szFHJwi0Wg2(liZ`y)EsQlzN8%^SyYqiaR;%RnUkLkdc!W1tu*M z&7!qfnKONs9K>RDP*~(^HlhVvqEl92)JB57mLX{-{L_{<)WfW--(Fz}X+!F;zbw0y z%P48>>oNZQ6~WC4qbP$}OD~`n7)wuo*#^gy_|C4&X1L*|6J_FgQ}R-|B-6I1-2iqs zv*$Dlcd718cP(DAVIcp8D~rPKvXJ5pQjBA=eSy<2aAIs~hOtL)#~|f&`gm~tmrOJ* zF!HsLeG-|%deVG4YVaaw{$tfV;fbKH+DjX?<+}J|54_B=e)Wm5a z%)8JPBE-`=(?tRMnny+K7bZk28@|m1F%TYk5dBqJDD7LS>dd5bBVu#S&K=IY+}NpE zLgy#SwTvF0#>UwT_^x(G|^o(X0EaPo5690iF*7RA}+y!JF1_{(uNq z^-k4*W8Vg^13x8dtaRL?T^i#=ElFy4xb5Q*|tIj^u&&S4e z^U-8wXHP3vH1s@cI!Cw7^-s!n@+0q(joNCNHs79JcRv>3ovbUKWaDpaqFLTi6bM=1`>C7m@<_h^ zhWSb}@|MEAoj~-1)aLsmL8?AwX7A!);vZXqsFXiH`~nRTJyBqTH?NfS#MxHyui0@h zH6!mR2*<1eV8HMsR%m*sb0qT>A>6<4Tk-x9kuCka^0M1}LuD7DpPSmN@V`1J2W~i$ zip@RuT7*M9R9TIL;_@AFe8|vDI&VG`@mPh9VCj1{k3wSDapB9t^AD~s1lAE0p8LE3 ztwF%uTYV-7>H}>7uvlA}h8Rz#A#{|HErSihY|PI57xt+-*S8pM;)_gn0bm`bfgF4+ z?k^)bmbb^bS;6|4nnS$-JY?$`DnG*mhp<`My-uOYKr4o0iriwxcdX!(3;Xnfej>j# z3!i)L`_Cg-WYW>6mgrjh92;K2801pJy!XsH7z~goW-u+VI6*s#+_8?yqxAyBhKJex zr!GW3B1OAhyEcm}kVr}~!*3mDd{1egjYNOAZU&g9-O9D3pV8~l zn$6AB>E5l>;H{wKBD34gs%CmHUn%CZ{j4(Qee!|qO1tm6GFF6fq{Sn`ei2KfulS95 z`p&16YC5X^OaX6D`O1ATi!!PJ->hN( zGLEun6G#ldu@909W*W)K>P!UU@4Av_?p#li*ouzTAIGFrvoV9yg$K(amP0iwmBYve z@Ykji_pIULYLogYk&P#p_h0Myk;ilxJ7dGJE&g*B?Dh~csXXB&w}+s+U;|F*>y>Gs zdHO(sM*z9_+F&|erhZF!yv?+B_h%qD{mVuTc|dX4m^abi$L!gv0@sAMPpy9A4l_Zk zdpwgogn@G3=inL4e1ByZg=x$je(#Eb#{&Xp>6b2ftl5SZ2V5w0VBE(WUTcBJsB`{Z zgY@Wy)M&#+1)J4X=u1<`*x>X#@g4vxI6cR*75!FnPOKA{>X~-+db#31iQVoB74~vB zco|y%g{}KT}kpyY(Xf zHt)3+K6YvMY57I(zg_x|W{SLB4NhH1YHO=66LZYCZxzg&KG`bqMW1pv$`mIQ_~z2G z|30vLYR-9opFcWUV9oZdW?J(~Ho0KX7VwE>&N*gWy}=YNobh(2MbOVxXAbE_FdgpJ zR%dF#l>@K+8nu1)Z511;Vk6@gXXW|tESyuRrbAGpAH;nft2%608l_S8>|FXpE542M zWSXp3jF0e(pg(@$HH2In-q*>I|M;p@0IHMLdz3a;aj1AC;F-(!lYFXqdq;TM4E*=U z4QUMlEoD<+28hih2OI1<=9vy~JEY2Yx9eWGFj>&7jeA0?CDKs(`}kVgT|`9Wfr266TBNJuD9pdoqBp5+O=W+>vz2ohfV{O|_j&N#H|q>HXCoi zo8c<}0Fsg*IC`IVtv-s>HHZ!V6HYYz;qx@4V`n_LMWgn!FxN>u*vQ+cgvQpoW7lVf zf48TljmzZt?CC@AhJ?uTca%K!b_qkPXbIdPjcZB)6C;(sUOoi;a%>Bg0&8!@se~5% zXmaB4XdG>byO&NU`@CeDx?-Yb^Lsv*AgP4WkU;Su4{~pqv+mOfpNVVwWL{W=O&=kR zAA?Njezu%)6#W#7JI@JY*mIwa(sd=20`4w4@7YV>AK`8>Z9&ouB>O}r)gFFQ)tC&Z zoP5B8+so=3*a^Tk--W1(J*d*)rG)DLRZ0LPRir6G%5tF6j>K7$x8(4SDDW+``!?NT z3>wZtW&U1p3LRGdtV`sX)Pa-OWV9^%z%A@}`3iQ+d8}?kN^3oWY)bI6ynDUbVv6WH zpb<%c(V;{-^;CKjUiR^qGp3CJOm1fVS4&9Ml7N^pNXg3z z&?*$lWrE?f*THTfoEa%` zD2^pm!nHeD9Ei5yzE@9=0aoj4CdOzAi$Ezi18Ax=>u<`}Y01q@6h5%qdIRAI5fcae z&lNi$y{bSs5#Hitd9gnUzevLbt;Xb{ctpioXPGhjQLjnp4tBV)c5+P+{cfA&2q|BZ z?Eq#3MtnMt*pv4Ltm+ZYrD$)d*FC-F*ZLTvsC( zQz_r)(1e?d8Yds|hE$<3--yL&i&CpKIHX_4y0h1G8DO4?fcx_22iRY36R(wod)Ux#<< z$wM{rN!)t=2t9v1_}-oJ(ZFB}SS(#oSbK2w4Q^zRA3M`w!hBBV(gjS*&)h|_ESo~P z!?<@1*^HPiKaETjDBt70lHKANBU8G+%NCGNL+=JDml_*z)x3D#mWPhw`fW*>gc81Z zNNKV`79VT0YNycNq07fB)Jg8osL!zd=1>PDiKWLR>8@g)`@eypuD|+X3M9c-d|n|$ zg+->t;Lzc2YT3DKRoUiS>>TCa9jPW|@EePMIKTB)-RHhuHe+b;?@4t;04u8V>{VG` zi*I|*G=DlhE3lu&1H5Z27vFzb+o|W?{ofK1&9rfj;i{Z)7yYAG2f;j3_<_ln+1HjC zoxd?s6xC)*&|C@cr*B%a{UlBl$&zScTg-)?O*B^B;)CY-wa}%w+a~KN(p>^~?mYdEw2%7=@eR^RRqx3*Zg$}GrcNJ zl+L7RzxK=K0o-^?_5SZci%fCY(3Kmro?LtCS!6p)Y6>SwVUU70%kk?G9|4m07@B_F zsY2f&`k)UQeNPBjv?F1gDCVk~@U=r@#-fo&6vTE*bU@EoxMdlT#R8$9sH{qBdo=*& z`EYWeyM99!^u3SjCV)$K)TPw*Ti&LgZ+7m z%_522kw59V1O9kMG1Wy8g_O8}0g%Zcy2f;cKf5X@yl9Vd;Wd58pPVmOC?(aKa61@n z_@rDD{&U&#B>#{DlwmIV8noxhBUhP=d-tRzmF>O;*^M_!;NoTrH-W!pqK&lv%=*Md zSu#e*Bb}ln@6H;**nxtOROu-{t^9)fC$*1*Fm&SG4DG`gA-#`{s*ylueVXW#$?oKj z3!HWxm;U)zz2>RQpLtBCuspv(YqX-qG~Mg9k1|VuKe9KR_v*-o1Ju5e!;xoj-W4(| z1Li^1dLg~+cIGrB2uyvr0@&ihy_0T)0_OiTbsk)wo+F|N0NBYKe9Nb#!$Z?d?RMrkeef1&Y~Z%9hD54Ga+RjU>Z&UNp!zC0<{@n_(^mC3$VPzTfBUg$vF}EJ}8pQ-U)6}df>!33;l0< zlw<#WZ_ygComD+D&b@~GpHvUG&i)UsKLo%oDd9{i-0Mg8{Vtc3jlFa0NAs=P#{?*P z|38Oq`hW1h+Z?1kn^>!RoM5O+aN?OgbR9qcabp}VL9jW8%Nnlg7&Q;xrk3j;u*Vik zcsibO5PbX5B4o{`p78sFe>p{X_X^{H^vVO56*WEl_rFL`5BLJyQ~0O&=-PgNnL2h} z4`k@T4F)Ko{QQLrhAT4LSzK^~sjjGoWul^NItsU{ilXkMi}0YhCo9}i6?EB9#$IM4 z>)Vp+)gsI-4uGGJ+_--f@NUIBg_}1~LosV);nkgi48i$uYcO8%O7l@?Sgc6}E=QC_ z7EMW*Z%p7exG25}G-BL9z*aoN*D;l%UW~vBR&P!I?g&36*S!~2i^xr9|0)e8t>@x< zL9S0glE(3!am%+r9SxgsPAsMJ?2P|62p=cRq@3x47DC6Vd4STKl7e(Yjl^KXRM z7YD@-Bv8W@li93{zg~{)`gi1*Sva^x&KE@>qqiQ3WO)RtAn<%kBZ>)w!oC3+>JD_Y z@NHk$i2&er^+uc-fHeiALO3)MP$U1XmK<^A>2iMLZo?yJ=R5lAlQ(aUq$8@GGg+X6 zmsgaRKj25bAG#9B6nsP@Lzczl@9W`@Vo-8j&GHVrY<(9zu{V32CH7fnf;g zQo3U#hHfcQK|lnC?jc7S1?fgYy1VWR|KHzzKQEp)zVb6%*SYpNXYIAuUYpNg1`oFI z`ff3{hq3EPU{l-oTgk7yI+D@$xscC9P>d%8ju-_2iAB|m zTJ-Z>HXImP@!N<8iziOOTKZBNR5%E5ac{)+WVI?e016Xpga4Y+q`A` zPGZclA#tkRkiCcxn+x-w7a=%Hc1M%B7_>YAvQ<9`n55~6?3@=?$JP!#p|K)Jx!IP5t8hh(VDlY=Ngu;S;U+;l~$y%B)BZ(PN7 zt5F2kDvv#s#~;di)+lp2;~4o+HSb3u2^?9N)7#+zf_Zxldv$LGU+n>L0G5lT#>1H@ z{Aqa)5gx|rs$}V8B=dEi^IETNSW}H~_G<=el{irR90vcO1bcoDeXnC{`N}E$(@!mG z_i%xjXa3HG6;g1{Kb)}oy%d1H3a^aM6M!JBx{))yciV3SV!a&QBgrL^490>z%@1H! z@GovwGxXBq6;d8>&Q-t+Gte|tC(iWCl^tr*2|CG)sbJ}rR%X9_ zPvv#kXTTyXowG$=!DyVFHv+Wiz`iPbY)L+hZZVa#AOUv$8h0)1zgkSw{y#E9UpkEQ zP@dYJ8w@aehh}7R3YW*N_GQiNz)Z>U0FwAPgj75p$ubQB^VLMf8g_G)qG`L)dChg{ zJM{3Lze+tJfU+jTXXGRfWlwizAHHNL$flQOB=%)W#CIb?KOzzzqFMPY2%kZYq%lao z?M#zM)&1h~bkh78sK<>%J%jh|&knV?o(sO>Ny+PTtQvj&!3~t-lUaesF-tQiD#exy zoKjZu2T!N}$K4pwxTE>J9EZZE9KhVP+a@H#CH(6=TQrS@+!WuFt&+86+};}7Jq$@f z{=Q0UG%<|yY+Q=%ogOxNOlOrs97$g}++?XV+W5&HA2EvDVHt~Hmsw-K2Rp9BkK&tE zj(F0NeV!`?N6uuAN>LelTa-~MesTu?&_C38u zt0-166uzt)khq6oazwP~(hiHyRF#=oV;U5dg&`J8oAE`7Zg%mPfO3}- z2{h1jcfa%EzR7Gct5vCjr+~au^#0?B#N6FVS&=0PKXz!_M+oeUat=UpZHq>+yPvHoGad| zk6s;F0T9ZOI9zi(6I__T+CCl0W;JmxJdE>K8MnZ^p`z}Ozu`y-1^<@19oSvI;Qlf( zgXG_eu`z=-wDg;3v4!mDx%v+=X2t(U&vB7T>lqxylE`vi5|h3$;3V0C01{HPAb9~o z2fY+VlN1i@?H4!VE5P_<^;dafSK-z(wtvI;Fck|9!d)za!#?=Ga19YmRRUMKk6%Ii z`K!NwH+MK#?h)~#f9fLJda^su|MKO_FHb~8E0H7>()b@feAx2esE_b2S}TML6WL^3 zG56Vm32{E1VI)@!P2EGQ-Y2puE$g7*P@&X zIjt3Et*ASpx5rLQ(`Ca4>4DWig{P%vuMfFCF$LZE`0u@b;!^opUFe zeQPJG?b9ae-M_wZaIl0iTKW?U3ky$Nc1m{obvAWgbxMw!<5d%zr#^oSyhzf0qu{^H zqmXfmxVc^B&3lPHR+tfLorzH&umMJZ^ZI_+?BG8hZqX0^x~nyvBh1#*GB}S~^PR^d zeER>tK!IRL&fRY^z?|n9g?nnXcAudNHy=gj0zS-`@KR{zHK&Xopzl7w_#i0!>~`4) zSHT)g5|zZox-*EMq?)X`AajW+aK_H@Wu5ge?eqPUiU;qXd2yLT3wW8Xj3)EGESRYk`5#~+Jn>*~UGA0Cn(J~$*he0WHHNO4H1oodU} z=Lqf~DZ!Q_cHva1?1;d~V^An!`+(iqPsd-SUxxXLW(z1~)3lb8Xqg%n3R>5kBD%0t z#0)lAz-TNtG=_Y1%%$(sK>yWNye{dc%Wv^y`K! zM1VkFyfeb(3kkyb&$q`L?0Fi3Y4(ks0h83|M`zI~$a|VgKoedcwzwE06wKJ<&5$)%Ji3YhPywE|4V}S9Tt)k0{#O7U_MQoWP&V!tS>E9Vk1LC8pb- zDXNv6lJcCXq_{ZoZf&7&3oX-!*yHmL)pBJZ1!g8E7GQJWHqF{L z#m;VzADH)V@VQ~h=pmgHKVeNjZ@mu}82yq-5v!+W^^8d4!y#ZDkv-3@4r=(g(B4jR z(z^H;lgQ%Uy6p2-+^ujbQ_{n=p|q}cOehBAvDGf>w#DmDjA-Y#vKFqW=;$u)vZi+6 zkVz5?5<6SXbdDmCK9lu3=;5$HBd9I*m%3gcU!ww=L1vFophN1zDUfl&rf<#&L9*h)dBn3(?#NF$M5y8X*L5EV=allE+Vy3>TGnv;(YNcM0m^2Z$ZIN`z z`K&1WuTGQ0JUUF``wS#wND;E81K9SGH;X>RSw-X@f(phAZyv)O@4+JL(*G}SoQ}rt z|H(?0lW>LDBj&TjK&F`m7=!4ZYLmx#nedcNFnMfAJwBc0t<2WVs2>*jAWP6Z1DGq5|G%KV(s!qVSf43dBR@_wHv! z;TKi(RsK^B{KqLBHQ8v&(Ip0D@#`_Pf4=zpa(|XtoaS#CsakWd_~GOvR8qbtmH0XG4>tYL)-^#HQQPs4HETfg`@1ugH zhkXQwprmSe?M>62xC3u5D`PIy#%HExA9cRX1Oq+ckgmr~Xv|P(?O$Qb_#vFv7tQ6)8 zac~`hr!VNL_HQ2K9EH#wkOc09GDdvO@lkEM+-W=@K4())?e>m2kMS;5NQv~<4KewD z`((3lZX^kGFSuX3`?m=;<XNG-8<}! z8Cx_JecgjBo2njolSP(#{$&eB6|t7e3G~lBa3rXp?4~b4({*>vc&hKMJ-R+oKt--r5 zt`%A#Xf!|B&&1S}PsDkS=Ma5>i*`w{=_6sxI_s!ZDx2H@E_G~l%`W3V0`Uiip)7LG3qq;) zMpDPBzsS}0ce}9Ln2V_Gqw@w?Df^zi z!M7Iyq|qK+z8}9!2Fc*Hn>(}yVY)qdDdY?~q&=iNlo|)pxC8E8Q8AJ#Mlc~KCGj}W zUQZgqw($b!zdkl9-X49OqKzKTP|w^bB(B{?PH>NzwYR4mVPW(PK7JBPNZm29C_;O% z<^|YI`=8EoB%S?;rRUb>vt8*;aRWjb)&iURx|t9Ov1&l0uPuLIZ{wktFjHg@ML(B6 zVmu-G%A{k3=wr6BSt@RJ88i}Urmy0Eh<4FwQzTTwT98LWQVDG$ek`m7dqKuffr0zO zYWzJE=Q@vUyP_x#VpZV+Ia(QevX?~iyMr`qV;OJ#i?@$e0|eI61;$b%xCu^tNEmp0 zPOZUx-D3UnUun?&^^t2nwuA;~@K^i=yvUY$w3~J1|=K=tU;Z;14`n5fuSuQ`3{RFY*yZAu; zLkvg|ks(+*+Ck+jDU=^G^7@IFRHLVoLkyO}#PSMKD2$o4zGh2Vzvu=S&VK5Cr84XE zVZ9$l)G(E3e697HEGW;wJkX3gyrsRv$1h1rg?`L4DQoLr?o;8=4z@M2IK;_E6jlEv zk09b>u_D|^1=(_`B;BV8&b$EaK5W$iy9rID5ETsJHM;)<@^Om*JfdNMf;HU`>xBSu zTK>XofCSKBqeib3sbFE5UseX`}VWM;&Al1>U>U?h<))2;|srJ1SKmc+$p{_k_ zJ!f3s*RAFFcFy14cnWy#yh6f$5ZeMsy@H{HZ^V)dBBy4;<9qUo0Jlo0M9>RkP3jl7i?9d*B z4HPIG27vYdXAE`cD$c?rMx+&AZcJT&ejP zcO79Xb<9*#MYELWToiX4Mne;1_2zzGO%ESR>$U4(`hm@;gw1^(u{KC*Kii|*njT)T zt{7DC>eDz-by8vpHd_mw%u}sqFt!9&rq=xZDHpD0S(h|U+t(PGxe38rAuJw09FpOu zK)U`xM}9Y{onlHw2vQQzH8G2RKYJ4|ar%nlCJDZ0%_G^hrR;3)X!Ff&PI_pY<-$uo z(FvE|VAS4$j{l-gzLc`_Jk}69hl9s9i~>6a$%F#$X2LXZw4WgU6@%u!N$~$X>06?w z%4#`U$YW`lL1tY^Wg#kf?&BrQYIq1uKCw(o$W{h?YCsjbJ(^4ssU<9vI+n_b^l~R+ zg6A?#t(j&uGufX_0pAbH z{jfp^g9Zrr1xtrs5QSDYg(B7F#ax1Gs$0ZhPWt^Iw>IF8y*sD2#e!uR5M2RI zMVi{N^1+>U_!I-!W(`_ITzuyHM49Z^Fot*i&P{l%()KF@JxDLIt84d-idL z73H~tgVefn37-1$)E(J&SJU%5fVyjJN6WQQvbBQ@?O=4TE>lqUI*}RuG*6uN=p!gY zP2#Wi*Zmy-T4*Z~uAJ;2eAO1HmM--OvvzJHLw39!k7UCEO8%;1%NR@hvQ+E)PqrF8 zmBtW(ltLNB-#Awe&w>TAx18s+0Sa&l)sZEXS~qmy9Ss3D?hSKy?yMT<)c!y=^Wt~S zp2|FO5m?5*0}mg~9k{}W9w>R1NWJH*zE4RjF1)~OiiINH>}rj9$c1=rN%HbN_um~& zmPHvSER?rTrjX7Jb5~d zmZbaEc-zglM1zpcmtCuH>%I@Hh}p?N(hei(+#?T&N9%-92-309MPPMVXd2$}{BjY(6a{d|Dy52?UDQowkqb@T$7 z;gw7wwvsIV_qbmW$+9B^1CUuv##3X5$@+P#%a<>^0{wx$3;e9Z`JVzjlZ;S~X^t_z9~9?N zbGgjm&-S&ieplC~mroW88oTBH)lOF8>3CFOu;`ks%SEeBh$^VOMJ(cbI{08fPIP)~ zKBelJjGXAi{_$+N^mpy!t&LD-^w+zCr+#OP@0Tivq?7*PL;6GM*C>e$jD(MFDj5@0 zrx_nUOz@dI9Ig&L((j-GnblF5dIiV$x4JX6iS5m}4@G|Z^k{!MNvk)d9bgFpe$_gg zxsK`^Ml#^Qh#E7y&<#=+3bRfGmcZQ3pHs=}m}C|}ZY*L%e#G~ndVT$aZ%-mV2JExi zjpE`Vd)l_6G!t}d%)~h*P`l}5%HEzJ@r+hD&59!}d&uf7p5D~y z^co4trDGxARZFmC9oKKR^mD@S5To)GNzo9RmH2y^+Jeth1s*k4JcA}XnCLC};Z=Vt zd0dd4Mxm`#R6DAi`ZUBd36BH=EuFPjH1RB-Sv?8jF?G7aNUkNhA67yl7I5Vy;D7N} z$H0KSx38}Y=zUv`0_=)>k4`e`_Jj}u2&)phL^CW@t>iPoGS^>kY;BR;6E;iHZT_o6 zRG~xq7HjwC>j56CyL_NGg}V!|bL^Zz!n$N`&$Xx!`p&a##dfr8h*=+-+mcpr7f;tJ zL9-RqC5)V)p4EYfPeI2QEdRmqetB|<#`A>&>5fYr`!8OON)m-;xS=rjpW0uCcdvz8 zu{;xuNdU7@Er?P*qJR^8nNxRtGMztlc}M0XCXxxbud2Tc56CDiDIw1kade~D(p+tT zIVDBT)4`FQ0Y3y?i9el8@+BknP&gB&9YzWYq2_&#j9XLHYO;~R+tal}r(#ok-u-jl zGcEp&dITS%z8fLs+rjPPq4*@kLC6B0_Viker%Z&3o%FzcpFT3!EBuhHdGs>XL8%KZ z1z{(IpHi|JIK8y~73`~33xo(GDPpmJYy<=LRSGS?r77%c)2A z5gO?b=7QGZdV2Gc`ugyx-<2zMBtVMIqA9-4>N@X#`T+5yXYFkB-S$-Vi_up1szvvV z=K3Z_6M9bE%;y4yk5$#y`pm~y@s`(#*Yn2!VvRJqNTypx=+##`WQWIi5VfxaCjUIBc)3^&a z^#lMf;|dpjD+L95kp6{lg2?Z}{>*oP2VO~OsV0I>>;>N()tF|RQDxz`>A}=L(syk1 z)9a&=b@|(>Fab$^KE6~>QF{NQUkAXt*7wi7nyawlW)m9!DQ2X0ZlTtNpcY!+sr=wlbiq57B#)yHHRqeKV&LIY5!T&=f|NZ4&{o zgzga)BW5 zm}C?_tkH8fFDuQihVB%TybPdG0PV1s0-R;v@96I@i{p(aOKUQ>^?tD;eteapY2&5e zzf4~ns*z?&`PQThuj_^^B^=HA>RoM!Qblh|oT@68d@3+4nJmw4PxbB6sGZMlgIFn* zEzWpL><9599>nJpqIa4OH7{wx8lyW()r#9}F*EEu%e z(HV-ofGZ*2PTmLJs15x=W2qq1DKQ$dGgGf7eS7vNuIs+|yx}X?@c+G1-(z91z&3dS z*s8<+I*L8|7h?>C!uu93yqj%ISJSxY&KkIs#Q=JntkXb$JaRk6x6AC}CIwoOEvwPO zpu~j8=d@9e#x%mIFDL*G>1cxeb3DZJ)(JBraAQ_ZXr?eCTXiT2F5r-5UfAXqa zW&Y~?@J~CKtc8l-v>gb3BUC^r_^At15r5M1lz~_5ai9y;{D9~@Pwr=;+`g@Wm2g6; z5&GoA&fi5N1aJ3MDA2U8PF(R_rxIzFAvur?-5r90V`CzneO`7||7u9D3kF5ACs{ zCehvKiJRW})3uqQu~umdv(IxUi_(a>3>x zR-}kvR4eo#kR5UTo?@h5WzZ;@KgbCiJgwxdRJqn~)91>_^SVJE&I}zLrS<#Y@?})6 zMhzDUb$-#3c?d&mlCsP*u;us$+?$mgF?%ah_P%iPWniJh06Mf>@!J^VR7JDS)x1V6 zeS23tVBb=6fU!F73zHF3iGI-NaN2VHUh}+cmtjfK>=55t5VLY}OX!mzB?US@w5%g} zfhSvtk{TVLLVI175;2x^qc}K$-NU}eaUW(<>-5>=zy_!ldJ(fe#RueA&lQu^x;i71 z9;Z2jz8gs=lJ~83n%(-uoptdCzH?F7jvd409-~i3H5I39wXQb6L&s-a?72IPOrZC6 zsTf+XXwMhJ#-cQi@ztm6zpnqR)x7413k>e}Mp&%ld)tNx>^*$itA{4L3q5iKlozQ- zWZ#yYR+gX0X95&nB=O0zu#NVr8+@A8@r|0ikm(|h4PLj`B!#8(NlUlc{!W`01Jfk^ zuMH-JozENm&ph2<|GANQ<*7#40anm4@xeIU9Uwv1CObP#*h~#J4}9myJ;)BNo%P6k zok>Rco`sR(ogorI92NE%=RXjm2L=w?xQa9kgp@{!a6~`9dImYdKT;eU>7T9sp7RMJ zTW$BX>dD&UUT|;u7rTgU66%9bJkgzK=>@U)2|BNx`n6{|Ite8KL0?ubcTr}P#w{Dg z-#Tw^ma1wx*SiBLMQ{mbyuLDl}i=%axoBg=Jdpt>DFTdsI=Ue>xq*#R*v@^aS^i(PE+5QDM zWvq}qwc2>q^A0VkX5vM5_MiXec3Y8k;AlGy~oYr(Q%R%TR-I)`&=fH&1+ zS~O0uD}=sl^5+GXv0T!&C%+S=WmmbzjOA7lM(1e<=Qea(}d`YjUC zt!@zF7sYG7jbc@XMI93WB*zab8r%0h%XqE%oPu1-=G53avBSeNJy2nurulP8u~W1y zfLT9?=bn8}1@1F_$&(3~+b@IU({?h7I=Op&?0H6K0G=Cm+ipAN)}``#%;#{v7V+Ie$L+WB%z1Vkma~V3zvU z^;KF0WA1r0{9QHCJKZ!rLv@pe7Qc&%7<;=7k5RL?EAO6A|HtE1M+wbvZ+^{`((`6( z{9@J6xOOABirJ4!n>#DF{?%|1rKm44W@kS!Qn5*!tu^KO+c3_={m7Lg)&KZxxBup% zXFk_whSTPX@LyVR-N|@!#d0%i+c%$mQoSp|;MHJhyL~f0plIf3wN+SF%FN)Cvh}c zH#%4zhEL6zwV-5zO5Bt;(-AK_+Tyr`%sHt8! zi8~yp`u`cWgcao?ri%xBe^lpF|9E`OK7@JQXfd+0AI-g~YRy}A<29VMlG`HcYPas* zp)}ZXJtwCYuqT5mG%=Yrx||%=P~+gAZ(6Rj%1m>ZsA=3WY%cxQ58PM!p#125HhO)T#O}(R1j3nXH~o-!vB$JQ0;$cVZ`JnYk6$(f z(=Qz=KfmL-A%gf(_Hb>yMAth^2Q;w%m>QnKE<-iG8S-a_h$N@~b*;d(tWBDg^+;he zeOG(7eo3ii3&ys=g>#~08Eg?8TEdHT{qU^Y2I3k>)*ac zoyJ~vXgT|D4}CQ|T>k#`YIQ6)JHV$ce)ndJYPz>}tC$+~#p734z6qtKkwIg*&*dDi z&Fg^K4*=r(Um~=p@Se0rk4dC%E8fpv1uk5c%=JO<=e?QVHe6Q|d7hCI2oI~!bs_u) z*1G2^pHD4OSKXo{<~LI3Q}0)FxjgtP9JdD*r#)(a2Ud>|NT6J&Zewo@#`{dq7ZpWi z=8iwS-<3H%S(4!M_gacU1qQU`-dwH1=jX2$cjiwx#eRO{-AX0EFI5?Hq6u6$P&Zmk zU+vSlJbdrVKYkL(C~TG*@mk1k*J`TNA60LY{`wkvm_HS8J2$7M(Ri@^I*lD>*kl}N zyPM$4U%wTT-Qv-+ccJ!aDqLZcPvE<<>ui_YYP0nGQ~OI@qoe8t_uR~9C=LEZsrw00 zTOxwXqh`-Ng1a;pI3iw>)-t(Wf9*0};B_%nA55o0x5&jb#Ahp=z$$W+j>|pVxUVmF z*aH3ED(z2YGd3HHO(|m=vt#yeT@HH^zcPQ>(8^;>dN@5uXuTdHu-n;9j_|&Wxo`a@ zO*kEMLlDCnBSk&f*d!z!7#imAbj%E7$_p*o46XFJJvEcL=%5xQx;#9+Ig2wvDMCDE z;sS-1lZ6_bOzXYJ8%QWe2hYs+Q`bMIIb@nvJ8BICn!P=)*lJA|RVV0nqdGUhSgooQ z9GF@B0mkhQsUP@)z%8;qSK@d-=_PQ>5a9j$ATfnVNMpL8GJof9nWs~~75EU#yuuv5 zJ&bF;9wzW`Mjg`O&YzwES@qAkpM{B57i#0-ia4)s{5yIPts&Ib-?Z8y>FYc{VpEdq z?uX)_{N?=ntL0F<)H4r~NnXpqN1KW#_7!GES2#L^lDG-nf(ZX`8c$Y<*sW(3yYU%p z3EIvCf-|4Z0EoXfb6J+pNMedy!zHo=!D1_bD#MqTz(3`~tKmo|t&+N04I7zLKi_QlEDop?O`Oq;COlk(6@8d zn{mQYyOvYE-P+{a6JB~t^c%77l29G)w%C}N?VrpXS3-9OrsdEFNeot z?ExWwwTrcOH(6evr9x^zFW_3JsMC{3WP%sYvmfwC)wrpACD+=?`$Sm?=s@ahaT{b) znYm5hViPR1I88ieQ;0b5q~u`sX7qd!l3RWuz4JwKY>C^2(ubfr5YRd93#kO2+Z_ za%65$E)7Y@t<`kBh@1LIBq5+Ls^??Wtd<8pb!t@|9P~@Uh3rLRfGXS%>72l9*6+)~ zR!4YcHC}Ku_VxGktN7pAYCRx*i&;CN-(5y8vw3(M&|fihdl^`I zcBNxx(shSse-^l#AFr*CZ4L#Ve_P4Db^B4R?6)q%6?e9TD%*8g)~U|c6l?Yv>wTvm z7xzK(I`XtYGtfsQ5I+wu|i9^=QZ69(8QSxUOwKxl!dG*V=}Bv^tWRh zSZ=TFiRfGQoTnw|&hw{OTFz2Fu(SXuHGMpN-VLZ(Gaf(raO!x`{Kwv`@!-~QW%q9a zeVmC(Rw$i77<)n$2`TpN0$eFV*C>>t7<~3uvZB;dWq+7i^-I9ws>)uOKb@xDe)WbeNklV@p-sLRCUs@M%9t;1S`10MB`C9T>?%M+Bqkifja?)fR)KYmaQ zBNcOm$(YeTN=hD25wsFVnuCKcN3p2^*W)Yci%L1ggxxB7kY#Ajo$}dZo>VZhBbZ|e z>^ku7>C3(tX zBH-!ASAR%YubyJ|vNQNDaXt~EDtme9vX7s{$amv%z@i|NRq^Jy;rK`P$$Yfn!-9Tg zo&|y0aD2$EQ{81=msXQBG|D!Gw$|zTDy;cFTd{JSn&Hyz$eNg1(ZJav4ZJy!W`#LN3-OU#&EfDxI-%kvygpaXM z1r>XvLXdz~r!+Fu$?~3|#RDS@YJ<$K-YX+-O1If%o=$GDTEr?GKP@LCuw)aqj5le`UvupVg6lvB5I-^dX{oHmf?Lh#?>L0$wc= zzZ@s`k0JoJ$t$gSsjK4x-FxwWf*^wtF!5|7G3Q^sD{&;=n+lFF1!vSs#a51TzA66JMPh{`2?gt&SNriu|6$FF81~cP*#_5rltBI5+*~z~Rq}9Qp zZ-FkaYzb@jLzY+GWEpsZCH-;lgqixF5F=O0JT(w0!3~(l;FIDD+JC|1v4#-<+3VQn z5PbE8sZ2)Yq<35*+o;85eWT)2-fmpjwfkRR=kFzjrsv0eU;Tl4lyF>9L21(cvq44QoE`pc(pp=YDtpyyf{1TQ_5L#5Z_-vMvqDAXTuF zW#{W8o213T=Q9ftKUohp6UJ~!JEF)j1eOknLRR?Rnr8Oa?gul6Qn&?brcWJ zVJfmC1lRYBEg}QEUGJG-^~%C$doZlE`!H-iDuoIDqe?0y@b^N0C4uao+Za!&`Kn{=TIlc05NZSp_@&*%{EYvq#@pdpFtu2-x0kd zhLQ6N1Mb55?6E9(xP~+p_T_~F$>;BA3fjFeCF2eT$N{TsEs)w?QXzHhR9Alw zaluvWSDyfG4>-rV`(++fo#SxxN`S~x+;TFZ2IH97Au=1g*X5EuSul(r(^|V9!{(mV z|31kAzex7@WOfdV-yuf@e(bj2@KV$U@5o%v(_K!-P5as*i5-)#s5E1+Lif;%&ZhgR z#|>f095gH$CSur4MW@hEt0LColxO!d4_itUGgM?6C<|t+%fX0?^af{Ig)E=+7TCuG zkO+DKXukN~c>{ta{ZW#h_J*RjJ##azLevkMX*JA3}77mxcY{z6Ci`zg|cDaK3w|x?(?} zMKBPY{EVhdp;-laAZE3n_CSS^|(aztrO;d*pPz7OHfEL^7GAh>yw*Tte-^a z9&26-A=a7<8p+{fy~z_0?7 zvWf>$x2FdQfzto6e3$MRGBjtKM1iBss5}X3d2!E&hygRR>9aCdAp;pn4|MT+^UO^e z8~;DkGJZlyfDwU4gDL)Ft1ld4b{~ic@Nl{ab*HXhiV}mlD9`2F%--Yxj(Fb5Vn<&w zdB~>(v&P5ZJShjI0=GN9%el@PFUxnJ6JH678P6Sbj#-ErProyPzdd4vJtr*Tgp;!E zI4B4{SruIsTWvJpIuqr%M2T%rt}Rfz0ACaX{+5>ry1=vymn+0#3{E1|Ibz?;w4m~* zyM;P^3VlzDOf0({B<^Ih;&yBOD z@2OZFo*(ug=B^iWe-n(X1jlLEQ-d93QT5#q2Q#B6G2^Z!0#6Vp%T^Zq%l~_P;A2y< zKgPXhxTI;b95br~5veV38t2I6n{h$aI1>35c#5we#s%?UEv=t1G_YPUAr?R5bR@41 zQ!1h60_gI19mEj8$dKDcZfbPmdt~sfms96a$~0cPb?F?R<66tL8ZWpbJJ~b-Iu?}Y zIWzfx4}F)2h;D_d_hSx-EYJ-|lI9DCd5@E-QFjW*hs#lWd`fHm*=H{Mq2uFQCu+Q& ze<_3r5JPllYQzWPWSXwE4|l{Hk0<_U<>;EAJeQL5tFL(*YfF)~c3*Xez^R;I!Uo^r zK_bFnf!^O=wE@{Cs%cIl_Z&|5`r7A`pf01e>wyzE=_lCjVX(mk`0mM3QaA1P?p!pN z9jgYy#6jD3;^krH4!q|K`mEYHc+8$9wvqp#qS9USKl9l&=d-rE0pkelIf0G@>yUt# z%>6imGLMB0doZkC3XJsJU8{{$v>e^BYPemGUt>O-*U1C0{-^# z{PO9|N2bOs(6?L`SH}MrYs%k#j>GnO%H|Xz|J8;MS z=CBp&Fo>zLs!b68Cd#Bd!7z06v-2ZxW_2~vw!Qxe(KSz_{g2XA&iSjsI5Q|%VrGw{ zHWnZx+P<37G`vx8mzh{18u07@fiLmzo&W(NbhR*r{U-~yIrK$eieFvPCljW=H8q;L z7bAW@RQLvQ-QmszoB)B%%$7kvi4JVbnGWkM12GY!+fy=59$kZt-8*5UyR)~GqNu~9 zG-|XPp(b(dFBP!w#mZ6z(d91Jw}dh0=L0vW9Y^W9i5KYdg-s2>rMvu*_!vdU{}P6I z+7r2&RatSdsLMMGf~h?GJt_%#5&E8TK4Pb9=3ronc!cJJp3b>#LP7X_8HWPYrKBlNMiBD9gs|;DBh{_oti2!tn2{LG zlhKc?SBo;Yhcfe-#x*A?`k5aXhJoE~=WNz@@e}30swXmQH&qhVT-$DKu+^;i@_a7S z#!w`~<6(2Eh`r;8*=p%DzoX{p4eeUV`)bPeRVRmL%o_90b96FW6?5g*59ed6JKLz8uOOI2MQ?zvkXRkj;ngdWZDZ1YHsqXUR*JVSbeYSt(ey+ zB{j6WERnzR7~U`t{6%~6y#DX8Yki%?5{;`^iDgWkL%ZEC_bWTs^*a5fMC7;5uFq+< z5-$7i`-op1wY_j<-n!0T3OP-Um`89ulrrBEDUtp*f0hQ7mm>y*@g89 zKaKzq6w0(34rxuZYUa>?d^Svp11$;xoAVemVPh0L>}?MMnX_LzU}fN1$;nb;SS`w~ z23I@_F7bKqRppwS?y`L>s*ztW5efRX`x(te>DNUAGxBC+vx5v#qt9yN{`1yw>%|Td zD5-|=IR`(gqfW)G%XK*7A3~KMeU41xV3PCk)ZGlh$kf`s zG;!aQd>OB6tQ$}Naj2?#FyF({>wB)m?T)SVQyZ=5bdB2v#MEG(e}C#&SRlz@#rL9j zl+EwQg&ghex(=xsGBwM-?m9iPryTh!mT~Ny zSrzWi_C;0xM}B6T$=L(=9MkY|uX(%BlL^gJ=1T?CiFAqohCuhe(VwJ0)dOPebf3jF ztzsGJ=HJM0=C*mdS8dxSNay^ipgi{}jT`uUYVlpM|MOvf$@zkx%;zWVlsG1v@-J&b zwmw!|_eyhSOWmA~o0{2iT3{f7Dp@>q<$7mKQt2-}&__pm_^M1GRme=9;og6%MK{Or zldX@mK~Bfyd+cJVYRRh`e8O({2r9|-7mG=##25hE9i{PGy!5CC)RrTdg$WcvOn@mh z4>7SmD7yKROC_<6#oS@&fAK$oEw+eB1k)yLddG#d^EMPDCq_kqqTkF}wM~W|?Xtk3 zuQ`CGB9S!=43MYBBV$G}iy+8j3k-oU4jqjpR>4XJw$*yRpIHyhWEpV&d&F}51xyTT z%D`~Dpe&k_t}rV;(o&rGYZ7XM6;#Alt)*eoYi0PmtSV@*#{d2F>RfKO%Q$P|al-#I zU|X`Umk;`mspJ(X!gp71rL!$emu-7&~~dH(#Sbuea88W`x);u{%3;EgrA8%6MrVz*uTelisfHm=7yTbs6RpR zIGg8Rj?WJswOQ--Z`7;M&~1(a8*!d-P3!XSos}F6hrzqUkJcRBbM#NDz~lR-(8~LS zHUA9Y7=}^InSwy)73`iDB38<)rcMw!3*MlA;iB<(19?MzLwiGi)0V`4uP&%)CslqA zKEez=iJVdRRDmP&luQHX7wqD;z+jC&!?+^uS)HN0X+x%Jk77^#Vdxz~3+`4pIL{P6 zSFq8TSBpjZx5Dh=1J>+&i?`mb;r!_URRp>m3365vyqz*gxE`C?|Jm1@KHI&rXZ - - - - - - - In the SharpDevelop source code download, you will find a small sample - application in SharpDevelop\samples\AvalonEdit.Sample. - - - - - - - - -

- The Code Project article - - - There is a Code Project article based on the sample application: - - http://www.codeproject.com/KB/edit/AvalonEdit.aspx - http://www.codeproject.com/KB/edit/AvalonEdit.aspx - _blank - - - - However, most of the material from that article has been included in this help file. - - -
- - - - - - \ No newline at end of file diff --git a/AvalonEdit/Documentation/Syntax Highlighting.aml b/AvalonEdit/Documentation/Syntax Highlighting.aml deleted file mode 100644 index 14281af45..000000000 --- a/AvalonEdit/Documentation/Syntax Highlighting.aml +++ /dev/null @@ -1,234 +0,0 @@ - - - - - Probably the most important feature for any text editor is syntax highlighting. - AvalonEdit has a flexible text rendering model, see - . Among the - text rendering extension points is the support for "visual line transformers" that - can change the display of a visual line after it has been constructed by the "visual element generators". - A useful base class implementing IVisualLineTransformer for the purpose of syntax highlighting - is T:ICSharpCode.AvalonEdit.Rendering.DocumentColorizingTransformer. - Take a look at that class' documentation to see - how to write fully custom syntax highlighters. This article only discusses the XML-driven built-in - highlighting engine. - - -
- The highlighting engine - - - The highlighting engine in AvalonEdit is implemented in the class - T:ICSharpCode.AvalonEdit.Highlighting.DocumentHighlighter. - Highlighting is the process of taking a DocumentLine and constructing - a T:ICSharpCode.AvalonEdit.Highlighting.HighlightedLine - instance for it by assigning colors to different sections of the line. - A HighlightedLine is simply a list of - (possibly nested) highlighted text sections. - - The HighlightingColorizer class is the only - link between highlighting and rendering. - It uses a DocumentHighlighter to implement - a line transformer that applies the - highlighting to the visual lines in the rendering process. - - Except for this single call, syntax highlighting is independent from the - rendering namespace. To help with other potential uses of the highlighting - engine, the HighlightedLine class has the - method ToHtml() - to produce syntax highlighted HTML source code. - - The highlighting rules used by the highlighting engine to highlight - the document are described by the following classes: - - - - HighlightingRuleSet - Describes a set of highlighting spans and rules. - HighlightingSpan - A span consists of two regular expressions (Start and End), a color, - and a child ruleset. - The region between Start and End expressions will be assigned the - given color, and inside that span, the rules of the child - ruleset apply. - If the child ruleset also has HighlightingSpans, - they can be nested, allowing highlighting constructs like nested comments or one language - embedded in another. - HighlightingRule - A highlighting rule is a regular expression with a color. - It will highlight matches of the regular expression using that color. - HighlightingColor - A highlighting color isn't just a color: it consists of a foreground - color, font weight and font style. - - - The highlighting engine works by first analyzing the spans: whenever a - begin RegEx matches some text, that span is pushed onto a stack. - Whenever the end RegEx of the current span matches some text, - the span is popped from the stack. - - Each span has a nested rule set associated with it, which is empty - by default. This is why keywords won't be highlighted inside comments: - the span's empty ruleset is active there, so the keyword rule is not applied. - - This feature is also used in the string span: the nested span will match - when a backslash is encountered, and the character following the backslash - will be consumed by the end RegEx of the nested span - (. matches any character). - This ensures that \" does not denote the end of the string span; - but \\" still does. - - What's great about the highlighting engine is that it highlights only - on-demand, works incrementally, and yet usually requires only a - few KB of memory even for large code files. - - On-demand means that when a document is opened, only the lines initially - visible will be highlighted. When the user scrolls down, highlighting will continue - from the point where it stopped the last time. If the user scrolls quickly, - so that the first visible line is far below the last highlighted line, - then the highlighting engine still has to process all the lines in between - – there might be comment starts in them. However, it will only scan that region - for changes in the span stack; highlighting rules will not be tested. - - The stack of active spans is stored at the beginning of every line. - If the user scrolls back up, the lines getting into view can be highlighted - immediately because the necessary context (the span stack) is still available. - - Incrementally means that even if the document is changed, the stored span stacks - will be reused as far as possible. If the user types /*, - that would theoretically cause the whole remainder of the file to become - highlighted in the comment color. - However, because the engine works on-demand, it will only update the span - stacks within the currently visible region and keep a notice - 'the highlighting state is not consistent between line X and line X+1', - where X is the last line in the visible region. - Now, if the user would scroll down, - the highlighting state would be updated and the 'not consistent' notice - would be moved down. But usually, the user will continue typing - and type */ only a few lines later. - Now the highlighting state in the visible region will revert to the normal - 'only the main ruleset is on the stack of active spans'. - When the user now scrolls down below the line with the 'not consistent' marker; - the engine will notice that the old stack and the new stack are identical; - and will remove the 'not consistent' marker. - This allows reusing the stored span stacks cached from before the user typed - /*. - - While the stack of active spans might change frequently inside the lines, - it rarely changes from the beginning of one line to the beginning of the next line. - With most languages, such changes happen only at the start and end of multiline comments. - The highlighting engine exploits this property by storing the list of - span stacks in a special data structure - (T:ICSharpCode.AvalonEdit.Utils.CompressingTreeList`1). - The memory usage of the highlighting engine is linear to the number of span stack changes; - not to the total number of lines. - This allows the highlighting engine to store the span stacks for big code - files using only a tiny amount of memory, especially in languages like - C# where sequences of // or /// - are more popular than /* */ comments. - - -
-
- XML highlighting definitions - - AvalonEdit supports XML syntax highlighting definitions (.xshd files). - In the AvalonEdit source code, you can find the file - ICSharpCode.AvalonEdit\Highlighting\Resources\ModeV2.xsd. - This is an XML schema for the .xshd file format; you can use it to - code completion for .xshd files in XML editors. - - Here is an example highlighting definition for a sub-set of C#: - - - - - - - - - - - " - " - - - - - - - - if - else - - - - - - \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 - - - -]]> - - -
-
- ICSharpCode.TextEditor XML highlighting definitions - - ICSharpCode.TextEditor (the predecessor of AvalonEdit) used - a different version of the XSHD file format. - AvalonEdit detects the difference between the formats using the XML namespace: - The new format uses xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008", - the old format does not use any XML namespace. - - AvalonEdit can load .xshd files written in that old format, and even - automatically convert them to the new format. However, not all - constructs of the old file format are supported by AvalonEdit. - - - -
-
- Programmatically accessing highlighting information - - As described above, the highlighting engine only stores the "span stack" - at the start of each line. This information can be retrieved using the - M:ICSharpCode.AvalonEdit.Highlighting.DocumentHighlighter.GetSpanStack(System.Int32) - method: - s.SpanColor != null && s.SpanColor.Name == "Comment"); -// returns true if the end of line 1 (=start of line 2) is inside a multiline comment]]> - Spans can be identified using their color. For this purpose, named colors should be used in the syntax definition. - - For more detailed results inside lines, the highlighting algorithm - must be executed for that line: - s.Offset <= off && s.Offset+s.Length >= off - && s.Color.Name == "Comment");]]> - - -
- - N:ICSharpCode.AvalonEdit.Highlighting - -
-
\ No newline at end of file diff --git a/AvalonEdit/Documentation/Text Rendering.aml b/AvalonEdit/Documentation/Text Rendering.aml deleted file mode 100644 index 2703277a2..000000000 --- a/AvalonEdit/Documentation/Text Rendering.aml +++ /dev/null @@ -1,178 +0,0 @@ - - - - - This document describes how the TextView class renders the text, and - how you can extend the text rendering process to add new features to the text editor. - - - - The T:ICSharpCode.AvalonEdit.Rendering.TextView - class is the heart of AvalonEdit. - It takes care of getting the document onto the screen. - To do this in an extensible way, the TextView uses its own kind of model: - the T:ICSharpCode.AvalonEdit.Rendering.VisualLine. - Visual lines are created only for the visible part of the document. - - The rendering process looks like this: - - The "element generators", "line transformers" and "background renderers" are - the extension points; it is possible to add custom implementations of them to - the TextView to implement additional features in the editor. - - - -
- Lifetime of VisualLines - - - VisualLines are only created for the visible part of the document. - Lots of actions can trigger their creation, but most commonly the creation will be - caused by the MeasureOverride method of TextView. - When the TextView is measured, it uses the height tree to determine the first - document line in the visible region. Then, it constructs and measures a VisualLine - for that first line, and repeats that with the following lines - until the visible region is filled. - - - The TextView caches VisualLines - when the user scrolls down, only the VisualLines - coming into view are created, the rest is reused. - The VisualLine cache can be manually invalidated using the Redraw method family; - moreover, lots of actions cause automatic invalidation: - any change in the document will invalidate the affected VisualLineschanging the width of the TextView invalidates all VisualLines if word-wrap is enabledchanging any text editor settings (word-wrap, font size, etc.) will invalidate all VisualLinesVisualLines leaving the visible area after scrolling will be disposed - In general, manual invalidation is required only if you have written a text editor extension - (BackgroundRenderer, VisualLineElementGenerator or VisualLineTransformer) that also consumes - external data - in that case, you'll have to notify the text editor that VisualLines need - to be recreated when your external data changes. - - - If external data used by your text editor extension changes, call - M:ICSharpCode.AvalonEdit.Rendering.TextView.Redraw - to invalidate the VisualLine. - - - - Invalidating VisualLines does not cause immediate recreation of the lines! - Rather, the VisualLines are recreated when the text view is next re-measured. - While measurement in WPF normally happens with DispatcherPriority.Render, - the TextView also supports redrawing with a lower priority than that. - For example, normal text insertion causes a redraw at background priority, so that - in case the user types faster than the text view can redraw, there will be only - one redraw for multiple input actions. - - - - The TextView will never return invalid lines to you, but you - may run into the case that the valid visual lines are not available. - - - What happens in this case depends on the method you are calling - - the new visual line might get created automatically, - null could be returned, or you may get a - T:ICSharpCode.AvalonEdit.Rendering.VisualLinesInvalidException. - - - You can call - M:ICSharpCode.AvalonEdit.Rendering.TextView.EnsureVisualLines - to make the text view create all VisualLines in the visible region. - - - -
-
- Building visual line elements - - - As a first step, the VisualLineElementGenerators are used to produce elements. The - room in between the elements returned from the generators is filled with text elements. - Then, the VisualLine assigns the VisualColumn and RelativeTextOffset properties of the line elements. - - - For example, a line contains the text "Hello, World". - The user has enabled "ShowSpaces", so the text editor should show a little dot instead of the space. - In this case, the SingleCharacterElementGenerator, which is responsible for ShowSpaces, will produce - a "SpaceTextElement" for the space character. Because no other generators are interested in the line, - the remaining strings "Hello," and "World" will be represented by VisualLineText elements. - - -
-
- Transforming visual line elements - - - After that, the IVisualLineTransformers are used to modify the produced line elements. Transformers - must not add elements, but they may split existing elements, e.g. to colorize only parts of an - element. When splitting elements (or somehow modifying the elements collection), care must be taken - that the VisualColumn,VisualLine,RelativeTextOffset and DocumentLength properties stay correct. - - - The ColorizingTransformer base class provides helper methods for splitting, so the derived class - can simply say "color this section in that color". - - - The DocumentColorizingTransformer extends the ColorizingTransformer and additionally - allows highlighting on per DocumentLine, coloring text segments (instead of directly - working with visual line elements). - - -
-
- Constructing TextLines - - - After building the visual line elements, the TextLines for the visual line are constructed. - A visual line may result in multiple text lines when word wrapping is active or when special visual - line elements force a line break. - Building text lines: - The text line construction is done by a WPF TextFormatter. - The VisualLineTextSource will take the visual line elements and build WPF TextRuns from it, - while the WPF TextFormatter takes care of word wrapping etc. - VisualLineElements are requested to produce TextRuns for their full or a partial length. - The TextView will take care to measure any inline UI elements in the visual lines. - - -
-
- Rest of the Rendering - - - After the visible region is filled, the TextView updates the heights stored in the document lines to - the measured heights. This way, scrolling takes account for word-wrapping. - The constructed text lines are stored for the arrange and render steps. - Now, finally, the measure step is complete. - - - The WPF arrange step doesn't have much work to do: - It just arranges inline UI elements at their position inside the text. - - - The actual rendering does not happen directly in the TextView, but in its - various layers. - - - These are the predefined layers: - - Background layer: renders the background colors associated with the visual elements - Selection layer: renders the background of the selection - Text layer: renders the TextLines that were constructed during the Measure step. - Starting with AvalonEdit 4.1, the TextLayer uses child elements to draw the text: one DrawingVisual for each VisualLine. - - - Immediately after the text layer, any inline UI elements are placed as if they were separate layers. - - Caret layer: renders a blinking caret - It's also possible to insert new layers into the TextView using the - M:ICSharpCode.AvalonEdit.Rendering.TextView.InsertLayer(System.Windows.UIElement,ICSharpCode.AvalonEdit.Rendering.KnownLayer,ICSharpCode.AvalonEdit.Rendering.LayerInsertionPosition) - method. - This allows adding custom interactive components to the editor - while being in full control of the Z-Order. - - -
- - T:ICSharpCode.AvalonEdit.Rendering.TextView - -
-
\ No newline at end of file diff --git a/AvalonEdit/Documentation/Welcome.aml b/AvalonEdit/Documentation/Welcome.aml deleted file mode 100644 index 243e435bb..000000000 --- a/AvalonEdit/Documentation/Welcome.aml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - AvalonEdit is a WPF-based extensible text editor. - - - While the WPF RichTextBox is quite powerful, you quickly run into its limits - when trying to use it as a code editor: it's hard to write efficient syntax highlighting for it, - and you cannot really implement features like code folding with the standard RichTextBox. - The problem is: the RichTextBox edits a rich document. - In contrast, AvalonEdit simply edits text. - However, AvalonEdit offers lots of possibilities on how the text document is - displayed - so it is much more suitable for a code editor where things like the text color - are not controlled by the user, but instead depend on the text (syntax highlighting). - - - AvalonEdit was written for the SharpDevelop IDE. It replaces our old - Windows Forms-based text editor (ICSharpCode.TextEditor). - - - - - -
- Usage - - The main class of the editor is T:ICSharpCode.AvalonEdit.TextEditor. - You can use it similar to a normal WPF TextBox: - -]]> - -
- -
- System requirements - - There are two versions of AvalonEdit - the normal one requires - - .NET Framework 4.0 - http://msdn.microsoft.com/en-us/library/w0x726c2.aspx - _blank - or higher; but we also offer a modified version for .NET 3.5 SP1. - For compiling AvalonEdit, you will need a C# 4.0 compiler (SharpDevelop 4.x or Visual Studio 2010). - - AvalonEdit requires FullTrust and will not run as XBAP. - -
- - - T:ICSharpCode.AvalonEdit.TextEditor - - www.avalonedit.net - http://www.avalonedit.net - _blank - - - www.icsharpcode.net - http://www.icsharpcode.net - _blank - - -
-
\ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/ChangeTrackingTest.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/ChangeTrackingTest.cs deleted file mode 100644 index fc0295ea2..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/ChangeTrackingTest.cs +++ /dev/null @@ -1,79 +0,0 @@ -// 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; -#if NREFACTORY -using ICSharpCode.NRefactory.Editor; -#endif -using NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Document -{ - [TestFixture] - public class ChangeTrackingTest - { - [Test] - public void NoChanges() - { - TextDocument document = new TextDocument("initial text"); - ITextSource snapshot1 = document.CreateSnapshot(); - ITextSource snapshot2 = document.CreateSnapshot(); - Assert.AreEqual(0, snapshot1.Version.CompareAge(snapshot2.Version)); - Assert.AreEqual(0, snapshot1.Version.GetChangesTo(snapshot2.Version).Count()); - Assert.AreEqual(document.Text, snapshot1.Text); - Assert.AreEqual(document.Text, snapshot2.Text); - } - - [Test] - public void ForwardChanges() - { - TextDocument document = new TextDocument("initial text"); - ITextSource snapshot1 = document.CreateSnapshot(); - document.Replace(0, 7, "nw"); - document.Insert(1, "e"); - ITextSource snapshot2 = document.CreateSnapshot(); - Assert.AreEqual(-1, snapshot1.Version.CompareAge(snapshot2.Version)); - TextChangeEventArgs[] arr = snapshot1.Version.GetChangesTo(snapshot2.Version).ToArray(); - Assert.AreEqual(2, arr.Length); - Assert.AreEqual("nw", arr[0].InsertedText.Text); - Assert.AreEqual("e", arr[1].InsertedText.Text); - - Assert.AreEqual("initial text", snapshot1.Text); - Assert.AreEqual("new text", snapshot2.Text); - } - - [Test] - public void BackwardChanges() - { - TextDocument document = new TextDocument("initial text"); - ITextSource snapshot1 = document.CreateSnapshot(); - document.Replace(0, 7, "nw"); - document.Insert(1, "e"); - ITextSource snapshot2 = document.CreateSnapshot(); - Assert.AreEqual(1, snapshot2.Version.CompareAge(snapshot1.Version)); - TextChangeEventArgs[] arr = snapshot2.Version.GetChangesTo(snapshot1.Version).ToArray(); - Assert.AreEqual(2, arr.Length); - Assert.AreEqual("", arr[0].InsertedText.Text); - Assert.AreEqual("initial", arr[1].InsertedText.Text); - - Assert.AreEqual("initial text", snapshot1.Text); - Assert.AreEqual("new text", snapshot2.Text); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/CollapsingTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/CollapsingTests.cs deleted file mode 100644 index 629295e8a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/CollapsingTests.cs +++ /dev/null @@ -1,170 +0,0 @@ -// 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; -using NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Document -{ - [TestFixture] - public class CollapsingTests - { - TextDocument document; - HeightTree heightTree; - - [SetUp] - public void Setup() - { - document = new TextDocument(); - document.Text = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10"; - heightTree = new HeightTree(document, 10); - foreach (DocumentLine line in document.Lines) { - heightTree.SetHeight(line, line.LineNumber); - } - } - - CollapsedLineSection SimpleCheck(int from, int to) - { - CollapsedLineSection sec1 = heightTree.CollapseText(document.GetLineByNumber(from), document.GetLineByNumber(to)); - for (int i = 1; i < from; i++) { - Assert.IsFalse(heightTree.GetIsCollapsed(i)); - } - for (int i = from; i <= to; i++) { - Assert.IsTrue(heightTree.GetIsCollapsed(i)); - } - for (int i = to + 1; i <= 10; i++) { - Assert.IsFalse(heightTree.GetIsCollapsed(i)); - } - CheckHeights(); - return sec1; - } - - [Test] - public void SimpleCheck() - { - SimpleCheck(4, 6); - } - - [Test] - public void SimpleUncollapse() - { - CollapsedLineSection sec1 = heightTree.CollapseText(document.GetLineByNumber(4), document.GetLineByNumber(6)); - sec1.Uncollapse(); - for (int i = 1; i <= 10; i++) { - Assert.IsFalse(heightTree.GetIsCollapsed(i)); - } - CheckHeights(); - } - - [Test] - public void FullCheck() - { - for (int from = 1; from <= 10; from++) { - for (int to = from; to <= 10; to++) { - try { - SimpleCheck(from, to).Uncollapse(); - for (int i = 1; i <= 10; i++) { - Assert.IsFalse(heightTree.GetIsCollapsed(i)); - } - CheckHeights(); - } catch { - Console.WriteLine("from = " + from + ", to = " + to); - throw; - } - } - } - } - - [Test] - public void InsertInCollapsedSection() - { - CollapsedLineSection sec1 = heightTree.CollapseText(document.GetLineByNumber(4), document.GetLineByNumber(6)); - document.Insert(document.GetLineByNumber(5).Offset, "a\nb\nc"); - for (int i = 1; i < 4; i++) { - Assert.IsFalse(heightTree.GetIsCollapsed(i)); - } - for (int i = 4; i <= 8; i++) { - Assert.IsTrue(heightTree.GetIsCollapsed(i)); - } - for (int i = 9; i <= 12; i++) { - Assert.IsFalse(heightTree.GetIsCollapsed(i)); - } - CheckHeights(); - } - - [Test] - public void RemoveInCollapsedSection() - { - CollapsedLineSection sec1 = heightTree.CollapseText(document.GetLineByNumber(3), document.GetLineByNumber(7)); - int line4Offset = document.GetLineByNumber(4).Offset; - int line6Offset = document.GetLineByNumber(6).Offset; - document.Remove(line4Offset, line6Offset - line4Offset); - for (int i = 1; i < 3; i++) { - Assert.IsFalse(heightTree.GetIsCollapsed(i)); - } - for (int i = 3; i <= 5; i++) { - Assert.IsTrue(heightTree.GetIsCollapsed(i)); - } - for (int i = 6; i <= 8; i++) { - Assert.IsFalse(heightTree.GetIsCollapsed(i)); - } - CheckHeights(); - } - - [Test] - public void RemoveEndOfCollapsedSection() - { - CollapsedLineSection sec1 = heightTree.CollapseText(document.GetLineByNumber(3), document.GetLineByNumber(6)); - int line5Offset = document.GetLineByNumber(5).Offset; - int line8Offset = document.GetLineByNumber(8).Offset; - document.Remove(line5Offset, line8Offset - line5Offset); - for (int i = 1; i < 3; i++) { - Assert.IsFalse(heightTree.GetIsCollapsed(i)); - } - for (int i = 3; i <= 5; i++) { - Assert.IsTrue(heightTree.GetIsCollapsed(i)); - } - for (int i = 6; i <= 7; i++) { - Assert.IsFalse(heightTree.GetIsCollapsed(i)); - } - CheckHeights(); - } - - [Test] - public void RemoveCollapsedSection() - { - CollapsedLineSection sec1 = heightTree.CollapseText(document.GetLineByNumber(3), document.GetLineByNumber(3)); - int line3Offset = document.GetLineByNumber(3).Offset; - document.Remove(line3Offset - 1, 1); - for (int i = 1; i <= 9; i++) { - Assert.IsFalse(heightTree.GetIsCollapsed(i)); - } - CheckHeights(); - Assert.AreSame(null, sec1.Start); - Assert.AreSame(null, sec1.End); - // section gets uncollapsed when it is removed - Assert.IsFalse(sec1.IsCollapsed); - } - - void CheckHeights() - { - HeightTests.CheckHeights(document, heightTree); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/HeightTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/HeightTests.cs deleted file mode 100644 index b39e914f3..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/HeightTests.cs +++ /dev/null @@ -1,91 +0,0 @@ -// 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.Rendering; -using NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Document -{ - [TestFixture] - public class HeightTests - { - TextDocument document; - HeightTree heightTree; - - [SetUp] - public void Setup() - { - document = new TextDocument(); - document.Text = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10"; - heightTree = new HeightTree(document, 10); - foreach (DocumentLine line in document.Lines) { - heightTree.SetHeight(line, line.LineNumber); - } - } - - [Test] - public void SimpleCheck() - { - CheckHeights(); - } - - [Test] - public void TestLinesRemoved() - { - document.Remove(5, 4); - CheckHeights(); - } - - [Test] - public void TestHeightChanged() - { - heightTree.SetHeight(document.GetLineByNumber(4), 100); - CheckHeights(); - } - - [Test] - public void TestLinesInserted() - { - document.Insert(0, "x\ny\n"); - heightTree.SetHeight(document.Lines[0], 100); - heightTree.SetHeight(document.Lines[1], 1000); - heightTree.SetHeight(document.Lines[2], 10000); - CheckHeights(); - } - - void CheckHeights() - { - CheckHeights(document, heightTree); - } - - internal static void CheckHeights(TextDocument document, HeightTree heightTree) - { - double[] heights = document.Lines.Select(l => heightTree.GetIsCollapsed(l.LineNumber) ? 0 : heightTree.GetHeight(l)).ToArray(); - double[] visualPositions = new double[document.LineCount+1]; - for (int i = 0; i < heights.Length; i++) { - visualPositions[i+1]=visualPositions[i]+heights[i]; - } - foreach (DocumentLine ls in document.Lines) { - Assert.AreEqual(visualPositions[ls.LineNumber-1], heightTree.GetVisualPosition(ls)); - } - Assert.AreEqual(visualPositions[document.LineCount], heightTree.TotalHeight); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/LineManagerTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/LineManagerTests.cs deleted file mode 100644 index e209ffc58..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/LineManagerTests.cs +++ /dev/null @@ -1,553 +0,0 @@ -// 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 NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Document -{ - [TestFixture] - public class LineManagerTests - { - TextDocument document; - - [SetUp] - public void SetUp() - { - document = new TextDocument(); - } - - [Test] - public void CheckEmptyDocument() - { - Assert.AreEqual("", document.Text); - Assert.AreEqual(0, document.TextLength); - Assert.AreEqual(1, document.LineCount); - } - - [Test] - public void CheckClearingDocument() - { - document.Text = "Hello,\nWorld!"; - Assert.AreEqual(2, document.LineCount); - var oldLines = document.Lines.ToArray(); - document.Text = ""; - Assert.AreEqual("", document.Text); - Assert.AreEqual(0, document.TextLength); - Assert.AreEqual(1, document.LineCount); - Assert.AreSame(oldLines[0], document.Lines.Single()); - Assert.IsFalse(oldLines[0].IsDeleted); - Assert.IsTrue(oldLines[1].IsDeleted); - Assert.IsNull(oldLines[0].NextLine); - Assert.IsNull(oldLines[1].PreviousLine); - } - - [Test] - public void CheckGetLineInEmptyDocument() - { - Assert.AreEqual(1, document.Lines.Count); - List lines = new List(document.Lines); - Assert.AreEqual(1, lines.Count); - DocumentLine line = document.Lines[0]; - Assert.AreSame(line, lines[0]); - Assert.AreSame(line, document.GetLineByNumber(1)); - Assert.AreSame(line, document.GetLineByOffset(0)); - } - - [Test] - public void CheckLineSegmentInEmptyDocument() - { - DocumentLine line = document.GetLineByNumber(1); - Assert.AreEqual(1, line.LineNumber); - Assert.AreEqual(0, line.Offset); - Assert.IsFalse(line.IsDeleted); - Assert.AreEqual(0, line.Length); - Assert.AreEqual(0, line.TotalLength); - Assert.AreEqual(0, line.DelimiterLength); - } - - [Test] - public void LineIndexOfTest() - { - DocumentLine line = document.GetLineByNumber(1); - Assert.AreEqual(0, document.Lines.IndexOf(line)); - DocumentLine lineFromOtherDocument = new TextDocument().GetLineByNumber(1); - Assert.AreEqual(-1, document.Lines.IndexOf(lineFromOtherDocument)); - document.Text = "a\nb\nc"; - DocumentLine middleLine = document.GetLineByNumber(2); - Assert.AreEqual(1, document.Lines.IndexOf(middleLine)); - document.Remove(1, 3); - Assert.IsTrue(middleLine.IsDeleted); - Assert.AreEqual(-1, document.Lines.IndexOf(middleLine)); - } - - [Test] - public void InsertInEmptyDocument() - { - document.Insert(0, "a"); - Assert.AreEqual(document.LineCount, 1); - DocumentLine line = document.GetLineByNumber(1); - Assert.AreEqual("a", document.GetText(line)); - } - - [Test] - public void SetText() - { - document.Text = "a"; - Assert.AreEqual(document.LineCount, 1); - DocumentLine line = document.GetLineByNumber(1); - Assert.AreEqual("a", document.GetText(line)); - } - - [Test] - public void InsertNothing() - { - document.Insert(0, ""); - Assert.AreEqual(document.LineCount, 1); - Assert.AreEqual(document.TextLength, 0); - } - - [Test, ExpectedException(typeof(ArgumentNullException))] - public void InsertNull() - { - document.Insert(0, (string)null); - } - - [Test, ExpectedException(typeof(ArgumentNullException))] - public void SetTextNull() - { - document.Text = null; - } - - [Test] - public void RemoveNothing() - { - document.Remove(0, 0); - Assert.AreEqual(document.LineCount, 1); - Assert.AreEqual(document.TextLength, 0); - } - - [Test, ExpectedException(typeof(ArgumentOutOfRangeException))] - public void GetCharAt0EmptyDocument() - { - document.GetCharAt(0); - } - - [Test, ExpectedException(typeof(ArgumentOutOfRangeException))] - public void GetCharAtNegativeOffset() - { - document.Text = "a\nb"; - document.GetCharAt(-1); - } - - [Test, ExpectedException(typeof(ArgumentOutOfRangeException))] - public void GetCharAtEndOffset() - { - document.Text = "a\nb"; - document.GetCharAt(document.TextLength); - } - - [Test, ExpectedException(typeof(ArgumentOutOfRangeException))] - public void InsertAtNegativeOffset() - { - document.Text = "a\nb"; - document.Insert(-1, "text"); - } - - [Test, ExpectedException(typeof(ArgumentOutOfRangeException))] - public void InsertAfterEndOffset() - { - document.Text = "a\nb"; - document.Insert(4, "text"); - } - - [Test, ExpectedException(typeof(ArgumentOutOfRangeException))] - public void RemoveNegativeAmount() - { - document.Text = "abcd"; - document.Remove(2, -1); - } - - [Test, ExpectedException(typeof(ArgumentOutOfRangeException))] - public void RemoveTooMuch() - { - document.Text = "abcd"; - document.Remove(2, 10); - } - - [Test, ExpectedException(typeof(ArgumentOutOfRangeException))] - public void GetLineByNumberNegative() - { - document.Text = "a\nb"; - document.GetLineByNumber(-1); - } - - [Test, ExpectedException(typeof(ArgumentOutOfRangeException))] - public void GetLineByNumberTooHigh() - { - document.Text = "a\nb"; - document.GetLineByNumber(3); - } - - [Test, ExpectedException(typeof(ArgumentOutOfRangeException))] - public void GetLineByOffsetNegative() - { - document.Text = "a\nb"; - document.GetLineByOffset(-1); - } - - - [Test, ExpectedException(typeof(ArgumentOutOfRangeException))] - public void GetLineByOffsetToHigh() - { - document.Text = "a\nb"; - document.GetLineByOffset(10); - } - - [Test] - public void InsertAtEndOffset() - { - document.Text = "a\nb"; - CheckDocumentLines("a", - "b"); - document.Insert(3, "text"); - CheckDocumentLines("a", - "btext"); - } - - [Test] - public void GetCharAt() - { - document.Text = "a\r\nb"; - Assert.AreEqual('a', document.GetCharAt(0)); - Assert.AreEqual('\r', document.GetCharAt(1)); - Assert.AreEqual('\n', document.GetCharAt(2)); - Assert.AreEqual('b', document.GetCharAt(3)); - } - - [Test] - public void CheckMixedNewLineTest() - { - const string mixedNewlineText = "line 1\nline 2\r\nline 3\rline 4"; - document.Text = mixedNewlineText; - Assert.AreEqual(mixedNewlineText, document.Text); - Assert.AreEqual(4, document.LineCount); - for (int i = 1; i < 4; i++) { - DocumentLine line = document.GetLineByNumber(i); - Assert.AreEqual(i, line.LineNumber); - Assert.AreEqual("line " + i, document.GetText(line)); - } - Assert.AreEqual(1, document.GetLineByNumber(1).DelimiterLength); - Assert.AreEqual(2, document.GetLineByNumber(2).DelimiterLength); - Assert.AreEqual(1, document.GetLineByNumber(3).DelimiterLength); - Assert.AreEqual(0, document.GetLineByNumber(4).DelimiterLength); - } - - [Test] - public void LfCrIsTwoNewLinesTest() - { - document.Text = "a\n\rb"; - Assert.AreEqual("a\n\rb", document.Text); - CheckDocumentLines("a", - "", - "b"); - } - - [Test] - public void RemoveFirstPartOfDelimiter() - { - document.Text = "a\r\nb"; - document.Remove(1, 1); - Assert.AreEqual("a\nb", document.Text); - CheckDocumentLines("a", - "b"); - } - - [Test] - public void RemoveLineContentAndJoinDelimiters() - { - document.Text = "a\rb\nc"; - document.Remove(2, 1); - Assert.AreEqual("a\r\nc", document.Text); - CheckDocumentLines("a", - "c"); - } - - [Test] - public void RemoveLineContentAndJoinDelimiters2() - { - document.Text = "a\rb\nc\nd"; - document.Remove(2, 3); - Assert.AreEqual("a\r\nd", document.Text); - CheckDocumentLines("a", - "d"); - } - - [Test] - public void RemoveLineContentAndJoinDelimiters3() - { - document.Text = "a\rb\r\nc"; - document.Remove(2, 2); - Assert.AreEqual("a\r\nc", document.Text); - CheckDocumentLines("a", - "c"); - } - - [Test] - public void RemoveLineContentAndJoinNonMatchingDelimiters() - { - document.Text = "a\nb\nc"; - document.Remove(2, 1); - Assert.AreEqual("a\n\nc", document.Text); - CheckDocumentLines("a", - "", - "c"); - } - - [Test] - public void RemoveLineContentAndJoinNonMatchingDelimiters2() - { - document.Text = "a\nb\rc"; - document.Remove(2, 1); - Assert.AreEqual("a\n\rc", document.Text); - CheckDocumentLines("a", - "", - "c"); - } - - [Test] - public void RemoveMultilineUpToFirstPartOfDelimiter() - { - document.Text = "0\n1\r\n2"; - document.Remove(1, 3); - Assert.AreEqual("0\n2", document.Text); - CheckDocumentLines("0", - "2"); - } - - [Test] - public void RemoveSecondPartOfDelimiter() - { - document.Text = "a\r\nb"; - document.Remove(2, 1); - Assert.AreEqual("a\rb", document.Text); - CheckDocumentLines("a", - "b"); - } - - [Test] - public void RemoveFromSecondPartOfDelimiter() - { - document.Text = "a\r\nb\nc"; - document.Remove(2, 3); - Assert.AreEqual("a\rc", document.Text); - CheckDocumentLines("a", - "c"); - } - - [Test] - public void RemoveFromSecondPartOfDelimiterToDocumentEnd() - { - document.Text = "a\r\nb"; - document.Remove(2, 2); - Assert.AreEqual("a\r", document.Text); - CheckDocumentLines("a", - ""); - } - - [Test] - public void RemoveUpToMatchingDelimiter1() - { - document.Text = "a\r\nb\nc"; - document.Remove(2, 2); - Assert.AreEqual("a\r\nc", document.Text); - CheckDocumentLines("a", - "c"); - } - - [Test] - public void RemoveUpToMatchingDelimiter2() - { - document.Text = "a\r\nb\r\nc"; - document.Remove(2, 3); - Assert.AreEqual("a\r\nc", document.Text); - CheckDocumentLines("a", - "c"); - } - - [Test] - public void RemoveUpToNonMatchingDelimiter() - { - document.Text = "a\r\nb\rc"; - document.Remove(2, 2); - Assert.AreEqual("a\r\rc", document.Text); - CheckDocumentLines("a", - "", - "c"); - } - - [Test] - public void RemoveTwoCharDelimiter() - { - document.Text = "a\r\nb"; - document.Remove(1, 2); - Assert.AreEqual("ab", document.Text); - CheckDocumentLines("ab"); - } - - [Test] - public void RemoveOneCharDelimiter() - { - document.Text = "a\nb"; - document.Remove(1, 1); - Assert.AreEqual("ab", document.Text); - CheckDocumentLines("ab"); - } - - void CheckDocumentLines(params string[] lines) - { - Assert.AreEqual(lines.Length, document.LineCount, "LineCount"); - for (int i = 0; i < lines.Length; i++) { - Assert.AreEqual(lines[i], document.GetText(document.Lines[i]), "Text of line " + (i + 1)); - } - } - - [Test] - public void FixUpFirstPartOfDelimiter() - { - document.Text = "a\n\nb"; - document.Replace(1, 1, "\r"); - Assert.AreEqual("a\r\nb", document.Text); - CheckDocumentLines("a", - "b"); - } - - [Test] - public void FixUpSecondPartOfDelimiter() - { - document.Text = "a\r\rb"; - document.Replace(2, 1, "\n"); - Assert.AreEqual("a\r\nb", document.Text); - CheckDocumentLines("a", - "b"); - } - - [Test] - public void InsertInsideDelimiter() - { - document.Text = "a\r\nc"; - document.Insert(2, "b"); - Assert.AreEqual("a\rb\nc", document.Text); - CheckDocumentLines("a", - "b", - "c"); - } - - [Test] - public void InsertInsideDelimiter2() - { - document.Text = "a\r\nd"; - document.Insert(2, "b\nc"); - Assert.AreEqual("a\rb\nc\nd", document.Text); - CheckDocumentLines("a", - "b", - "c", - "d"); - } - - [Test] - public void InsertInsideDelimiter3() - { - document.Text = "a\r\nc"; - document.Insert(2, "b\r"); - Assert.AreEqual("a\rb\r\nc", document.Text); - CheckDocumentLines("a", - "b", - "c"); - } - - [Test] - public void ExtendDelimiter1() - { - document.Text = "a\nc"; - document.Insert(1, "b\r"); - Assert.AreEqual("ab\r\nc", document.Text); - CheckDocumentLines("ab", - "c"); - } - - [Test] - public void ExtendDelimiter2() - { - document.Text = "a\rc"; - document.Insert(2, "\nb"); - Assert.AreEqual("a\r\nbc", document.Text); - CheckDocumentLines("a", - "bc"); - } - - [Test] - public void ReplaceLineContentBetweenMatchingDelimiters() - { - document.Text = "a\rb\nc"; - document.Replace(2, 1, "x"); - Assert.AreEqual("a\rx\nc", document.Text); - CheckDocumentLines("a", - "x", - "c"); - } - - [Test] - public void GetOffset() - { - document.Text = "Hello,\nWorld!"; - Assert.AreEqual(0, document.GetOffset(1, 1)); - Assert.AreEqual(1, document.GetOffset(1, 2)); - Assert.AreEqual(5, document.GetOffset(1, 6)); - Assert.AreEqual(6, document.GetOffset(1, 7)); - Assert.AreEqual(7, document.GetOffset(2, 1)); - Assert.AreEqual(8, document.GetOffset(2, 2)); - Assert.AreEqual(12, document.GetOffset(2, 6)); - Assert.AreEqual(13, document.GetOffset(2, 7)); - } - - [Test] - public void GetOffsetIgnoreNegativeColumns() - { - document.Text = "Hello,\nWorld!"; - Assert.AreEqual(0, document.GetOffset(1, -1)); - Assert.AreEqual(0, document.GetOffset(1, -100)); - Assert.AreEqual(0, document.GetOffset(1, 0)); - Assert.AreEqual(7, document.GetOffset(2, -1)); - Assert.AreEqual(7, document.GetOffset(2, -100)); - Assert.AreEqual(7, document.GetOffset(2, 0)); - } - - [Test] - public void GetOffsetIgnoreTooHighColumns() - { - document.Text = "Hello,\nWorld!"; - Assert.AreEqual(6, document.GetOffset(1, 8)); - Assert.AreEqual(6, document.GetOffset(1, 100)); - Assert.AreEqual(13, document.GetOffset(2, 8)); - Assert.AreEqual(13, document.GetOffset(2, 100)); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/RandomizedLineManagerTest.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/RandomizedLineManagerTest.cs deleted file mode 100644 index c5471712c..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/RandomizedLineManagerTest.cs +++ /dev/null @@ -1,183 +0,0 @@ -// 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.Rendering; -using NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Document -{ - /// - /// A randomized test for the line manager. - /// - [TestFixture] - public class RandomizedLineManagerTest - { - TextDocument document; - Random rnd; - - [TestFixtureSetUp] - public void FixtureSetup() - { - int seed = Environment.TickCount; - Console.WriteLine("RandomizedLineManagerTest Seed: " + seed); - rnd = new Random(seed); - } - - [SetUp] - public void Setup() - { - document = new TextDocument(); - } - - [Test] - public void ShortReplacements() - { - char[] chars = { 'a', 'b', '\r', '\n' }; - char[] buffer = new char[20]; - for (int i = 0; i < 2500; i++) { - int offset = rnd.Next(0, document.TextLength); - int length = rnd.Next(0, document.TextLength - offset); - int newTextLength = rnd.Next(0, 20); - for (int j = 0; j < newTextLength; j++) { - buffer[j] = chars[rnd.Next(0, chars.Length)]; - } - - document.Replace(offset, length, new string(buffer, 0, newTextLength)); - CheckLines(); - } - } - - [Test] - public void LargeReplacements() - { - char[] chars = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', '\r', '\n' }; - char[] buffer = new char[1000]; - for (int i = 0; i < 20; i++) { - int offset = rnd.Next(0, document.TextLength); - int length = rnd.Next(0, (document.TextLength - offset) / 4); - int newTextLength = rnd.Next(0, 1000); - for (int j = 0; j < newTextLength; j++) { - buffer[j] = chars[rnd.Next(0, chars.Length)]; - } - - string newText = new string(buffer, 0, newTextLength); - string expectedText = document.Text.Remove(offset, length).Insert(offset, newText); - document.Replace(offset, length, newText); - Assert.AreEqual(expectedText, document.Text); - CheckLines(); - } - } - - void CheckLines() - { - string text = document.Text; - int lineNumber = 1; - int lineStart = 0; - for (int i = 0; i < text.Length; i++) { - char c = text[i]; - if (c == '\r' && i + 1 < text.Length && text[i + 1] == '\n') { - DocumentLine line = document.GetLineByNumber(lineNumber); - Assert.AreEqual(lineNumber, line.LineNumber); - Assert.AreEqual(2, line.DelimiterLength); - Assert.AreEqual(lineStart, line.Offset); - Assert.AreEqual(i - lineStart, line.Length); - i++; // consume \n - lineNumber++; - lineStart = i+1; - } else if (c == '\r' || c == '\n') { - DocumentLine line = document.GetLineByNumber(lineNumber); - Assert.AreEqual(lineNumber, line.LineNumber); - Assert.AreEqual(1, line.DelimiterLength); - Assert.AreEqual(lineStart, line.Offset); - Assert.AreEqual(i - lineStart, line.Length); - lineNumber++; - lineStart = i+1; - } - } - Assert.AreEqual(lineNumber, document.LineCount); - } - - [Test] - public void CollapsingTest() - { - char[] chars = { 'a', 'b', '\r', '\n' }; - char[] buffer = new char[20]; - HeightTree heightTree = new HeightTree(document, 10); - List collapsedSections = new List(); - for (int i = 0; i < 2500; i++) { -// Console.WriteLine("Iteration " + i); -// Console.WriteLine(heightTree.GetTreeAsString()); -// foreach (CollapsedLineSection cs in collapsedSections) { -// Console.WriteLine(cs); -// } - - switch (rnd.Next(0, 10)) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - int offset = rnd.Next(0, document.TextLength); - int length = rnd.Next(0, document.TextLength - offset); - int newTextLength = rnd.Next(0, 20); - for (int j = 0; j < newTextLength; j++) { - buffer[j] = chars[rnd.Next(0, chars.Length)]; - } - - document.Replace(offset, length, new string(buffer, 0, newTextLength)); - break; - case 6: - case 7: - int startLine = rnd.Next(1, document.LineCount + 1); - int endLine = rnd.Next(startLine, document.LineCount + 1); - collapsedSections.Add(heightTree.CollapseText(document.GetLineByNumber(startLine), document.GetLineByNumber(endLine))); - break; - case 8: - if (collapsedSections.Count > 0) { - CollapsedLineSection cs = collapsedSections[rnd.Next(0, collapsedSections.Count)]; - // unless the text section containing the CollapsedSection was deleted: - if (cs.Start != null) { - cs.Uncollapse(); - } - collapsedSections.Remove(cs); - } - break; - case 9: - foreach (DocumentLine ls in document.Lines) { - heightTree.SetHeight(ls, ls.LineNumber); - } - break; - } - var treeSections = new HashSet(heightTree.GetAllCollapsedSections()); - int expectedCount = 0; - foreach (CollapsedLineSection cs in collapsedSections) { - if (cs.Start != null) { - expectedCount++; - Assert.IsTrue(treeSections.Contains(cs)); - } - } - Assert.AreEqual(expectedCount, treeSections.Count); - CheckLines(); - HeightTests.CheckHeights(document, heightTree); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/TextAnchorTest.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/TextAnchorTest.cs deleted file mode 100644 index 1e481dc54..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/TextAnchorTest.cs +++ /dev/null @@ -1,331 +0,0 @@ -// 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; -#endif -using NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Document -{ - [TestFixture] - public class TextAnchorTest - { - TextDocument document; - - [SetUp] - public void SetUp() - { - document = new TextDocument(); - } - - [Test] - public void AnchorInEmptyDocument() - { - TextAnchor a1 = document.CreateAnchor(0); - TextAnchor a2 = document.CreateAnchor(0); - a1.MovementType = AnchorMovementType.BeforeInsertion; - a2.MovementType = AnchorMovementType.AfterInsertion; - Assert.AreEqual(0, a1.Offset); - Assert.AreEqual(0, a2.Offset); - document.Insert(0, "x"); - Assert.AreEqual(0, a1.Offset); - Assert.AreEqual(1, a2.Offset); - } - - [Test] - public void AnchorsSurviveDeletion() - { - document.Text = new string(' ', 10); - TextAnchor[] a1 = new TextAnchor[11]; - TextAnchor[] a2 = new TextAnchor[11]; - for (int i = 0; i < 11; i++) { - //Console.WriteLine("Insert first at i = " + i); - a1[i] = document.CreateAnchor(i); - a1[i].SurviveDeletion = true; - //Console.WriteLine(document.GetTextAnchorTreeAsString()); - //Console.WriteLine("Insert second at i = " + i); - a2[i] = document.CreateAnchor(i); - a2[i].SurviveDeletion = false; - //Console.WriteLine(document.GetTextAnchorTreeAsString()); - } - for (int i = 0; i < 11; i++) { - Assert.AreEqual(i, a1[i].Offset); - Assert.AreEqual(i, a2[i].Offset); - } - document.Remove(1, 8); - for (int i = 0; i < 11; i++) { - if (i <= 1) { - Assert.IsFalse(a1[i].IsDeleted); - Assert.IsFalse(a2[i].IsDeleted); - Assert.AreEqual(i, a1[i].Offset); - Assert.AreEqual(i, a2[i].Offset); - } else if (i <= 8) { - Assert.IsFalse(a1[i].IsDeleted); - Assert.IsTrue(a2[i].IsDeleted); - Assert.AreEqual(1, a1[i].Offset); - } else { - Assert.IsFalse(a1[i].IsDeleted); - Assert.IsFalse(a2[i].IsDeleted); - Assert.AreEqual(i - 8, a1[i].Offset); - Assert.AreEqual(i - 8, a2[i].Offset); - } - } - } - - - Random rnd; - - [TestFixtureSetUp] - public void FixtureSetup() - { - int seed = Environment.TickCount; - Console.WriteLine("TextAnchorTest Seed: " + seed); - rnd = new Random(seed); - } - - [Test] - public void CreateAnchors() - { - List anchors = new List(); - List expectedOffsets = new List(); - document.Text = new string(' ', 1000); - for (int i = 0; i < 1000; i++) { - int offset = rnd.Next(1000); - anchors.Add(document.CreateAnchor(offset)); - expectedOffsets.Add(offset); - } - for (int i = 0; i < anchors.Count; i++) { - Assert.AreEqual(expectedOffsets[i], anchors[i].Offset); - } - GC.KeepAlive(anchors); - } - - [Test] - public void CreateAndGCAnchors() - { - List anchors = new List(); - List expectedOffsets = new List(); - document.Text = new string(' ', 1000); - for (int t = 0; t < 250; t++) { - int c = rnd.Next(50); - if (rnd.Next(2) == 0) { - for (int i = 0; i < c; i++) { - int offset = rnd.Next(1000); - anchors.Add(document.CreateAnchor(offset)); - expectedOffsets.Add(offset); - } - } else if (c <= anchors.Count) { - anchors.RemoveRange(0, c); - expectedOffsets.RemoveRange(0, c); - GC.Collect(); - } - for (int j = 0; j < anchors.Count; j++) { - Assert.AreEqual(expectedOffsets[j], anchors[j].Offset); - } - } - GC.KeepAlive(anchors); - } - - [Test] - public void MoveAnchorsDuringReplace() - { - document.Text = "abcd"; - TextAnchor start = document.CreateAnchor(1); - TextAnchor middleDeletable = document.CreateAnchor(2); - TextAnchor middleSurvivorLeft = document.CreateAnchor(2); - middleSurvivorLeft.SurviveDeletion = true; - middleSurvivorLeft.MovementType = AnchorMovementType.BeforeInsertion; - TextAnchor middleSurvivorRight = document.CreateAnchor(2); - middleSurvivorRight.SurviveDeletion = true; - middleSurvivorRight.MovementType = AnchorMovementType.AfterInsertion; - TextAnchor end = document.CreateAnchor(3); - document.Replace(1, 2, "BxC"); - - Assert.AreEqual(1, start.Offset); - Assert.IsTrue(middleDeletable.IsDeleted); - Assert.AreEqual(1, middleSurvivorLeft.Offset); - Assert.AreEqual(4, middleSurvivorRight.Offset); - Assert.AreEqual(4, end.Offset); - } - - [Test] - public void CreateAndMoveAnchors() - { - List anchors = new List(); - List expectedOffsets = new List(); - document.Text = new string(' ', 1000); - for (int t = 0; t < 250; t++) { - //Console.Write("t = " + t + " "); - int c = rnd.Next(50); - switch (rnd.Next(5)) { - case 0: - //Console.WriteLine("Add c=" + c + " anchors"); - for (int i = 0; i < c; i++) { - int offset = rnd.Next(document.TextLength); - TextAnchor anchor = document.CreateAnchor(offset); - if (rnd.Next(2) == 0) - anchor.MovementType = AnchorMovementType.BeforeInsertion; - else - anchor.MovementType = AnchorMovementType.AfterInsertion; - anchor.SurviveDeletion = rnd.Next(2) == 0; - anchors.Add(anchor); - expectedOffsets.Add(offset); - } - break; - case 1: - if (c <= anchors.Count) { - //Console.WriteLine("Remove c=" + c + " anchors"); - anchors.RemoveRange(0, c); - expectedOffsets.RemoveRange(0, c); - GC.Collect(); - } - break; - case 2: - int insertOffset = rnd.Next(document.TextLength); - int insertLength = rnd.Next(1000); - //Console.WriteLine("insertOffset=" + insertOffset + " insertLength="+insertLength); - document.Insert(insertOffset, new string(' ', insertLength)); - for (int i = 0; i < anchors.Count; i++) { - if (anchors[i].MovementType == AnchorMovementType.BeforeInsertion) { - if (expectedOffsets[i] > insertOffset) - expectedOffsets[i] += insertLength; - } else { - if (expectedOffsets[i] >= insertOffset) - expectedOffsets[i] += insertLength; - } - } - break; - case 3: - int removalOffset = rnd.Next(document.TextLength); - int removalLength = rnd.Next(document.TextLength - removalOffset); - //Console.WriteLine("RemovalOffset=" + removalOffset + " RemovalLength="+removalLength); - document.Remove(removalOffset, removalLength); - for (int i = anchors.Count - 1; i >= 0; i--) { - if (expectedOffsets[i] > removalOffset && expectedOffsets[i] < removalOffset + removalLength) { - if (anchors[i].SurviveDeletion) { - expectedOffsets[i] = removalOffset; - } else { - Assert.IsTrue(anchors[i].IsDeleted); - anchors.RemoveAt(i); - expectedOffsets.RemoveAt(i); - } - } else if (expectedOffsets[i] > removalOffset) { - expectedOffsets[i] -= removalLength; - } - } - break; - case 4: - int replaceOffset = rnd.Next(document.TextLength); - int replaceRemovalLength = rnd.Next(document.TextLength - replaceOffset); - int replaceInsertLength = rnd.Next(1000); - //Console.WriteLine("ReplaceOffset=" + replaceOffset + " RemovalLength="+replaceRemovalLength + " InsertLength=" + replaceInsertLength); - document.Replace(replaceOffset, replaceRemovalLength, new string(' ', replaceInsertLength)); - for (int i = anchors.Count - 1; i >= 0; i--) { - if (expectedOffsets[i] > replaceOffset && expectedOffsets[i] < replaceOffset + replaceRemovalLength) { - if (anchors[i].SurviveDeletion) { - if (anchors[i].MovementType == AnchorMovementType.AfterInsertion) - expectedOffsets[i] = replaceOffset + replaceInsertLength; - else - expectedOffsets[i] = replaceOffset; - } else { - Assert.IsTrue(anchors[i].IsDeleted); - anchors.RemoveAt(i); - expectedOffsets.RemoveAt(i); - } - } else if (expectedOffsets[i] > replaceOffset) { - expectedOffsets[i] += replaceInsertLength - replaceRemovalLength; - } else if (expectedOffsets[i] == replaceOffset && replaceRemovalLength == 0 && anchors[i].MovementType == AnchorMovementType.AfterInsertion) { - expectedOffsets[i] += replaceInsertLength - replaceRemovalLength; - } - } - break; - } - Assert.AreEqual(anchors.Count, expectedOffsets.Count); - for (int j = 0; j < anchors.Count; j++) { - Assert.AreEqual(expectedOffsets[j], anchors[j].Offset); - } - } - GC.KeepAlive(anchors); - } - - [Test] - public void RepeatedTextDragDrop() - { - document.Text = new string(' ', 1000); - for (int i = 0; i < 20; i++) { - TextAnchor a = document.CreateAnchor(144); - TextAnchor b = document.CreateAnchor(157); - document.Insert(128, new string('a', 13)); - document.Remove(157, 13); - a = document.CreateAnchor(128); - b = document.CreateAnchor(141); - - document.Insert(157, new string('b', 13)); - document.Remove(128, 13); - - a = null; - b = null; - if ((i % 5) == 0) - GC.Collect(); - } - } - - [Test] - public void ReplaceSpacesWithTab() - { - document.Text = "a b"; - TextAnchor before = document.CreateAnchor(1); - before.MovementType = AnchorMovementType.AfterInsertion; - TextAnchor after = document.CreateAnchor(5); - TextAnchor survivingMiddle = document.CreateAnchor(2); - TextAnchor deletedMiddle = document.CreateAnchor(3); - - document.Replace(1, 4, "\t", OffsetChangeMappingType.CharacterReplace); - Assert.AreEqual("a\tb", document.Text); - // yes, the movement is a bit strange; but that's how CharacterReplace works when the text gets shorter - Assert.AreEqual(1, before.Offset); - Assert.AreEqual(2, after.Offset); - Assert.AreEqual(2, survivingMiddle.Offset); - Assert.AreEqual(2, deletedMiddle.Offset); - } - - [Test] - public void ReplaceTwoCharactersWithThree() - { - document.Text = "a12b"; - TextAnchor before = document.CreateAnchor(1); - before.MovementType = AnchorMovementType.AfterInsertion; - TextAnchor after = document.CreateAnchor(3); - before.MovementType = AnchorMovementType.BeforeInsertion; - TextAnchor middleB = document.CreateAnchor(2); - before.MovementType = AnchorMovementType.BeforeInsertion; - TextAnchor middleA = document.CreateAnchor(2); - before.MovementType = AnchorMovementType.AfterInsertion; - - document.Replace(1, 2, "123", OffsetChangeMappingType.CharacterReplace); - Assert.AreEqual("a123b", document.Text); - Assert.AreEqual(1, before.Offset); - Assert.AreEqual(4, after.Offset); - Assert.AreEqual(2, middleA.Offset); - Assert.AreEqual(2, middleB.Offset); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/TextSegmentTreeTest.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/TextSegmentTreeTest.cs deleted file mode 100644 index d893583b2..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/TextSegmentTreeTest.cs +++ /dev/null @@ -1,368 +0,0 @@ -// 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; -#endif -using NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Document -{ - [TestFixture] - public class TextSegmentTreeTest - { - Random rnd; - - [TestFixtureSetUp] - public void FixtureSetup() - { - int seed = Environment.TickCount; - Console.WriteLine("TextSegmentTreeTest Seed: " + seed); - rnd = new Random(seed); - } - - class TestTextSegment : TextSegment - { - internal int ExpectedOffset, ExpectedLength; - - public TestTextSegment(int expectedOffset, int expectedLength) - { - this.ExpectedOffset = expectedOffset; - this.ExpectedLength = expectedLength; - this.StartOffset = expectedOffset; - this.Length = expectedLength; - } - } - - TextSegmentCollection tree; - List expectedSegments; - - [SetUp] - public void SetUp() - { - tree = new TextSegmentCollection(); - expectedSegments = new List(); - } - - [Test] - public void FindInEmptyTree() - { - Assert.AreSame(null, tree.FindFirstSegmentWithStartAfter(0)); - Assert.AreEqual(0, tree.FindSegmentsContaining(0).Count); - Assert.AreEqual(0, tree.FindOverlappingSegments(10, 20).Count); - } - - [Test] - public void FindFirstSegmentWithStartAfter() - { - var s1 = new TestTextSegment(5, 10); - var s2 = new TestTextSegment(10, 10); - tree.Add(s1); - tree.Add(s2); - Assert.AreSame(s1, tree.FindFirstSegmentWithStartAfter(-100)); - Assert.AreSame(s1, tree.FindFirstSegmentWithStartAfter(0)); - Assert.AreSame(s1, tree.FindFirstSegmentWithStartAfter(4)); - Assert.AreSame(s1, tree.FindFirstSegmentWithStartAfter(5)); - Assert.AreSame(s2, tree.FindFirstSegmentWithStartAfter(6)); - Assert.AreSame(s2, tree.FindFirstSegmentWithStartAfter(9)); - Assert.AreSame(s2, tree.FindFirstSegmentWithStartAfter(10)); - Assert.AreSame(null, tree.FindFirstSegmentWithStartAfter(11)); - Assert.AreSame(null, tree.FindFirstSegmentWithStartAfter(100)); - } - - [Test] - public void FindFirstSegmentWithStartAfterWithDuplicates() - { - var s1 = new TestTextSegment(5, 10); - var s1b = new TestTextSegment(5, 7); - var s2 = new TestTextSegment(10, 10); - var s2b = new TestTextSegment(10, 7); - tree.Add(s1); - tree.Add(s1b); - tree.Add(s2); - tree.Add(s2b); - Assert.AreSame(s1b, tree.GetNextSegment(s1)); - Assert.AreSame(s2b, tree.GetNextSegment(s2)); - Assert.AreSame(s1, tree.FindFirstSegmentWithStartAfter(-100)); - Assert.AreSame(s1, tree.FindFirstSegmentWithStartAfter(0)); - Assert.AreSame(s1, tree.FindFirstSegmentWithStartAfter(4)); - Assert.AreSame(s1, tree.FindFirstSegmentWithStartAfter(5)); - Assert.AreSame(s2, tree.FindFirstSegmentWithStartAfter(6)); - Assert.AreSame(s2, tree.FindFirstSegmentWithStartAfter(9)); - Assert.AreSame(s2, tree.FindFirstSegmentWithStartAfter(10)); - Assert.AreSame(null, tree.FindFirstSegmentWithStartAfter(11)); - Assert.AreSame(null, tree.FindFirstSegmentWithStartAfter(100)); - } - - [Test] - public void FindFirstSegmentWithStartAfterWithDuplicates2() - { - var s1 = new TestTextSegment(5, 1); - var s2 = new TestTextSegment(5, 2); - var s3 = new TestTextSegment(5, 3); - var s4 = new TestTextSegment(5, 4); - tree.Add(s1); - tree.Add(s2); - tree.Add(s3); - tree.Add(s4); - Assert.AreSame(s1, tree.FindFirstSegmentWithStartAfter(0)); - Assert.AreSame(s1, tree.FindFirstSegmentWithStartAfter(1)); - Assert.AreSame(s1, tree.FindFirstSegmentWithStartAfter(4)); - Assert.AreSame(s1, tree.FindFirstSegmentWithStartAfter(5)); - Assert.AreSame(null, tree.FindFirstSegmentWithStartAfter(6)); - } - - TestTextSegment AddSegment(int offset, int length) - { -// Console.WriteLine("Add " + offset + ", " + length); - TestTextSegment s = new TestTextSegment(offset, length); - tree.Add(s); - expectedSegments.Add(s); - return s; - } - - void RemoveSegment(TestTextSegment s) - { -// Console.WriteLine("Remove " + s); - expectedSegments.Remove(s); - tree.Remove(s); - } - - void TestRetrieval(int offset, int length) - { - HashSet actual = new HashSet(tree.FindOverlappingSegments(offset, length)); - HashSet expected = new HashSet(); - foreach (TestTextSegment e in expectedSegments) { - if (e.ExpectedOffset + e.ExpectedLength < offset) - continue; - if (e.ExpectedOffset > offset + length) - continue; - expected.Add(e); - } - Assert.IsTrue(actual.IsSubsetOf(expected)); - Assert.IsTrue(expected.IsSubsetOf(actual)); - } - - void CheckSegments() - { - Assert.AreEqual(expectedSegments.Count, tree.Count); - foreach (TestTextSegment s in expectedSegments) { - Assert.AreEqual(s.ExpectedOffset, s.StartOffset /*, "startoffset for " + s*/); - Assert.AreEqual(s.ExpectedLength, s.Length /*, "length for " + s*/); - } - } - - [Test] - public void AddSegments() - { - TestTextSegment s1 = AddSegment(10, 20); - TestTextSegment s2 = AddSegment(15, 10); - CheckSegments(); - } - - void ChangeDocument(OffsetChangeMapEntry change) - { - tree.UpdateOffsets(change); - foreach (TestTextSegment s in expectedSegments) { - int endOffset = s.ExpectedOffset + s.ExpectedLength; - s.ExpectedOffset = change.GetNewOffset(s.ExpectedOffset, AnchorMovementType.AfterInsertion); - s.ExpectedLength = Math.Max(0, change.GetNewOffset(endOffset, AnchorMovementType.BeforeInsertion) - s.ExpectedOffset); - } - } - - [Test] - public void InsertionBeforeAllSegments() - { - TestTextSegment s1 = AddSegment(10, 20); - TestTextSegment s2 = AddSegment(15, 10); - ChangeDocument(new OffsetChangeMapEntry(5, 0, 2)); - CheckSegments(); - } - - [Test] - public void ReplacementBeforeAllSegmentsTouchingFirstSegment() - { - TestTextSegment s1 = AddSegment(10, 20); - TestTextSegment s2 = AddSegment(15, 10); - ChangeDocument(new OffsetChangeMapEntry(5, 5, 2)); - CheckSegments(); - } - - [Test] - public void InsertionAfterAllSegments() - { - TestTextSegment s1 = AddSegment(10, 20); - TestTextSegment s2 = AddSegment(15, 10); - ChangeDocument(new OffsetChangeMapEntry(45, 0, 2)); - CheckSegments(); - } - - [Test] - public void ReplacementOverlappingWithStartOfSegment() - { - TestTextSegment s1 = AddSegment(10, 20); - TestTextSegment s2 = AddSegment(15, 10); - ChangeDocument(new OffsetChangeMapEntry(9, 7, 2)); - CheckSegments(); - } - - [Test] - public void ReplacementOfWholeSegment() - { - TestTextSegment s1 = AddSegment(10, 20); - TestTextSegment s2 = AddSegment(15, 10); - ChangeDocument(new OffsetChangeMapEntry(10, 20, 30)); - CheckSegments(); - } - - [Test] - public void ReplacementAtEndOfSegment() - { - TestTextSegment s1 = AddSegment(10, 20); - TestTextSegment s2 = AddSegment(15, 10); - ChangeDocument(new OffsetChangeMapEntry(24, 6, 10)); - CheckSegments(); - } - - [Test] - public void RandomizedNoDocumentChanges() - { - for (int i = 0; i < 1000; i++) { -// Console.WriteLine(tree.GetTreeAsString()); -// Console.WriteLine("Iteration " + i); - - switch (rnd.Next(3)) { - case 0: - AddSegment(rnd.Next(500), rnd.Next(30)); - break; - case 1: - AddSegment(rnd.Next(500), rnd.Next(300)); - break; - case 2: - if (tree.Count > 0) { - RemoveSegment(expectedSegments[rnd.Next(tree.Count)]); - } - break; - } - CheckSegments(); - } - } - - [Test] - public void RandomizedCloseNoDocumentChanges() - { - // Lots of segments in a short document. Tests how the tree copes with multiple identical segments. - for (int i = 0; i < 1000; i++) { - switch (rnd.Next(3)) { - case 0: - AddSegment(rnd.Next(20), rnd.Next(10)); - break; - case 1: - AddSegment(rnd.Next(20), rnd.Next(20)); - break; - case 2: - if (tree.Count > 0) { - RemoveSegment(expectedSegments[rnd.Next(tree.Count)]); - } - break; - } - CheckSegments(); - } - } - - [Test] - public void RandomizedRetrievalTest() - { - for (int i = 0; i < 1000; i++) { - AddSegment(rnd.Next(500), rnd.Next(300)); - } - CheckSegments(); - for (int i = 0; i < 1000; i++) { - TestRetrieval(rnd.Next(1000) - 100, rnd.Next(500)); - } - } - - [Test] - public void RandomizedWithDocumentChanges() - { - for (int i = 0; i < 500; i++) { -// Console.WriteLine(tree.GetTreeAsString()); -// Console.WriteLine("Iteration " + i); - - switch (rnd.Next(6)) { - case 0: - AddSegment(rnd.Next(500), rnd.Next(30)); - break; - case 1: - AddSegment(rnd.Next(500), rnd.Next(300)); - break; - case 2: - if (tree.Count > 0) { - RemoveSegment(expectedSegments[rnd.Next(tree.Count)]); - } - break; - case 3: - ChangeDocument(new OffsetChangeMapEntry(rnd.Next(800), rnd.Next(50), rnd.Next(50))); - break; - case 4: - ChangeDocument(new OffsetChangeMapEntry(rnd.Next(800), 0, rnd.Next(50))); - break; - case 5: - ChangeDocument(new OffsetChangeMapEntry(rnd.Next(800), rnd.Next(50), 0)); - break; - } - CheckSegments(); - } - } - - [Test] - public void RandomizedWithDocumentChangesClose() - { - for (int i = 0; i < 500; i++) { -// Console.WriteLine(tree.GetTreeAsString()); -// Console.WriteLine("Iteration " + i); - - switch (rnd.Next(6)) { - case 0: - AddSegment(rnd.Next(50), rnd.Next(30)); - break; - case 1: - AddSegment(rnd.Next(50), rnd.Next(3)); - break; - case 2: - if (tree.Count > 0) { - RemoveSegment(expectedSegments[rnd.Next(tree.Count)]); - } - break; - case 3: - ChangeDocument(new OffsetChangeMapEntry(rnd.Next(80), rnd.Next(10), rnd.Next(10))); - break; - case 4: - ChangeDocument(new OffsetChangeMapEntry(rnd.Next(80), 0, rnd.Next(10))); - break; - case 5: - ChangeDocument(new OffsetChangeMapEntry(rnd.Next(80), rnd.Next(10), 0)); - break; - } - CheckSegments(); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/TextUtilitiesTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/TextUtilitiesTests.cs deleted file mode 100644 index ab9abffe9..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/TextUtilitiesTests.cs +++ /dev/null @@ -1,94 +0,0 @@ -// 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 NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Document -{ - [TestFixture] - public class TextUtilitiesTests - { - #region GetWhitespaceAfter - [Test] - public void TestGetWhitespaceAfter() - { - Assert.AreEqual(new SimpleSegment(2, 3), TextUtilities.GetWhitespaceAfter(new StringTextSource("a \t \tb"), 2)); - } - - [Test] - public void TestGetWhitespaceAfterDoesNotSkipNewLine() - { - Assert.AreEqual(new SimpleSegment(2, 3), TextUtilities.GetWhitespaceAfter(new StringTextSource("a \t \tb"), 2)); - } - - [Test] - public void TestGetWhitespaceAfterEmptyResult() - { - Assert.AreEqual(new SimpleSegment(2, 0), TextUtilities.GetWhitespaceAfter(new StringTextSource("a b"), 2)); - } - - [Test] - public void TestGetWhitespaceAfterEndOfString() - { - Assert.AreEqual(new SimpleSegment(2, 0), TextUtilities.GetWhitespaceAfter(new StringTextSource("a "), 2)); - } - - [Test] - public void TestGetWhitespaceAfterUntilEndOfString() - { - Assert.AreEqual(new SimpleSegment(2, 3), TextUtilities.GetWhitespaceAfter(new StringTextSource("a \t \t"), 2)); - } - #endregion - - #region GetWhitespaceBefore - [Test] - public void TestGetWhitespaceBefore() - { - Assert.AreEqual(new SimpleSegment(1, 3), TextUtilities.GetWhitespaceBefore(new StringTextSource("a\t \t b"), 4)); - } - - [Test] - public void TestGetWhitespaceBeforeDoesNotSkipNewLine() - { - Assert.AreEqual(new SimpleSegment(2, 1), TextUtilities.GetWhitespaceBefore(new StringTextSource("a\n b"), 3)); - } - - [Test] - public void TestGetWhitespaceBeforeEmptyResult() - { - Assert.AreEqual(new SimpleSegment(2, 0), TextUtilities.GetWhitespaceBefore(new StringTextSource(" a b"), 2)); - } - - [Test] - public void TestGetWhitespaceBeforeStartOfString() - { - Assert.AreEqual(new SimpleSegment(0, 0), TextUtilities.GetWhitespaceBefore(new StringTextSource(" a"), 0)); - } - - [Test] - public void TestGetWhitespaceBeforeUntilStartOfString() - { - Assert.AreEqual(new SimpleSegment(0, 2), TextUtilities.GetWhitespaceBefore(new StringTextSource(" \t a"), 2)); - } - #endregion - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/UndoStackTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/UndoStackTests.cs deleted file mode 100644 index 2c9c425d4..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Document/UndoStackTests.cs +++ /dev/null @@ -1,92 +0,0 @@ -// 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 NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Document -{ - public class UndoStackTests - { - [Test] - public void ContinueUndoGroup() - { - var doc = new TextDocument(); - doc.Insert(0, "a"); - doc.UndoStack.StartContinuedUndoGroup(); - doc.Insert(1, "b"); - doc.UndoStack.EndUndoGroup(); - doc.UndoStack.Undo(); - Assert.AreEqual("", doc.Text); - } - - [Test] - public void ContinueEmptyUndoGroup() - { - var doc = new TextDocument(); - doc.Insert(0, "a"); - doc.UndoStack.StartUndoGroup(); - doc.UndoStack.EndUndoGroup(); - doc.UndoStack.StartContinuedUndoGroup(); - doc.Insert(1, "b"); - doc.UndoStack.EndUndoGroup(); - doc.UndoStack.Undo(); - Assert.AreEqual("a", doc.Text); - } - - [Test] - public void ContinueEmptyUndoGroup_WithOptionalEntries() - { - var doc = new TextDocument(); - doc.Insert(0, "a"); - doc.UndoStack.StartUndoGroup(); - doc.UndoStack.PushOptional(new StubUndoableAction()); - doc.UndoStack.EndUndoGroup(); - doc.UndoStack.StartContinuedUndoGroup(); - doc.Insert(1, "b"); - doc.UndoStack.EndUndoGroup(); - doc.UndoStack.Undo(); - Assert.AreEqual("a", doc.Text); - } - - [Test] - public void EmptyContinuationGroup() - { - var doc = new TextDocument(); - doc.Insert(0, "a"); - doc.UndoStack.StartContinuedUndoGroup(); - doc.UndoStack.EndUndoGroup(); - doc.UndoStack.StartContinuedUndoGroup(); - doc.Insert(1, "b"); - doc.UndoStack.EndUndoGroup(); - doc.UndoStack.Undo(); - Assert.AreEqual("", doc.Text); - } - - class StubUndoableAction : IUndoableOperation - { - public void Undo() - { - } - - public void Redo() - { - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Editing/ChangeDocumentTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Editing/ChangeDocumentTests.cs deleted file mode 100644 index bc0176ad7..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Editing/ChangeDocumentTests.cs +++ /dev/null @@ -1,78 +0,0 @@ -// 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 ICSharpCode.AvalonEdit.Document; -#if NREFACTORY -using ICSharpCode.NRefactory; -#endif -using NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Editing -{ - [TestFixture] - public class ChangeDocumentTests - { - [Test] - public void ClearCaretAndSelectionOnDocumentChange() - { - TextArea textArea = new TextArea(); - textArea.Document = new TextDocument("1\n2\n3\n4th line"); - textArea.Caret.Offset = 6; - textArea.Selection = Selection.Create(textArea, 3, 6); - textArea.Document = new TextDocument("1\n2nd"); - Assert.AreEqual(0, textArea.Caret.Offset); - Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); - Assert.IsTrue(textArea.Selection.IsEmpty); - } - - [Test] - public void SetDocumentToNull() - { - TextArea textArea = new TextArea(); - textArea.Document = new TextDocument("1\n2\n3\n4th line"); - textArea.Caret.Offset = 6; - textArea.Selection = Selection.Create(textArea, 3, 6); - textArea.Document = null; - Assert.AreEqual(0, textArea.Caret.Offset); - Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); - Assert.IsTrue(textArea.Selection.IsEmpty); - } - - [Test] - public void CheckEventOrderOnDocumentChange() - { - TextArea textArea = new TextArea(); - TextDocument newDocument = new TextDocument(); - StringBuilder b = new StringBuilder(); - textArea.TextView.DocumentChanged += delegate { - b.Append("TextView.DocumentChanged;"); - Assert.AreSame(newDocument, textArea.TextView.Document); - Assert.AreSame(newDocument, textArea.Document); - }; - textArea.DocumentChanged += delegate { - b.Append("TextArea.DocumentChanged;"); - Assert.AreSame(newDocument, textArea.TextView.Document); - Assert.AreSame(newDocument, textArea.Document); - }; - textArea.Document = newDocument; - Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Editing/TextSegmentReadOnlySectionTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Editing/TextSegmentReadOnlySectionTests.cs deleted file mode 100644 index 23cbeb5b1..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Editing/TextSegmentReadOnlySectionTests.cs +++ /dev/null @@ -1,183 +0,0 @@ -// 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; -using System.Linq; -using NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Editing -{ - [TestFixture] - public class TextSegmentReadOnlySectionTests - { - TextSegmentCollection segments; - TextSegmentReadOnlySectionProvider provider; - - [SetUp] - public void SetUp() - { - segments = new TextSegmentCollection(); - provider = new TextSegmentReadOnlySectionProvider(segments); - } - - [Test] - public void InsertionPossibleWhenNothingIsReadOnly() - { - Assert.IsTrue(provider.CanInsert(0)); - Assert.IsTrue(provider.CanInsert(100)); - } - - [Test] - public void DeletionPossibleWhenNothingIsReadOnly() - { - var result = provider.GetDeletableSegments(new SimpleSegment(10, 20)).ToList(); - Assert.AreEqual(1, result.Count); - Assert.AreEqual(10, result[0].Offset); - Assert.AreEqual(20, result[0].Length); - } - - [Test] - public void EmptyDeletionPossibleWhenNothingIsReadOnly() - { - var result = provider.GetDeletableSegments(new SimpleSegment(10, 0)).ToList(); - Assert.AreEqual(1, result.Count); - Assert.AreEqual(10, result[0].Offset); - Assert.AreEqual(0, result[0].Length); - } - - [Test] - public void InsertionPossibleBeforeReadOnlySegment() - { - segments.Add(new TextSegment { StartOffset = 10, EndOffset = 15 }); - Assert.IsTrue(provider.CanInsert(5)); - } - - [Test] - public void InsertionPossibleAtStartOfReadOnlySegment() - { - segments.Add(new TextSegment { StartOffset = 10, EndOffset = 15 }); - Assert.IsTrue(provider.CanInsert(10)); - } - - [Test] - public void InsertionImpossibleInsideReadOnlySegment() - { - segments.Add(new TextSegment { StartOffset = 10, EndOffset = 15 }); - Assert.IsFalse(provider.CanInsert(11)); - Assert.IsFalse(provider.CanInsert(12)); - Assert.IsFalse(provider.CanInsert(13)); - Assert.IsFalse(provider.CanInsert(14)); - } - - [Test] - public void InsertionPossibleAtEndOfReadOnlySegment() - { - segments.Add(new TextSegment { StartOffset = 10, EndOffset = 15 }); - Assert.IsTrue(provider.CanInsert(15)); - } - - [Test] - public void InsertionPossibleBetweenReadOnlySegments() - { - segments.Add(new TextSegment { StartOffset = 10, EndOffset = 15 }); - segments.Add(new TextSegment { StartOffset = 15, EndOffset = 20 }); - Assert.IsTrue(provider.CanInsert(15)); - } - - [Test] - public void DeletionImpossibleInReadOnlySegment() - { - segments.Add(new TextSegment { StartOffset = 10, Length = 5 }); - var result = provider.GetDeletableSegments(new SimpleSegment(11, 2)).ToList(); - Assert.AreEqual(0, result.Count); - } - - [Test] - public void EmptyDeletionImpossibleInReadOnlySegment() - { - segments.Add(new TextSegment { StartOffset = 10, Length = 5 }); - var result = provider.GetDeletableSegments(new SimpleSegment(11, 0)).ToList(); - Assert.AreEqual(0, result.Count); - } - - [Test] - public void EmptyDeletionPossibleAtStartOfReadOnlySegment() - { - segments.Add(new TextSegment { StartOffset = 10, Length = 5 }); - var result = provider.GetDeletableSegments(new SimpleSegment(10, 0)).ToList(); - Assert.AreEqual(1, result.Count); - Assert.AreEqual(10, result[0].Offset); - Assert.AreEqual(0, result[0].Length); - } - - [Test] - public void EmptyDeletionPossibleAtEndOfReadOnlySegment() - { - segments.Add(new TextSegment { StartOffset = 10, Length = 5 }); - var result = provider.GetDeletableSegments(new SimpleSegment(15, 0)).ToList(); - Assert.AreEqual(1, result.Count); - Assert.AreEqual(15, result[0].Offset); - Assert.AreEqual(0, result[0].Length); - } - - [Test] - public void DeletionAroundReadOnlySegment() - { - segments.Add(new TextSegment { StartOffset = 20, Length = 5 }); - var result = provider.GetDeletableSegments(new SimpleSegment(15, 16)).ToList(); - Assert.AreEqual(2, result.Count); - Assert.AreEqual(15, result[0].Offset); - Assert.AreEqual(5, result[0].Length); - Assert.AreEqual(25, result[1].Offset); - Assert.AreEqual(6, result[1].Length); - } - - [Test] - public void DeleteLastCharacterInReadOnlySegment() - { - segments.Add(new TextSegment { StartOffset = 20, Length = 5 }); - var result = provider.GetDeletableSegments(new SimpleSegment(24, 1)).ToList(); - Assert.AreEqual(0, result.Count); - /* // we would need this result for the old Backspace code so that the last character doesn't get selected: - Assert.AreEqual(1, result.Count); - Assert.AreEqual(25, result[0].Offset); - Assert.AreEqual(0, result[0].Length);*/ - } - - [Test] - public void DeleteFirstCharacterInReadOnlySegment() - { - segments.Add(new TextSegment { StartOffset = 20, Length = 5 }); - var result = provider.GetDeletableSegments(new SimpleSegment(20, 1)).ToList(); - Assert.AreEqual(0, result.Count); - /* // we would need this result for the old Delete code so that the first character doesn't get selected: - Assert.AreEqual(1, result.Count); - Assert.AreEqual(2, result[0].Offset); - Assert.AreEqual(0, result[0].Length);*/ - } - - [Test] - public void DeleteWholeReadOnlySegment() - { - segments.Add(new TextSegment { StartOffset = 20, Length = 5 }); - var result = provider.GetDeletableSegments(new SimpleSegment(20, 5)).ToList(); - Assert.AreEqual(0, result.Count); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Highlighting/HighlightedLineMergeTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Highlighting/HighlightedLineMergeTests.cs deleted file mode 100644 index b6c1eface..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Highlighting/HighlightedLineMergeTests.cs +++ /dev/null @@ -1,182 +0,0 @@ -// 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 NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Highlighting -{ - [TestFixture] - public class HighlightedLineMergeTests - { - IDocument document = new TextDocument(new string(' ', 20)); - - [Test] - public void SimpleMerge1() - { - HighlightedLine baseLine = new HighlightedLine(document, document.GetLineByNumber(1)); - baseLine.Sections.Add(MakeSection(0, 1, "B")); - - HighlightedLine additionalLine = new HighlightedLine(document, document.GetLineByNumber(1)); - additionalLine.Sections.Add(MakeSection(0, 2, "A")); - - baseLine.MergeWith(additionalLine); - // The additional section gets split up so that it fits into the tree structure - Assert.That(baseLine.Sections, Is.EqualTo( - new[] { - MakeSection(0, 1, "B"), - MakeSection(0, 1, "A"), - MakeSection(1, 2, "A") - }).Using(new SectionComparer())); - } - - [Test] - public void SimpleMerge2() - { - HighlightedLine baseLine = new HighlightedLine(document, document.GetLineByNumber(1)); - baseLine.Sections.Add(MakeSection(0, 1, "B")); - baseLine.Sections.Add(MakeSection(0, 1, "BN")); - - HighlightedLine additionalLine = new HighlightedLine(document, document.GetLineByNumber(1)); - additionalLine.Sections.Add(MakeSection(0, 2, "A")); - - baseLine.MergeWith(additionalLine); - // The additional section gets split up so that it fits into the tree structure - Assert.That(baseLine.Sections, Is.EqualTo( - new[] { - MakeSection(0, 1, "B"), - MakeSection(0, 1, "BN"), - MakeSection(0, 1, "A"), - MakeSection(1, 2, "A") - }).Using(new SectionComparer())); - } - - HighlightedSection MakeSection(int start, int end, string name) - { - return new HighlightedSection { Offset = start, Length = end - start, Color = new HighlightingColor { Name = name }}; - } - - class SectionComparer : IEqualityComparer - { - public bool Equals(HighlightedSection a, HighlightedSection b) - { - return a.Offset == b.Offset && a.Length == b.Length && a.Color.Name == b.Color.Name; - } - - public int GetHashCode(HighlightedSection obj) - { - return obj.Offset; - } - } - - #region Automatic Test - /* - const int combinations = 6 * 3 * 4 * 3 * 3 * 4; - HighlightingColor[] baseLineColors = { - new HighlightingColor { Name = "Base-A" }, - new HighlightingColor { Name = "Base-B" }, - new HighlightingColor { Name = "Base-N" }, - new HighlightingColor { Name = "Base-C" } - }; - HighlightingColor[] additionalLineColors = { - new HighlightingColor { Name = "Add-A" }, - new HighlightingColor { Name = "Add-B" }, - new HighlightingColor { Name = "Add-N" }, - new HighlightingColor { Name = "Add-C" } - }; - - HighlightedLine BuildHighlightedLine(int num, HighlightingColor[] colors) - { - // We are build a HighlightedLine with 4 segments: - // A B C (top-level) and N nested within B. - // These are the integers controlling the generating process: - - int aStart = GetNum(ref num, 5); // start offset of A - int aLength = GetNum(ref num, 2); // length of A - - int bDistance = GetNum(ref num, 3); // distance from start of B to end of A - int bStart = aStart + aLength + bDistance; - int nDistance = GetNum(ref num, 2); // distance from start of B to start of N, range 0-2 - int nLength = GetNum(ref num, 2); // length of N - int bEndDistance = GetNum(ref num, 2); // distance from end of N to end of B - int bLength = nDistance + nLength + bEndDistance; - - int cDistance = GetNum(ref num, 3); // distance from end of B to start of C - int cStart = bStart + bLength + cDistance; - int cLength = 1; - Assert.AreEqual(0, num); - - var documentLine = document.GetLineByNumber(1); - HighlightedLine line = new HighlightedLine(document, documentLine); - line.Sections.Add(new HighlightedSection { Offset = aStart, Length = aLength, Color = colors[0] }); - line.Sections.Add(new HighlightedSection { Offset = bStart, Length = bLength, Color = colors[1] }); - line.Sections.Add(new HighlightedSection { Offset = bStart + nDistance, Length = nLength, Color = colors[2] }); - line.Sections.Add(new HighlightedSection { Offset = cStart, Length = cLength, Color = colors[3] }); - - return line; - } - - /// - /// Gets a number between 0 and max (inclusive) - /// - int GetNum(ref int num, int max) - { - int result = num % (max+1); - num = num / (max + 1); - return result; - } - - [Test] - public void TestAll() - { - for (int c1 = 0; c1 < combinations; c1++) { - HighlightedLine line1 = BuildHighlightedLine(c1, additionalLineColors); - for (int c2 = 0; c2 < combinations; c2++) { - HighlightedLine line2 = BuildHighlightedLine(c2, baseLineColors); - HighlightingColor[] expectedPerCharColors = new HighlightingColor[document.TextLength]; - ApplyColors(expectedPerCharColors, line2); - ApplyColors(expectedPerCharColors, line1); - try { - line2.MergeWith(line1); - } catch (InvalidOperationException ex) { - throw new InvalidOperationException(string.Format("Error for c1 = {0}, c2 = {1}", c1, c2), ex); - } - - HighlightingColor[] actualPerCharColors = new HighlightingColor[document.TextLength]; - ApplyColors(actualPerCharColors, line2); - Assert.AreEqual(expectedPerCharColors, actualPerCharColors, string.Format("c1 = {0}, c2 = {1}", c1, c2)); - } - } - } - - void ApplyColors(HighlightingColor[] perCharColors, HighlightedLine line) - { - foreach (var section in line.Sections) { - for (int i = 0; i < section.Length; i++) { - perCharColors[section.Offset + i] = section.Color; - } - } - } - */ - #endregion - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Highlighting/HtmlClipboardTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Highlighting/HtmlClipboardTests.cs deleted file mode 100644 index 0d7ffd995..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Highlighting/HtmlClipboardTests.cs +++ /dev/null @@ -1,56 +0,0 @@ -// 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 ICSharpCode.AvalonEdit.Document; -using NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Highlighting -{ - [TestFixture] - public class HtmlClipboardTests - { - TextDocument document; - DocumentHighlighter highlighter; - - public HtmlClipboardTests() - { - document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); - highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); - } - - [Test] - public void FullDocumentTest() - { - var segment = new TextSegment { StartOffset = 0, Length = document.TextLength }; - string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); - Assert.AreEqual("using System.Text;
" + Environment.NewLine + - "    string " + - "text = SomeMethod();", html); - } - - [Test] - public void PartOfHighlightedWordTest() - { - var segment = new TextSegment { StartOffset = 1, Length = 3 }; - string html = HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, new HtmlOptions()); - Assert.AreEqual("sin", html); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/ICSharpCode.AvalonEdit.Tests.PartCover.Settings b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/ICSharpCode.AvalonEdit.Tests.PartCover.Settings deleted file mode 100644 index 464ea890d..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/ICSharpCode.AvalonEdit.Tests.PartCover.Settings +++ /dev/null @@ -1,3 +0,0 @@ - - +[ICSharpCode.AvalonEdit]* - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/ICSharpCode.AvalonEdit.Tests.csproj b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/ICSharpCode.AvalonEdit.Tests.csproj deleted file mode 100644 index 82903ddb0..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/ICSharpCode.AvalonEdit.Tests.csproj +++ /dev/null @@ -1,126 +0,0 @@ - - - - {6222A3A1-83CE-47A3-A4E4-A018F82D44D8} - Debug - Net40 - Library - ICSharpCode.AvalonEdit - ICSharpCode.AvalonEdit.Tests - v4.0 - Properties - True - ..\ICSharpCode.AvalonEdit\ICSharpCode.AvalonEdit.snk - False - File - False - False - 4 - False - bin\$(Configuration)\ - OnBuildSuccess - - - False - obj\$(Configuration)\ - False - Auto - 4194304 - AnyCPU - 4096 - - - v3.5 - - - v4.0 - DOTNET4 - - - v4.5 - NREFACTORY - - - true - Full - False - True - obj\ - True - True - - - false - None - True - False - obj\ - True - - - - - {3B2A5653-EC97-4001-BB9B-D90F1AF2C371} - ICSharpCode.NRefactory - - - ..\packages\NUnit.2.6.3\lib\nunit.framework.dll - - - 3.0 - - - 3.0 - - - - 3.5 - - - 4.0 - - - - 3.5 - - - 3.0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {6C55B776-26D4-4DB3-A6AB-87E783B2F3D1} - ICSharpCode.AvalonEdit - - - - - - - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/MultipleUIThreads.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/MultipleUIThreads.cs deleted file mode 100644 index 8cd9a2413..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/MultipleUIThreads.cs +++ /dev/null @@ -1,44 +0,0 @@ -// 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.Threading; -using System.Windows; -using NUnit.Framework; - -namespace ICSharpCode.AvalonEdit -{ - [TestFixture] - public class MultipleUIThreads - { - Exception error; - - [Test] - public void CreateEditorInstancesOnMultipleUIThreads() - { - Thread t1 = new Thread(new ThreadStart(Run)); - Thread t2 = new Thread(new ThreadStart(Run)); - t1.SetApartmentState(ApartmentState.STA); - t2.SetApartmentState(ApartmentState.STA); - t1.Start(); - t2.Start(); - t1.Join(); - t2.Join(); - if (error != null) - throw new InvalidOperationException(error.Message, error); - } - - [STAThread] - void Run() - { - try { - var window = new Window(); - window.Content = new TextEditor(); - window.ShowActivated = false; - window.Show(); - } catch (Exception ex) { - error = ex; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Properties/AssemblyInfo.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Properties/AssemblyInfo.cs deleted file mode 100644 index 99842d5a6..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,55 +0,0 @@ -// 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. - -#region Using directives - -using System; -using System.Reflection; -using System.Runtime.InteropServices; - -using NUnit.Framework; - -#endregion - -// 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.Tests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ICSharpCode.AvalonEdit.Tests")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// This sets the default COM visibility of types in the assembly to invisible. -// If you need to expose a type to COM, use [ComVisible(true)] on that type. -[assembly: ComVisible(false)] - -// The assembly version has following format : -// -// Major.Minor.Build.Revision -// -// You can specify all the values or you can use the default the Revision and -// Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.*")] - -// Run unit tests on STA thread. -[assembly: RequiresSTA] - -namespace ICSharpCode.NRefactory.Editor {} \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Search/FindTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Search/FindTests.cs deleted file mode 100644 index 958baffa3..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Search/FindTests.cs +++ /dev/null @@ -1,132 +0,0 @@ -// 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; -#if NREFACTORY -using ICSharpCode.NRefactory.Editor; -#endif -using NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Search -{ - [TestFixture] - public class FindTests - { - [Test] - public void SkipWordBorderSimple() - { - var strategy = SearchStrategyFactory.Create("All", false, true, SearchMode.Normal); - var text = new StringTextSource(" FindAllTests "); - var results = strategy.FindAll(text, 0, text.TextLength).ToArray(); - - Assert.IsEmpty(results, "No results should be found!"); - } - - [Test] - public void SkipWordBorder() - { - var strategy = SearchStrategyFactory.Create("AllTests", false, true, SearchMode.Normal); - var text = new StringTextSource("name=\"{FindAllTests}\""); - var results = strategy.FindAll(text, 0, text.TextLength).ToArray(); - - Assert.IsEmpty(results, "No results should be found!"); - } - - [Test] - public void SkipWordBorder2() - { - var strategy = SearchStrategyFactory.Create("AllTests", false, true, SearchMode.Normal); - var text = new StringTextSource("name=\"FindAllTests "); - var results = strategy.FindAll(text, 0, text.TextLength).ToArray(); - - Assert.IsEmpty(results, "No results should be found!"); - } - - [Test] - public void SkipWordBorder3() - { - var strategy = SearchStrategyFactory.Create("// find", false, true, SearchMode.Normal); - var text = new StringTextSource(" // findtest"); - var results = strategy.FindAll(text, 0, text.TextLength).ToArray(); - - Assert.IsEmpty(results, "No results should be found!"); - } - - [Test] - public void WordBorderTest() - { - var strategy = SearchStrategyFactory.Create("// find", false, true, SearchMode.Normal); - var text = new StringTextSource(" // find me"); - var results = strategy.FindAll(text, 0, text.TextLength).ToArray(); - - Assert.AreEqual(1, results.Length, "One result should be found!"); - Assert.AreEqual(" ".Length, results[0].Offset); - Assert.AreEqual("// find".Length, results[0].Length); - } - - [Test] - public void ResultAtStart() - { - var strategy = SearchStrategyFactory.Create("result", false, true, SearchMode.Normal); - var text = new StringTextSource("result // find me"); - var results = strategy.FindAll(text, 0, text.TextLength).ToArray(); - - Assert.AreEqual(1, results.Length, "One result should be found!"); - Assert.AreEqual(0, results[0].Offset); - Assert.AreEqual("result".Length, results[0].Length); - } - - [Test] - public void ResultAtEnd() - { - var strategy = SearchStrategyFactory.Create("me", false, true, SearchMode.Normal); - var text = new StringTextSource("result // find me"); - var results = strategy.FindAll(text, 0, text.TextLength).ToArray(); - - Assert.AreEqual(1, results.Length, "One result should be found!"); - Assert.AreEqual("result // find ".Length, results[0].Offset); - Assert.AreEqual("me".Length, results[0].Length); - } - - [Test] - public void TextWithDots() - { - var strategy = SearchStrategyFactory.Create("Text", false, true, SearchMode.Normal); - var text = new StringTextSource(".Text."); - var results = strategy.FindAll(text, 0, text.TextLength).ToArray(); - - Assert.AreEqual(1, results.Length, "One result should be found!"); - Assert.AreEqual(".".Length, results[0].Offset); - Assert.AreEqual("Text".Length, results[0].Length); - } - - [Test] - public void SimpleTest() - { - var strategy = SearchStrategyFactory.Create("AllTests", false, false, SearchMode.Normal); - var text = new StringTextSource("name=\"FindAllTests "); - var results = strategy.FindAll(text, 0, text.TextLength).ToArray(); - - Assert.AreEqual(1, results.Length, "One result should be found!"); - Assert.AreEqual("name=\"Find".Length, results[0].Offset); - Assert.AreEqual("AllTests".Length, results[0].Length); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/CaretNavigationTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/CaretNavigationTests.cs deleted file mode 100644 index ebc9c5a44..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/CaretNavigationTests.cs +++ /dev/null @@ -1,158 +0,0 @@ -// 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; -#if NREFACTORY -using ICSharpCode.NRefactory.Editor; -#endif -using NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Utils -{ - [TestFixture] - public class CaretNavigationTests - { - int GetNextCaretStop(string text, int offset, CaretPositioningMode mode) - { - return TextUtilities.GetNextCaretPosition(new StringTextSource(text), offset, LogicalDirection.Forward, mode); - } - - int GetPrevCaretStop(string text, int offset, CaretPositioningMode mode) - { - return TextUtilities.GetNextCaretPosition(new StringTextSource(text), offset, LogicalDirection.Backward, mode); - } - - [Test] - public void CaretStopInEmptyString() - { - Assert.AreEqual(0, GetNextCaretStop("", -1, CaretPositioningMode.Normal)); - Assert.AreEqual(-1, GetNextCaretStop("", 0, CaretPositioningMode.Normal)); - Assert.AreEqual(-1, GetPrevCaretStop("", 0, CaretPositioningMode.Normal)); - Assert.AreEqual(0, GetPrevCaretStop("", 1, CaretPositioningMode.Normal)); - - Assert.AreEqual(-1, GetNextCaretStop("", -1, CaretPositioningMode.WordStart)); - Assert.AreEqual(-1, GetNextCaretStop("", -1, CaretPositioningMode.WordBorder)); - Assert.AreEqual(-1, GetPrevCaretStop("", 1, CaretPositioningMode.WordStart)); - Assert.AreEqual(-1, GetPrevCaretStop("", 1, CaretPositioningMode.WordBorder)); - } - - [Test] - public void StartOfDocumentWithWordStart() - { - Assert.AreEqual(0, GetNextCaretStop("word", -1, CaretPositioningMode.Normal)); - Assert.AreEqual(0, GetNextCaretStop("word", -1, CaretPositioningMode.WordStart)); - Assert.AreEqual(0, GetNextCaretStop("word", -1, CaretPositioningMode.WordBorder)); - - Assert.AreEqual(0, GetPrevCaretStop("word", 1, CaretPositioningMode.Normal)); - Assert.AreEqual(0, GetPrevCaretStop("word", 1, CaretPositioningMode.WordStart)); - Assert.AreEqual(0, GetPrevCaretStop("word", 1, CaretPositioningMode.WordBorder)); - } - - [Test] - public void StartOfDocumentNoWordStart() - { - Assert.AreEqual(0, GetNextCaretStop(" word", -1, CaretPositioningMode.Normal)); - Assert.AreEqual(1, GetNextCaretStop(" word", -1, CaretPositioningMode.WordStart)); - Assert.AreEqual(1, GetNextCaretStop(" word", -1, CaretPositioningMode.WordBorder)); - - Assert.AreEqual(0, GetPrevCaretStop(" word", 1, CaretPositioningMode.Normal)); - Assert.AreEqual(-1, GetPrevCaretStop(" word", 1, CaretPositioningMode.WordStart)); - Assert.AreEqual(-1, GetPrevCaretStop(" word", 1, CaretPositioningMode.WordBorder)); - } - - [Test] - public void EndOfDocumentWordBorder() - { - Assert.AreEqual(4, GetNextCaretStop("word", 3, CaretPositioningMode.Normal)); - Assert.AreEqual(-1, GetNextCaretStop("word", 3, CaretPositioningMode.WordStart)); - Assert.AreEqual(4, GetNextCaretStop("word", 3, CaretPositioningMode.WordBorder)); - - Assert.AreEqual(4, GetPrevCaretStop("word", 5, CaretPositioningMode.Normal)); - Assert.AreEqual(0, GetPrevCaretStop("word", 5, CaretPositioningMode.WordStart)); - Assert.AreEqual(4, GetPrevCaretStop("word", 5, CaretPositioningMode.WordBorder)); - } - - [Test] - public void EndOfDocumentNoWordBorder() - { - Assert.AreEqual(4, GetNextCaretStop("txt ", 3, CaretPositioningMode.Normal)); - Assert.AreEqual(-1, GetNextCaretStop("txt ", 3, CaretPositioningMode.WordStart)); - Assert.AreEqual(-1, GetNextCaretStop("txt ", 3, CaretPositioningMode.WordBorder)); - - Assert.AreEqual(4, GetPrevCaretStop("txt ", 5, CaretPositioningMode.Normal)); - Assert.AreEqual(0, GetPrevCaretStop("txt ", 5, CaretPositioningMode.WordStart)); - Assert.AreEqual(3, GetPrevCaretStop("txt ", 5, CaretPositioningMode.WordBorder)); - } - - [Test] - public void SingleCharacterOutsideBMP() - { - string c = "\U0001D49E"; - Assert.AreEqual(2, GetNextCaretStop(c, 0, CaretPositioningMode.Normal)); - Assert.AreEqual(0, GetPrevCaretStop(c, 2, CaretPositioningMode.Normal)); - } - - [Test] - public void DetectWordBordersOutsideBMP() - { - string c = " a\U0001D49Eb "; - Assert.AreEqual(1, GetNextCaretStop(c, 0, CaretPositioningMode.WordBorder)); - Assert.AreEqual(5, GetNextCaretStop(c, 1, CaretPositioningMode.WordBorder)); - - Assert.AreEqual(5, GetPrevCaretStop(c, 6, CaretPositioningMode.WordBorder)); - Assert.AreEqual(1, GetPrevCaretStop(c, 5, CaretPositioningMode.WordBorder)); - } - - [Test] - public void DetectWordBordersOutsideBMP2() - { - string c = " \U0001D49E\U0001D4AA "; - Assert.AreEqual(1, GetNextCaretStop(c, 0, CaretPositioningMode.WordBorder)); - Assert.AreEqual(5, GetNextCaretStop(c, 1, CaretPositioningMode.WordBorder)); - - Assert.AreEqual(5, GetPrevCaretStop(c, 6, CaretPositioningMode.WordBorder)); - Assert.AreEqual(1, GetPrevCaretStop(c, 5, CaretPositioningMode.WordBorder)); - } - - [Test] - public void CombiningMark() - { - string str = " x͆ "; - Assert.AreEqual(3, GetNextCaretStop(str, 1, CaretPositioningMode.Normal)); - Assert.AreEqual(1, GetPrevCaretStop(str, 3, CaretPositioningMode.Normal)); - } - - [Test] - public void StackedCombiningMark() - { - string str = " x͆͆͆͆ "; - Assert.AreEqual(6, GetNextCaretStop(str, 1, CaretPositioningMode.Normal)); - Assert.AreEqual(1, GetPrevCaretStop(str, 6, CaretPositioningMode.Normal)); - } - - [Test] - public void SingleClosingBraceAtLineEnd() - { - string str = "\t\t}"; - Assert.AreEqual(2, GetNextCaretStop(str, 1, CaretPositioningMode.WordStart)); - Assert.AreEqual(-1, GetPrevCaretStop(str, 1, CaretPositioningMode.WordStart)); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/CompressingTreeListTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/CompressingTreeListTests.cs deleted file mode 100644 index f6e2c038a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/CompressingTreeListTests.cs +++ /dev/null @@ -1,146 +0,0 @@ -// 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 NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Utils -{ - [TestFixture] - public class CompressingTreeListTests - { - [Test] - public void EmptyTreeList() - { - CompressingTreeList list = new CompressingTreeList(string.Equals); - Assert.AreEqual(0, list.Count); - foreach (string v in list) { - Assert.Fail(); - } - string[] arr = new string[0]; - list.CopyTo(arr, 0); - } - - [Test] - public void CheckAdd10BillionElements() - { - const int billion = 1000000000; - CompressingTreeList list = new CompressingTreeList(string.Equals); - list.InsertRange(0, billion, "A"); - list.InsertRange(1, billion, "B"); - Assert.AreEqual(2 * billion, list.Count); - Assert.Throws(delegate { list.InsertRange(2, billion, "C"); }); - } - - [Test] - public void AddRepeated() - { - CompressingTreeList list = new CompressingTreeList((a, b) => a == b); - list.Add(42); - list.Add(42); - list.Add(42); - list.Insert(0, 42); - list.Insert(1, 42); - Assert.AreEqual(new[] { 42, 42, 42, 42, 42 }, list.ToArray()); - } - - [Test] - public void RemoveRange() - { - CompressingTreeList list = new CompressingTreeList((a, b) => a == b); - for (int i = 1; i <= 3; i++) { - list.InsertRange(list.Count, 2, i); - } - Assert.AreEqual(new[] { 1, 1, 2, 2, 3, 3 }, list.ToArray()); - list.RemoveRange(1, 4); - Assert.AreEqual(new[] { 1, 3 }, list.ToArray()); - list.Insert(1, 1); - list.InsertRange(2, 2, 2); - list.Insert(4, 1); - Assert.AreEqual(new[] { 1, 1, 2, 2, 1, 3 }, list.ToArray()); - list.RemoveRange(2, 2); - Assert.AreEqual(new[] { 1, 1, 1, 3 }, list.ToArray()); - } - - [Test] - public void RemoveAtEnd() - { - CompressingTreeList list = new CompressingTreeList((a, b) => a == b); - for (int i = 1; i <= 3; i++) { - list.InsertRange(list.Count, 2, i); - } - Assert.AreEqual(new[] { 1, 1, 2, 2, 3, 3 }, list.ToArray()); - list.RemoveRange(3, 3); - Assert.AreEqual(new[] { 1, 1, 2 }, list.ToArray()); - } - - [Test] - public void RemoveAtStart() - { - CompressingTreeList list = new CompressingTreeList((a, b) => a == b); - for (int i = 1; i <= 3; i++) { - list.InsertRange(list.Count, 2, i); - } - Assert.AreEqual(new[] { 1, 1, 2, 2, 3, 3 }, list.ToArray()); - list.RemoveRange(0, 1); - Assert.AreEqual(new[] { 1, 2, 2, 3, 3 }, list.ToArray()); - } - - [Test] - public void RemoveAtStart2() - { - CompressingTreeList list = new CompressingTreeList((a, b) => a == b); - for (int i = 1; i <= 3; i++) { - list.InsertRange(list.Count, 2, i); - } - Assert.AreEqual(new[] { 1, 1, 2, 2, 3, 3 }, list.ToArray()); - list.RemoveRange(0, 3); - Assert.AreEqual(new[] { 2, 3, 3 }, list.ToArray()); - } - - [Test] - public void Transform() - { - CompressingTreeList list = new CompressingTreeList((a, b) => a == b); - list.AddRange(new[] { 0, 1, 1, 0 }); - int calls = 0; - list.Transform(i => { calls++; return i + 1; }); - Assert.AreEqual(3, calls); - Assert.AreEqual(new[] { 1, 2, 2, 1 }, list.ToArray()); - } - - [Test] - public void TransformToZero() - { - CompressingTreeList list = new CompressingTreeList((a, b) => a == b); - list.AddRange(new[] { 0, 1, 1, 0 }); - list.Transform(i => 0); - Assert.AreEqual(new[] { 0, 0, 0, 0 }, list.ToArray()); - } - - [Test] - public void TransformRange() - { - CompressingTreeList list = new CompressingTreeList((a, b) => a == b); - list.AddRange(new[] { 0, 1, 1, 1, 0, 0 }); - list.TransformRange(2, 3, i => 0); - Assert.AreEqual(new[] { 0, 1, 0, 0, 0, 0 }, list.ToArray()); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/ExtensionMethodsTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/ExtensionMethodsTests.cs deleted file mode 100644 index 9f77f6814..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/ExtensionMethodsTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -// 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 NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Utils -{ - [TestFixture] - public class ExtensionMethodsTests - { - [Test] - public void ZeroIsNotCloseToOne() - { - Assert.IsFalse(0.0.IsClose(1)); - } - - [Test] - public void ZeroIsCloseToZero() - { - Assert.IsTrue(0.0.IsClose(0)); - } - - [Test] - public void InfinityIsCloseToInfinity() - { - Assert.IsTrue(double.PositiveInfinity.IsClose(double.PositiveInfinity)); - } - - [Test] - public void NaNIsNotCloseToNaN() - { - Assert.IsFalse(double.NaN.IsClose(double.NaN)); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/IndentationStringTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/IndentationStringTests.cs deleted file mode 100644 index a580791da..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/IndentationStringTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -// 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 NUnit.Framework; - -namespace ICSharpCode.AvalonEdit.Utils -{ - [TestFixture] - public class IndentationStringTests - { - [Test] - public void IndentWithSingleTab() - { - var options = new TextEditorOptions { IndentationSize = 4, ConvertTabsToSpaces = false }; - Assert.AreEqual("\t", options.IndentationString); - Assert.AreEqual("\t", options.GetIndentationString(2)); - Assert.AreEqual("\t", options.GetIndentationString(3)); - Assert.AreEqual("\t", options.GetIndentationString(4)); - Assert.AreEqual("\t", options.GetIndentationString(5)); - Assert.AreEqual("\t", options.GetIndentationString(6)); - } - - [Test] - public void IndentWith4Spaces() - { - var options = new TextEditorOptions { IndentationSize = 4, ConvertTabsToSpaces = true }; - Assert.AreEqual(" ", options.IndentationString); - Assert.AreEqual(" ", options.GetIndentationString(2)); - Assert.AreEqual(" ", options.GetIndentationString(3)); - Assert.AreEqual(" ", options.GetIndentationString(4)); - Assert.AreEqual(" ", options.GetIndentationString(5)); - Assert.AreEqual(" ", options.GetIndentationString(6)); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/RopeTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/RopeTests.cs deleted file mode 100644 index 21e6c573b..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/Utils/RopeTests.cs +++ /dev/null @@ -1,195 +0,0 @@ -// 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 NUnit.Framework; -using System.Text; - -namespace ICSharpCode.AvalonEdit.Utils -{ - [TestFixture] - public class RopeTests - { - [Test] - public void EmptyRope() - { - Rope empty = new Rope(); - Assert.AreEqual(0, empty.Length); - Assert.AreEqual("", empty.ToString()); - } - - [Test] - public void EmptyRopeFromString() - { - Rope empty = new Rope(string.Empty); - Assert.AreEqual(0, empty.Length); - Assert.AreEqual("", empty.ToString()); - } - - [Test] - public void InitializeRopeFromShortString() - { - Rope rope = new Rope("Hello, World"); - Assert.AreEqual(12, rope.Length); - Assert.AreEqual("Hello, World", rope.ToString()); - } - - string BuildLongString(int lines) - { - StringWriter w = new StringWriter(); - w.NewLine = "\n"; - for (int i = 1; i <= lines; i++) { - w.WriteLine(i.ToString()); - } - return w.ToString(); - } - - [Test] - public void InitializeRopeFromLongString() - { - string text = BuildLongString(1000); - Rope rope = new Rope(text); - Assert.AreEqual(text.Length, rope.Length); - Assert.AreEqual(text, rope.ToString()); - Assert.AreEqual(text.ToCharArray(), rope.ToArray()); - } - - [Test] - public void TestToArrayAndToStringWithParts() - { - string text = BuildLongString(1000); - Rope rope = new Rope(text); - - string textPart = text.Substring(1200, 600); - char[] arrayPart = textPart.ToCharArray(); - Assert.AreEqual(textPart, rope.ToString(1200, 600)); - Assert.AreEqual(arrayPart, rope.ToArray(1200, 600)); - - Rope partialRope = rope.GetRange(1200, 600); - Assert.AreEqual(textPart, partialRope.ToString()); - Assert.AreEqual(arrayPart, partialRope.ToArray()); - } - - [Test] - public void ConcatenateStringToRope() - { - StringBuilder b = new StringBuilder(); - Rope rope = new Rope(); - for (int i = 1; i <= 1000; i++) { - b.Append(i.ToString()); - rope.AddText(i.ToString()); - b.Append(' '); - rope.Add(' '); - } - Assert.AreEqual(b.ToString(), rope.ToString()); - } - - [Test] - public void ConcatenateSmallRopesToRope() - { - StringBuilder b = new StringBuilder(); - Rope rope = new Rope(); - for (int i = 1; i <= 1000; i++) { - b.Append(i.ToString()); - b.Append(' '); - rope.AddRange(CharRope.Create(i.ToString() + " ")); - } - Assert.AreEqual(b.ToString(), rope.ToString()); - } - - [Test] - public void AppendLongTextToEmptyRope() - { - string text = BuildLongString(1000); - Rope rope = new Rope(); - rope.AddText(text); - Assert.AreEqual(text, rope.ToString()); - } - - [Test] - public void ConcatenateStringToRopeBackwards() - { - StringBuilder b = new StringBuilder(); - Rope rope = new Rope(); - for (int i = 1; i <= 1000; i++) { - b.Append(i.ToString()); - b.Append(' '); - } - for (int i = 1000; i >= 1; i--) { - rope.Insert(0, ' '); - rope.InsertText(0, i.ToString()); - } - Assert.AreEqual(b.ToString(), rope.ToString()); - } - - [Test] - public void ConcatenateSmallRopesToRopeBackwards() - { - StringBuilder b = new StringBuilder(); - Rope rope = new Rope(); - for (int i = 1; i <= 1000; i++) { - b.Append(i.ToString()); - b.Append(' '); - } - for (int i = 1000; i >= 1; i--) { - rope.InsertRange(0, CharRope.Create(i.ToString() + " ")); - } - Assert.AreEqual(b.ToString(), rope.ToString()); - } - - [Test] - public void ConcatenateStringToRopeByInsertionInMiddle() - { - StringBuilder b = new StringBuilder(); - Rope rope = new Rope(); - for (int i = 1; i <= 998; i++) { - b.Append(i.ToString("d3")); - b.Append(' '); - } - int middle = 0; - for (int i = 1; i <= 499; i++) { - rope.InsertText(middle, i.ToString("d3")); - middle += 3; - rope.Insert(middle, ' '); - middle++; - rope.InsertText(middle, (999-i).ToString("d3")); - rope.Insert(middle + 3, ' '); - } - Assert.AreEqual(b.ToString(), rope.ToString()); - } - - [Test] - public void ConcatenateSmallRopesByInsertionInMiddle() - { - StringBuilder b = new StringBuilder(); - Rope rope = new Rope(); - for (int i = 1; i <= 1000; i++) { - b.Append(i.ToString("d3")); - b.Append(' '); - } - int middle = 0; - for (int i = 1; i <= 500; i++) { - rope.InsertRange(middle, CharRope.Create(i.ToString("d3") + " ")); - middle += 4; - rope.InsertRange(middle, CharRope.Create((1001-i).ToString("d3") + " ")); - } - Assert.AreEqual(b.ToString(), rope.ToString()); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/WeakReferenceTests.cs b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/WeakReferenceTests.cs deleted file mode 100644 index 5f1ce4e47..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/WeakReferenceTests.cs +++ /dev/null @@ -1,127 +0,0 @@ -// 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.Threading; -using ICSharpCode.AvalonEdit.Document; -using ICSharpCode.AvalonEdit.Editing; -using ICSharpCode.AvalonEdit.Rendering; -using NUnit.Framework; - -namespace ICSharpCode.AvalonEdit -{ - [TestFixture] - public class WeakReferenceTests - { - [Test] - public void TextViewCanBeCollectedTest() - { - TextView textView = new TextView(); - WeakReference wr = new WeakReference(textView); - textView = null; - GarbageCollect(); - Assert.IsFalse(wr.IsAlive); - } - - [Test] - public void DocumentDoesNotHoldReferenceToTextView() - { - TextDocument textDocument = new TextDocument(); - Assert.AreEqual(0, textDocument.LineTrackers.Count); - - TextView textView = new TextView(); - WeakReference wr = new WeakReference(textView); - textView.Document = textDocument; - Assert.AreEqual(1, textDocument.LineTrackers.Count); - textView = null; - - GarbageCollect(); - Assert.IsFalse(wr.IsAlive); - // document cannot immediately clear the line tracker - Assert.AreEqual(1, textDocument.LineTrackers.Count); - - // but it should clear it on the next change - textDocument.Insert(0, "a"); - Assert.AreEqual(0, textDocument.LineTrackers.Count); - } - - [Test] - public void DocumentDoesNotHoldReferenceToTextArea() - { - TextDocument textDocument = new TextDocument(); - - TextArea textArea = new TextArea(); - WeakReference wr = new WeakReference(textArea); - textArea.Document = textDocument; - textArea = null; - - GarbageCollect(); - Assert.IsFalse(wr.IsAlive); - GC.KeepAlive(textDocument); - } - - [Test] - public void DocumentDoesNotHoldReferenceToTextEditor() - { - TextDocument textDocument = new TextDocument(); - - TextEditor textEditor = new TextEditor(); - WeakReference wr = new WeakReference(textEditor); - textEditor.Document = textDocument; - textEditor = null; - - GarbageCollect(); - Assert.IsFalse(wr.IsAlive); - GC.KeepAlive(textDocument); - } - - [Test] - public void DocumentDoesNotHoldReferenceToLineMargin() - { - TextDocument textDocument = new TextDocument(); - - WeakReference wr = DocumentDoesNotHoldReferenceToLineMargin_CreateMargin(textDocument); - - GarbageCollect(); - Assert.IsFalse(wr.IsAlive); - GC.KeepAlive(textDocument); - } - - // using a method to ensure the local variables can be garbage collected after the method returns - WeakReference DocumentDoesNotHoldReferenceToLineMargin_CreateMargin(TextDocument textDocument) - { - TextView textView = new TextView() { - Document = textDocument - }; - LineNumberMargin margin = new LineNumberMargin() { - TextView = textView - }; - return new WeakReference(textView); - } - - static void GarbageCollect() - { - for (int i = 0; i < 3; i++) { - GC.WaitForPendingFinalizers(); - GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); - // pump WPF messages so that WeakEventManager can unregister - Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new Action(delegate {})); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/packages.config b/AvalonEdit/ICSharpCode.AvalonEdit.Tests/packages.config deleted file mode 100644 index ad37a5282..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit.Tests/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/AvalonEditCommands.cs b/AvalonEdit/ICSharpCode.AvalonEdit/AvalonEditCommands.cs deleted file mode 100644 index 90a34077a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/AvalonEditCommands.cs +++ /dev/null @@ -1,102 +0,0 @@ -// 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 -{ - /// - /// Custom commands for AvalonEdit. - /// - public static class AvalonEditCommands - { - /// - /// Deletes the current line. - /// The default shortcut is Ctrl+D. - /// - public static readonly RoutedCommand DeleteLine = new RoutedCommand( - "DeleteLine", typeof(TextEditor), - new InputGestureCollection { - new KeyGesture(Key.D, ModifierKeys.Control) - }); - - /// - /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace", - Justification = "WPF uses 'Whitespace'")] - public static readonly RoutedCommand RemoveLeadingWhitespace = new RoutedCommand("RemoveLeadingWhitespace", typeof(TextEditor)); - - /// - /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace", - Justification = "WPF uses 'Whitespace'")] - public static readonly RoutedCommand RemoveTrailingWhitespace = new RoutedCommand("RemoveTrailingWhitespace", typeof(TextEditor)); - - /// - /// Converts the selected text to upper case. - /// - public static readonly RoutedCommand ConvertToUppercase = new RoutedCommand("ConvertToUppercase", typeof(TextEditor)); - - /// - /// Converts the selected text to lower case. - /// - public static readonly RoutedCommand ConvertToLowercase = new RoutedCommand("ConvertToLowercase", typeof(TextEditor)); - - /// - /// Converts the selected text to title case. - /// - public static readonly RoutedCommand ConvertToTitleCase = new RoutedCommand("ConvertToTitleCase", typeof(TextEditor)); - - /// - /// Inverts the case of the selected text. - /// - public static readonly RoutedCommand InvertCase = new RoutedCommand("InvertCase", typeof(TextEditor)); - - /// - /// Converts tabs to spaces in the selected text. - /// - public static readonly RoutedCommand ConvertTabsToSpaces = new RoutedCommand("ConvertTabsToSpaces", typeof(TextEditor)); - - /// - /// Converts spaces to tabs in the selected text. - /// - public static readonly RoutedCommand ConvertSpacesToTabs = new RoutedCommand("ConvertSpacesToTabs", typeof(TextEditor)); - - /// - /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). - /// - public static readonly RoutedCommand ConvertLeadingTabsToSpaces = new RoutedCommand("ConvertLeadingTabsToSpaces", typeof(TextEditor)); - - /// - /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). - /// - public static readonly RoutedCommand ConvertLeadingSpacesToTabs = new RoutedCommand("ConvertLeadingSpacesToTabs", typeof(TextEditor)); - - /// - /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). - /// - public static readonly RoutedCommand IndentSelection = new RoutedCommand( - "IndentSelection", typeof(TextEditor), - new InputGestureCollection { - new KeyGesture(Key.I, ModifierKeys.Control) - }); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionList.cs b/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionList.cs deleted file mode 100644 index 9be061a33..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionList.cs +++ /dev/null @@ -1,416 +0,0 @@ -// 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 -{ - /// - /// The listbox used inside the CompletionWindow, contains CompletionListBox. - /// - public class CompletionList : Control - { - static CompletionList() - { - DefaultStyleKeyProperty.OverrideMetadata(typeof(CompletionList), - new FrameworkPropertyMetadata(typeof(CompletionList))); - } - - bool isFiltering = true; - /// - /// 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. - /// - public bool IsFiltering { - get { return isFiltering; } - set { isFiltering = value; } - } - - /// - /// Dependency property for . - /// - public static readonly DependencyProperty EmptyTemplateProperty = - DependencyProperty.Register("EmptyTemplate", typeof(ControlTemplate), typeof(CompletionList), - new FrameworkPropertyMetadata()); - - /// - /// Content of EmptyTemplate will be shown when CompletionList contains no items. - /// If EmptyTemplate is null, nothing will be shown. - /// - public ControlTemplate EmptyTemplate { - get { return (ControlTemplate)GetValue(EmptyTemplateProperty); } - set { SetValue(EmptyTemplateProperty, value); } - } - - /// - /// Is raised when the completion list indicates that the user has chosen - /// an entry to be completed. - /// - public event EventHandler InsertionRequested; - - /// - /// Raises the InsertionRequested event. - /// - public void RequestInsertion(EventArgs e) - { - if (InsertionRequested != null) - InsertionRequested(this, e); - } - - CompletionListBox listBox; - - /// - public override void OnApplyTemplate() - { - base.OnApplyTemplate(); - - listBox = GetTemplateChild("PART_ListBox") as CompletionListBox; - if (listBox != null) { - listBox.ItemsSource = completionData; - } - } - - /// - /// Gets the list box. - /// - public CompletionListBox ListBox { - get { - if (listBox == null) - ApplyTemplate(); - return listBox; - } - } - - /// - /// Gets the scroll viewer used in this list box. - /// - public ScrollViewer ScrollViewer { - get { return listBox != null ? listBox.scrollViewer : null; } - } - - ObservableCollection completionData = new ObservableCollection(); - - /// - /// Gets the list to which completion data can be added. - /// - public IList CompletionData { - get { return completionData; } - } - - /// - protected override void OnKeyDown(KeyEventArgs e) - { - base.OnKeyDown(e); - if (!e.Handled) { - HandleKey(e); - } - } - - /// - /// Handles a key press. Used to let the completion list handle key presses while the - /// focus is still on the text editor. - /// - 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; - } - } - - /// - 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); - } - } - } - - /// - /// Gets/Sets the selected item. - /// - /// - /// The setter of this property does not scroll to the selected item. - /// You might want to also call . - /// - public ICompletionData SelectedItem { - get { - return (listBox != null ? listBox.SelectedItem : null) as ICompletionData; - } - set { - if (listBox == null && value != null) - ApplyTemplate(); - if (listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null - listBox.SelectedItem = value; - } - } - - /// - /// Scrolls the specified item into view. - /// - public void ScrollIntoView(ICompletionData item) - { - if (listBox == null) - ApplyTemplate(); - if (listBox != null) - listBox.ScrollIntoView(item); - } - - /// - /// Occurs when the SelectedItem property changes. - /// - 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 currentList; - - /// - /// Selects the best match, and filter the items if turned on using . - /// - public void SelectItem(string text) - { - if (text == currentText) - return; - if (listBox == null) - ApplyTemplate(); - - if (this.IsFiltering) { - SelectItemFiltering(text); - } - else { - SelectItemWithStart(text); - } - currentText = text; - } - - /// - /// Filters CompletionList items to show only those matching given query, and selects the best match. - /// - 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(); - 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); - } - - /// - /// Selects the item that starts with the specified query. - /// - 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionList.xaml b/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionList.xaml deleted file mode 100644 index bf49cc0b6..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionList.xaml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionListBox.cs b/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionListBox.cs deleted file mode 100644 index 0b625425a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionListBox.cs +++ /dev/null @@ -1,111 +0,0 @@ -// 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 -{ - /// - /// The list box used inside the CompletionList. - /// - public class CompletionListBox : ListBox - { - internal ScrollViewer scrollViewer; - - /// - 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; - } - } - - /// - /// Gets the number of the first visible item. - /// - 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); - } - } - } - - /// - /// Gets the number of visible items. - /// - 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)); - } - } - } - - /// - /// Removes the selection. - /// - public void ClearSelection() - { - this.SelectedIndex = -1; - } - - /// - /// Selects the item with the specified index and scrolls it into view. - /// - 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); - } - - /// - /// Centers the view on the item with the specified index. - /// - public void CenterViewOn(int index) - { - this.FirstVisibleItem = index - VisibleItemCount / 2; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionWindow.cs b/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionWindow.cs deleted file mode 100644 index bf1c8ac67..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionWindow.cs +++ /dev/null @@ -1,210 +0,0 @@ -// 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.Controls.Primitives; -using System.Windows.Input; -using ICSharpCode.AvalonEdit.Document; -using ICSharpCode.AvalonEdit.Editing; - -namespace ICSharpCode.AvalonEdit.CodeCompletion -{ - /// - /// The code completion window. - /// - public class CompletionWindow : CompletionWindowBase - { - readonly CompletionList completionList = new CompletionList(); - ToolTip toolTip = new ToolTip(); - - /// - /// Gets the completion list used in this completion window. - /// - public CompletionList CompletionList { - get { return completionList; } - } - - /// - /// Creates a new code completion window. - /// - 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; - } - - /// - 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(); - } - - /// - protected override void OnClosed(EventArgs e) - { - base.OnClosed(e); - if (toolTip != null) { - toolTip.IsOpen = false; - toolTip = null; - } - } - - /// - 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; - } - - /// - /// Gets/Sets whether the completion window should close automatically. - /// The default value is true. - /// - public bool CloseAutomatically { get; set; } - - /// - protected override bool CloseOnFocusLost { - get { return this.CloseAutomatically; } - } - - /// - /// 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. - /// - 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)); - } - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionWindowBase.cs b/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionWindowBase.cs deleted file mode 100644 index ee6048eb0..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/CompletionWindowBase.cs +++ /dev/null @@ -1,397 +0,0 @@ -// 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 -{ - /// - /// Base class for completion windows. Handles positioning the window at the caret. - /// - 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)); - } - - /// - /// Gets the parent TextArea. - /// - public TextArea TextArea { get; private set; } - - Window parentWindow; - TextDocument document; - - /// - /// 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. - /// - public int StartOffset { get; set; } - - /// - /// 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. - /// - public int EndOffset { get; set; } - - /// - /// Gets whether the window was opened above the current line. - /// - protected bool IsUp { get; private set; } - - /// - /// Creates a new CompletionWindowBase. - /// - 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()) { - if (x.window.GetType() == this.GetType()) - this.TextArea.PopStackedInputHandler(x); - } - - myInputHandler = new InputHandler(this); - this.TextArea.PushStackedInputHandler(myInputHandler); - } - - /// - /// Detaches events from the text area. - /// - 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; - - /// - /// 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. - /// - 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(); - } - - /// - protected override void OnDeactivated(EventArgs e) - { - base.OnDeactivated(e); - Dispatcher.BeginInvoke(new Action(CloseIfFocusLost), DispatcherPriority.Background); - } - #endregion - - /// - /// Raises a tunnel/bubble event pair for a WPF control. - /// - /// The WPF control for which the event should be raised. - /// The tunneling event. - /// The bubbling event. - /// The event args to use. - /// The value of the event args. - [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(); - } - - /// - /// Activates the parent window. - /// - 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(); - } - } - } - - /// - /// Gets whether the completion window should automatically close when the text editor looses focus. - /// - protected virtual bool CloseOnFocusLost { - get { return true; } - } - - bool IsTextAreaFocused { - get { - if (parentWindow != null && !parentWindow.IsActive) - return false; - return this.TextArea.IsKeyboardFocused; - } - } - - bool sourceIsInitialized; - - /// - 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; - } - - /// - protected override void OnClosed(EventArgs e) - { - base.OnClosed(e); - DetachEvents(); - } - - /// - protected override void OnKeyDown(KeyEventArgs e) - { - base.OnKeyDown(e); - if (!e.Handled && e.Key == Key.Escape) { - e.Handled = true; - Close(); - } - } - - Point visualLocation, visualLocationTop; - - /// - /// Positions the completion window at the specified position. - /// - protected void SetPosition(TextViewPosition position) - { - TextView textView = this.TextArea.TextView; - - visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); - visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); - UpdatePosition(); - } - - /// - /// 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. - /// - 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; - } - - /// - protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) - { - base.OnRenderSizeChanged(sizeInfo); - if (sizeInfo.HeightChanged && IsUp) { - this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; - } - } - - /// - /// Gets/sets whether the completion window should expect text insertion at the start offset, - /// which not go into the completion region, but before it. - /// - /// This property allows only a single insertion, it is reset to false - /// when that insertion has occurred. - 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/ICompletionData.cs b/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/ICompletionData.cs deleted file mode 100644 index 6d7daf78a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/ICompletionData.cs +++ /dev/null @@ -1,73 +0,0 @@ -// 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 -{ - /// - /// Describes an entry in the . - /// - public interface ICompletionData - { - /// - /// Gets the image. - /// - ImageSource Image { get; } - - /// - /// Gets the text. This property is used to filter the list of visible elements. - /// - string Text { get; } - - /// - /// The displayed content. This can be the same as 'Text', or a WPF UIElement if - /// you want to display rich content. - /// - object Content { get; } - - /// - /// Gets the description. - /// - object Description { get; } - - /// - /// 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. - /// - double Priority { get; } - - /// - /// Perform the completion. - /// - /// The text area on which completion is performed. - /// The text segment that was used by the completion window if - /// the user types (segment between CompletionWindow.StartOffset and CompletionWindow.EndOffset). - /// The EventArgs used for the insertion request. - /// These can be TextCompositionEventArgs, KeyEventArgs, MouseEventArgs, depending on how - /// the insertion was triggered. - void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/IOverloadProvider.cs b/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/IOverloadProvider.cs deleted file mode 100644 index a4c04d3c3..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/IOverloadProvider.cs +++ /dev/null @@ -1,57 +0,0 @@ -// 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 -{ - /// - /// Provides the items for the OverloadViewer. - /// - public interface IOverloadProvider : INotifyPropertyChanged - { - /// - /// Gets/Sets the selected index. - /// - int SelectedIndex { get; set; } - - /// - /// Gets the number of overloads. - /// - int Count { get; } - - /// - /// Gets the text 'SelectedIndex of Count'. - /// - string CurrentIndexText { get; } - - /// - /// Gets the current header. - /// - object CurrentHeader { get; } - - /// - /// Gets the current content. - /// - object CurrentContent { get; } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/InsightWindow.cs b/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/InsightWindow.cs deleted file mode 100644 index c0332e2a2..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/InsightWindow.cs +++ /dev/null @@ -1,109 +0,0 @@ -// 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 -{ - /// - /// A popup-like window that is attached to a text segment. - /// - public class InsightWindow : CompletionWindowBase - { - static InsightWindow() - { - DefaultStyleKeyProperty.OverrideMetadata(typeof(InsightWindow), - new FrameworkPropertyMetadata(typeof(InsightWindow))); - AllowsTransparencyProperty.OverrideMetadata(typeof(InsightWindow), - new FrameworkPropertyMetadata(Boxes.True)); - } - - /// - /// Creates a new InsightWindow. - /// - public InsightWindow(TextArea textArea) : base(textArea) - { - this.CloseAutomatically = true; - AttachEvents(); - } - - /// - 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); - } - - /// - /// Gets/Sets whether the insight window should close automatically. - /// The default value is true. - /// - public bool CloseAutomatically { get; set; } - - /// - protected override bool CloseOnFocusLost { - get { return this.CloseAutomatically; } - } - - void AttachEvents() - { - this.TextArea.Caret.PositionChanged += CaretPositionChanged; - } - - /// - 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(); - } - } - } - } - - /// - /// TemplateSelector for InsightWindow to replace plain string content by a TextBlock with TextWrapping. - /// - 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/InsightWindow.xaml b/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/InsightWindow.xaml deleted file mode 100644 index 5b925ef7e..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/InsightWindow.xaml +++ /dev/null @@ -1,118 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/OverloadInsightWindow.cs b/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/OverloadInsightWindow.cs deleted file mode 100644 index 2ec182ce4..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/OverloadInsightWindow.cs +++ /dev/null @@ -1,73 +0,0 @@ -// 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 -{ - /// - /// Insight window that shows an OverloadViewer. - /// - public class OverloadInsightWindow : InsightWindow - { - OverloadViewer overloadViewer = new OverloadViewer(); - - /// - /// Creates a new OverloadInsightWindow. - /// - public OverloadInsightWindow(TextArea textArea) : base(textArea) - { - overloadViewer.Margin = new Thickness(2,0,0,0); - this.Content = overloadViewer; - } - - /// - /// Gets/Sets the item provider. - /// - public IOverloadProvider Provider { - get { return overloadViewer.Provider; } - set { overloadViewer.Provider = value; } - } - - /// - protected override void OnKeyDown(KeyEventArgs e) - { - base.OnKeyDown(e); - if (!e.Handled && this.Provider != null && 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(); - } - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/OverloadViewer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/OverloadViewer.cs deleted file mode 100644 index 9f810f80c..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/CodeCompletion/OverloadViewer.cs +++ /dev/null @@ -1,116 +0,0 @@ -// 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 -{ - /// - /// Represents a text between "Up" and "Down" buttons. - /// - public class OverloadViewer : Control - { - static OverloadViewer() - { - DefaultStyleKeyProperty.OverrideMetadata(typeof(OverloadViewer), - new FrameworkPropertyMetadata(typeof(OverloadViewer))); - } - - /// - /// The text property. - /// - public static readonly DependencyProperty TextProperty = - DependencyProperty.Register("Text", typeof(string), typeof(OverloadViewer)); - - /// - /// Gets/Sets the text between the Up and Down buttons. - /// - public string Text { - get { return (string)GetValue(TextProperty); } - set { SetValue(TextProperty, value); } - } - - /// - 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); - }; - } - - /// - /// The ItemProvider property. - /// - public static readonly DependencyProperty ProviderProperty = - DependencyProperty.Register("Provider", typeof(IOverloadProvider), typeof(OverloadViewer)); - - /// - /// Gets/Sets the item provider. - /// - public IOverloadProvider Provider { - get { return (IOverloadProvider)GetValue(ProviderProperty); } - set { SetValue(ProviderProperty, value); } - } - - /// - /// Changes the selected index. - /// - /// The relative index change - usual values are +1 or -1. - 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(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentChangeEventArgs.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentChangeEventArgs.cs deleted file mode 100644 index df248941c..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentChangeEventArgs.cs +++ /dev/null @@ -1,123 +0,0 @@ -// 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 -{ - /// - /// Describes a change of the document text. - /// This class is thread-safe. - /// - [Serializable] - public class DocumentChangeEventArgs : TextChangeEventArgs - { - volatile OffsetChangeMap offsetChangeMap; - - /// - /// Gets the OffsetChangeMap associated with this document change. - /// - /// The OffsetChangeMap instance is guaranteed to be frozen and thus thread-safe. - 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); - } - - /// - /// Gets the OffsetChangeMap, or null if the default offset map (=single replacement) is being used. - /// - internal OffsetChangeMap OffsetChangeMapOrNull { - get { - return offsetChangeMap; - } - } - - /// - /// Gets the new offset where the specified offset moves after this document change. - /// - public override int GetNewOffset(int offset, AnchorMovementType movementType = AnchorMovementType.Default) - { - if (offsetChangeMap != null) - return offsetChangeMap.GetNewOffset(offset, movementType); - else - return CreateSingleChangeMapEntry().GetNewOffset(offset, movementType); - } - - /// - /// Creates a new DocumentChangeEventArgs object. - /// - public DocumentChangeEventArgs(int offset, string removedText, string insertedText) - : this(offset, removedText, insertedText, null) - { - } - - /// - /// Creates a new DocumentChangeEventArgs object. - /// - public DocumentChangeEventArgs(int offset, string removedText, string insertedText, OffsetChangeMap offsetChangeMap) - : base(offset, removedText, insertedText) - { - SetOffsetChangeMap(offsetChangeMap); - } - - /// - /// Creates a new DocumentChangeEventArgs object. - /// - 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; - } - } - - /// - 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentChangeOperation.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentChangeOperation.cs deleted file mode 100644 index 55717ac79..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentChangeOperation.cs +++ /dev/null @@ -1,67 +0,0 @@ -// 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 -{ - /// - /// Describes a change to a TextDocument. - /// - 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentLine.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentLine.cs deleted file mode 100644 index 68e6be95f..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentLine.cs +++ /dev/null @@ -1,268 +0,0 @@ -// 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 -{ - /// - /// Represents a line inside a . - /// - /// - /// - /// The 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. - /// - /// - /// 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. - /// - /// - 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 -// /// -// /// Is raised when the line is deleted. -// /// -// public event EventHandler Deleted; -// -// /// -// /// Is raised when the line's text changes. -// /// -// public event EventHandler TextChanged; -// -// /// -// /// Raises the Deleted or TextChanged event. -// /// -// 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 - /// - /// Gets if this line was deleted from the document. - /// - public bool IsDeleted { - get { - DebugVerifyAccess(); - return isDeleted; - } - } - - /// - /// Gets the number of this line. - /// Runtime: O(log n) - /// - /// The line was deleted. - public int LineNumber { - get { - if (IsDeleted) - throw new InvalidOperationException(); - return DocumentLineTree.GetIndexFromNode(this) + 1; - } - } - - /// - /// Gets the starting offset of the line in the document's text. - /// Runtime: O(log n) - /// - /// The line was deleted. - public int Offset { - get { - if (IsDeleted) - throw new InvalidOperationException(); - return DocumentLineTree.GetOffsetFromNode(this); - } - } - - /// - /// Gets the end offset of the line in the document's text (the offset before the line delimiter). - /// Runtime: O(log n) - /// - /// The line was deleted. - /// EndOffset = + . - public int EndOffset { - get { return this.Offset + this.Length; } - } - #endregion - - #region Length - int totalLength; - byte delimiterLength; - - /// - /// Gets the length of this line. The length does not include the line delimiter. O(1) - /// - /// This property is still available even if the line was deleted; - /// in that case, it contains the line's length before the deletion. - public int Length { - get { - DebugVerifyAccess(); - return totalLength - delimiterLength; - } - } - - /// - /// Gets the length of this line, including the line delimiter. O(1) - /// - /// This property is still available even if the line was deleted; - /// in that case, it contains the line's length before the deletion. - public int TotalLength { - get { - DebugVerifyAccess(); - return totalLength; - } - internal set { - // this is set by DocumentLineTree - totalLength = value; - } - } - - /// - /// Gets the length of the line delimiter. - /// The value is 1 for single "\r" or "\n", 2 for the "\r\n" sequence; - /// and 0 for the last line in the document. - /// - /// This property is still available even if the line was deleted; - /// in that case, it contains the line delimiter's length before the deletion. - public int DelimiterLength { - get { - DebugVerifyAccess(); - return delimiterLength; - } - internal set { - Debug.Assert(value >= 0 && value <= 2); - delimiterLength = (byte)value; - } - } - #endregion - - #region Previous / Next Line - /// - /// Gets the next line in the document. - /// - /// The line following this line, or null if this is the last line. - 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; - } - } - } - - /// - /// Gets the previous line in the document. - /// - /// The line before this line, or null if this is the first line. - 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 - /// - /// Gets a string with debug output showing the line number and offset. - /// Does not include the line's text. - /// - 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentLineTree.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentLineTree.cs deleted file mode 100644 index 17851f758..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentLineTree.cs +++ /dev/null @@ -1,727 +0,0 @@ -// 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; - - /// - /// Data structure for efficient management of the document lines (most operations are O(lg n)). - /// This implements an augmented red-black tree. - /// See for the augmented data. - /// - /// NOTE: The tree is never empty, initially it contains an empty line. - /// - sealed class DocumentLineTree : IList - { - #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 - /// - /// Rebuild the tree, in O(n). - /// - public void RebuildTree(List 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; - } - - /// - /// build a tree from a list of nodes - /// - 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.this[int index] { - get { - document.VerifyAccess(); - return GetByNumber(1 + index); - } - set { - throw new NotSupportedException(); - } - } - - int ICollection.Count { - get { - document.VerifyAccess(); - return LineCount; - } - } - - bool ICollection.IsReadOnly { - get { return true; } - } - - int IList.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.Insert(int index, DocumentLine item) - { - throw new NotSupportedException(); - } - - void IList.RemoveAt(int index) - { - throw new NotSupportedException(); - } - - void ICollection.Add(DocumentLine item) - { - throw new NotSupportedException(); - } - - void ICollection.Clear() - { - throw new NotSupportedException(); - } - - bool ICollection.Contains(DocumentLine item) - { - IList self = this; - return self.IndexOf(item) >= 0; - } - - void ICollection.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.Remove(DocumentLine item) - { - throw new NotSupportedException(); - } - - public IEnumerator GetEnumerator() - { - document.VerifyAccess(); - return Enumerate(); - } - - IEnumerator 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentTextWriter.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentTextWriter.cs deleted file mode 100644 index af058ecbb..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/DocumentTextWriter.cs +++ /dev/null @@ -1,86 +0,0 @@ -// 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 -{ - /// - /// A TextWriter implementation that directly inserts into a document. - /// - public class DocumentTextWriter : TextWriter - { - readonly IDocument document; - int insertionOffset; - - /// - /// Creates a new DocumentTextWriter that inserts into document, starting at insertionOffset. - /// - 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); - } - - /// - /// Gets/Sets the current insertion offset. - /// - public int InsertionOffset { - get { return insertionOffset; } - set { insertionOffset = value; } - } - - /// - public override void Write(char value) - { - document.Insert(insertionOffset, value.ToString()); - insertionOffset++; - } - - /// - public override void Write(char[] buffer, int index, int count) - { - document.Insert(insertionOffset, new string(buffer, index, count)); - insertionOffset += count; - } - - /// - public override void Write(string value) - { - document.Insert(insertionOffset, value); - insertionOffset += value.Length; - } - - /// - public override Encoding Encoding { - get { return Encoding.UTF8; } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/GapTextBuffer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/GapTextBuffer.cs deleted file mode 100644 index 0dd5f2166..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/GapTextBuffer.cs +++ /dev/null @@ -1,207 +0,0 @@ -// 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 -{ - /* - /// - /// Implementation of a gap text buffer. - /// - sealed class GapTextBuffer - { - char[] buffer = Empty.Array; - - /// - /// The current text content. - /// Is set to null whenever the buffer changes, and gets a value only when the - /// full text content is requested. - /// - string textContent; - - /// - /// last GetText result - /// - string lastGetTextResult; - int lastGetTextRequestOffset; - - int gapBeginOffset; - int gapEndOffset; - int gapLength; // gapLength == gapEndOffset - gapBeginOffset - - /// - /// 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. - /// - const int minGapLength = 128; - - /// - /// when the gap exceeds this size, reallocate a smaller buffer - /// - const int maxGapLength = 4096; - - public int Length { - get { - return buffer.Length - gapLength; - } - } - - /// - /// Gets the buffer content. - /// - 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; - } - - /// - /// Inserts text at the specified offset. - /// - 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; - } - - /// - /// Remove characters at . - /// Leave a gap of at least . - /// - 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; - } - } - */ -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/IDocument.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/IDocument.cs deleted file mode 100644 index 0b7e0c988..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/IDocument.cs +++ /dev/null @@ -1,343 +0,0 @@ -// 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 - /// - /// A document representing a source code file for refactoring. - /// Line and column counting starts at 1. - /// Offset counting starts at 0. - /// - public interface IDocument : ITextSource, IServiceProvider - { - #if NREFACTORY - /// - /// Creates an immutable snapshot of this document. - /// - IDocument CreateDocumentSnapshot(); - #endif - - /// - /// Gets/Sets the text of the whole document.. - /// - new string Text { get; set; } // hides ITextSource.Text to add the setter - - /// - /// This event is called directly before a change is applied to the document. - /// - /// - /// 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. - /// - event EventHandler TextChanging; - - /// - /// This event is called directly after a change is applied to the document. - /// - /// - /// 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. - /// - event EventHandler TextChanged; - - /// - /// This event is called after a group of changes is completed. - /// - /// - event EventHandler ChangeCompleted; - - /// - /// Gets the number of lines in the document. - /// - int LineCount { get; } - - /// - /// Gets the document line with the specified number. - /// - /// The number of the line to retrieve. The first line has number 1. - IDocumentLine GetLineByNumber(int lineNumber); - - /// - /// Gets the document line that contains the specified offset. - /// - IDocumentLine GetLineByOffset(int offset); - - /// - /// Gets the offset from a text location. - /// - /// - int GetOffset(int line, int column); - - /// - /// Gets the offset from a text location. - /// - /// - int GetOffset(TextLocation location); - - /// - /// Gets the location from an offset. - /// - /// - TextLocation GetLocation(int offset); - - /// - /// Inserts text. - /// - /// The offset at which the text is inserted. - /// The new text. - /// - /// 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. - /// - void Insert(int offset, string text); - - /// - /// Inserts text. - /// - /// The offset at which the text is inserted. - /// The new text. - /// - /// 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. - /// - void Insert(int offset, ITextSource text); - - /// - /// Inserts text. - /// - /// The offset at which the text is inserted. - /// The new text. - /// - /// 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 parameter. - /// - void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType); - - /// - /// Inserts text. - /// - /// The offset at which the text is inserted. - /// The new text. - /// - /// 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 parameter. - /// - void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType); - - /// - /// Removes text. - /// - /// Starting offset of the text to be removed. - /// Length of the text to be removed. - void Remove(int offset, int length); - - /// - /// Replaces text. - /// - /// The starting offset of the text to be replaced. - /// The length of the text to be replaced. - /// The new text. - void Replace(int offset, int length, string newText); - - /// - /// Replaces text. - /// - /// The starting offset of the text to be replaced. - /// The length of the text to be replaced. - /// The new text. - void Replace(int offset, int length, ITextSource newText); - - /// - /// Make the document combine the following actions into a single - /// action for undo purposes. - /// - void StartUndoableAction(); - - /// - /// Ends the undoable action started with . - /// - void EndUndoableAction(); - - /// - /// Creates an undo group. Dispose the returned value to close the undo group. - /// - /// An object that closes the undo group when Dispose() is called. - IDisposable OpenUndoGroup(); - - /// - /// Creates a new at the specified offset. - /// - /// - ITextAnchor CreateAnchor(int offset); - - /// - /// 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. - /// - string FileName { get; } - - /// - /// Fired when the file name of the document changes. - /// - event EventHandler FileNameChanged; - } - - /// - /// A line inside a . - /// - public interface IDocumentLine : ISegment - { - /// - /// Gets the length of this line, including the line delimiter. - /// - int TotalLength { get; } - - /// - /// Gets the length of the line terminator. - /// Returns 1 or 2; or 0 at the end of the document. - /// - int DelimiterLength { get; } - - /// - /// Gets the number of this line. - /// The first line has the number 1. - /// - int LineNumber { get; } - - /// - /// Gets the previous line. Returns null if this is the first line in the document. - /// - IDocumentLine PreviousLine { get; } - - /// - /// Gets the next line. Returns null if this is the last line in the document. - /// - IDocumentLine NextLine { get; } - - /// - /// Gets whether the line was deleted. - /// - bool IsDeleted { get; } - } - - /// - /// Describes a change of the document text. - /// This class is thread-safe. - /// - [Serializable] - public class TextChangeEventArgs : EventArgs - { - readonly int offset; - readonly ITextSource removedText; - readonly ITextSource insertedText; - - /// - /// The offset at which the change occurs. - /// - public int Offset { - get { return offset; } - } - - /// - /// The text that was removed. - /// - public ITextSource RemovedText { - get { return removedText; } - } - - /// - /// The number of characters removed. - /// - public int RemovalLength { - get { return removedText.TextLength; } - } - - /// - /// The text that was inserted. - /// - public ITextSource InsertedText { - get { return insertedText; } - } - - /// - /// The number of characters inserted. - /// - public int InsertionLength { - get { return insertedText.TextLength; } - } - - /// - /// Creates a new TextChangeEventArgs object. - /// - 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; - } - - /// - /// Creates a new TextChangeEventArgs object. - /// - 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; - } - - /// - /// Gets the new offset where the specified offset moves after this document change. - /// - 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; - } - } - - /// - /// Creates TextChangeEventArgs for the reverse change. - /// - public virtual TextChangeEventArgs Invert() - { - return new TextChangeEventArgs(offset, insertedText, removedText); - } - } - #endif -} \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/ILineTracker.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/ILineTracker.cs deleted file mode 100644 index be6c7a0b2..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/ILineTracker.cs +++ /dev/null @@ -1,77 +0,0 @@ -// 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 -{ - /// - /// Allows for low-level line tracking. - /// - /// - /// 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. - /// - public interface ILineTracker - { - /// - /// Is called immediately before a document line is removed. - /// - void BeforeRemoveLine(DocumentLine line); - -// /// -// /// Is called immediately after a document line is removed. -// /// -// void AfterRemoveLine(DocumentLine line); - - /// - /// 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. - /// - void SetLineLength(DocumentLine line, int newTotalLength); - - /// - /// Is called immediately after a line was inserted. - /// - /// The new line - /// The existing line before the new line - void LineInserted(DocumentLine insertionPos, DocumentLine newLine); - - /// - /// 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. - /// - void RebuildDocument(); - - /// - /// 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 event - /// is raised. - /// - void ChangeComplete(DocumentChangeEventArgs e); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/ITextAnchor.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/ITextAnchor.cs deleted file mode 100644 index ba8977f0f..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/ITextAnchor.cs +++ /dev/null @@ -1,142 +0,0 @@ -// 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 - /// - /// 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. - /// - /// - /// Use the property to get the offset from a text anchor. - /// Use the method to create an anchor from an offset. - /// - /// - /// 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. - /// - /// 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 property also runs in O(lg N). - /// - /// - /// Usage: - /// TextAnchor anchor = document.CreateAnchor(offset); - /// ChangeMyDocument(); - /// int newOffset = anchor.Offset; - /// - /// - public interface ITextAnchor - { - /// - /// Gets the text location of this anchor. - /// - /// Thrown when trying to get the Offset from a deleted anchor. - TextLocation Location { get; } - - /// - /// Gets the offset of the text anchor. - /// - /// Thrown when trying to get the Offset from a deleted anchor. - int Offset { get; } - - /// - /// Controls how the anchor moves. - /// - /// 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 will be used to determine which of these two options the anchor will choose. - /// The default value is . - AnchorMovementType MovementType { get; set; } - - /// - /// - /// Specifies whether the anchor survives deletion of the text containing it. - /// - /// false: The anchor is deleted when the a selection that includes the anchor is deleted. - /// true: The anchor is not deleted. - /// - /// - /// - bool SurviveDeletion { get; set; } - - /// - /// Gets whether the anchor was deleted. - /// - /// - /// When a piece of text containing an anchor is removed, then that anchor will be deleted. - /// First, the property is set to true on all deleted anchors, - /// then the events are raised. - /// You cannot retrieve the offset from an anchor that has been deleted. - /// 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 = true. - /// - bool IsDeleted { get; } - - /// - /// Occurs after the anchor was deleted. - /// - /// - /// - /// 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. - /// - /// - event EventHandler Deleted; - - /// - /// Gets the line number of the anchor. - /// - /// Thrown when trying to get the Offset from a deleted anchor. - int Line { get; } - - /// - /// Gets the column number of this anchor. - /// - /// Thrown when trying to get the Offset from a deleted anchor. - int Column { get; } - } - - /// - /// Defines how a text anchor moves. - /// - public enum AnchorMovementType - { - /// - /// 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. - /// - Default, - /// - /// Behaves like a start marker - when text is inserted at the anchor position, the anchor will stay - /// before the inserted text. - /// - BeforeInsertion, - /// - /// Behave like an end marker - when text is insered at the anchor position, the anchor will move - /// after the inserted text. - /// - AfterInsertion - } - #endif -} \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/ITextSource.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/ITextSource.cs deleted file mode 100644 index 33077fe41..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/ITextSource.cs +++ /dev/null @@ -1,357 +0,0 @@ -// 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 - /// - /// A read-only view on a (potentially mutable) text source. - /// The IDocument interface derives from this interface. - /// - public interface ITextSource - { - /// - /// Gets a version identifier for this text source. - /// Returns null for unversioned text sources. - /// - ITextSourceVersion Version { get; } - - /// - /// Creates an immutable snapshot of this text source. - /// Unlike all other methods in this interface, this method is thread-safe. - /// - ITextSource CreateSnapshot(); - - /// - /// Creates an immutable snapshot of a part of this text source. - /// Unlike all other methods in this interface, this method is thread-safe. - /// - ITextSource CreateSnapshot(int offset, int length); - - /// - /// Creates a new TextReader to read from this text source. - /// - TextReader CreateReader(); - - /// - /// Creates a new TextReader to read from this text source. - /// - TextReader CreateReader(int offset, int length); - - /// - /// Gets the total text length. - /// - /// The length of the text, in characters. - /// This is the same as Text.Length, but is more efficient because - /// it doesn't require creating a String object. - int TextLength { get; } - - /// - /// Gets the whole text as string. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] - string Text { get; } - - /// - /// Gets a character at the specified position in the document. - /// - /// The index of the character to get. - /// Offset is outside the valid range (0 to TextLength-1). - /// The character at the specified position. - /// This is the same as Text[offset], but is more efficient because - /// it doesn't require creating a String object. - char GetCharAt(int offset); - - /// - /// Retrieves the text for a portion of the document. - /// - /// offset or length is outside the valid range. - /// This is the same as Text.Substring, but is more efficient because - /// it doesn't require creating a String object for the whole document. - string GetText(int offset, int length); - - /// - /// Retrieves the text for a portion of the document. - /// - /// offset or length is outside the valid range. - string GetText(ISegment segment); - - /// - /// Writes the text from this document into the TextWriter. - /// - void WriteTextTo(TextWriter writer); - - /// - /// Writes the text from this document into the TextWriter. - /// - void WriteTextTo(TextWriter writer, int offset, int length); - - /// - /// Gets the index of the first occurrence of the character in the specified array. - /// - /// Character to search for - /// Start index of the area to search. - /// Length of the area to search. - /// The first index where the character was found; or -1 if no occurrence was found. - int IndexOf(char c, int startIndex, int count); - - /// - /// Gets the index of the first occurrence of any character in the specified array. - /// - /// Characters to search for - /// Start index of the area to search. - /// Length of the area to search. - /// The first index where any character was found; or -1 if no occurrence was found. - int IndexOfAny(char[] anyOf, int startIndex, int count); - - /// - /// Gets the index of the first occurrence of the specified search text in this text source. - /// - /// The search text - /// Start index of the area to search. - /// Length of the area to search. - /// String comparison to use. - /// The first index where the search term was found; or -1 if no occurrence was found. - int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType); - - /// - /// Gets the index of the last occurrence of the specified character in this text source. - /// - /// The search character - /// Start index of the area to search. - /// Length of the area to search. - /// The last index where the search term was found; or -1 if no occurrence was found. - /// The search proceeds backwards from (startIndex+count) to startIndex. - /// This is different than the meaning of the parameters on string.LastIndexOf! - int LastIndexOf(char c, int startIndex, int count); - - /// - /// Gets the index of the last occurrence of the specified search text in this text source. - /// - /// The search text - /// Start index of the area to search. - /// Length of the area to search. - /// String comparison to use. - /// The last index where the search term was found; or -1 if no occurrence was found. - /// The search proceeds backwards from (startIndex+count) to startIndex. - /// This is different than the meaning of the parameters on string.LastIndexOf! - 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 SearchForward (string pattern, int startIndex); - IEnumerable SearchForwardIgnoreCase (string pattern, int startIndex); - - IEnumerable SearchBackward (string pattern, int startIndex); - IEnumerable SearchBackwardIgnoreCase (string pattern, int startIndex); - */ - } - - /// - /// Represents a version identifier for a text source. - /// - /// - /// 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. - /// - public interface ITextSourceVersion - { - /// - /// Gets whether this checkpoint belongs to the same document as the other checkpoint. - /// - /// - /// Returns false when given null. - /// - bool BelongsToSameDocumentAs(ITextSourceVersion other); - - /// - /// Compares the age of this checkpoint to the other checkpoint. - /// - /// This method is thread-safe. - /// Raised if 'other' belongs to a different document than this version. - /// -1 if this version is older than . - /// 0 if this version instance represents the same version as . - /// 1 if this version is newer than . - int CompareAge(ITextSourceVersion other); - - /// - /// Gets the changes from this checkpoint to the other checkpoint. - /// If 'other' is older than this checkpoint, reverse changes are calculated. - /// - /// This method is thread-safe. - /// Raised if 'other' belongs to a different document than this checkpoint. - IEnumerable GetChangesTo(ITextSourceVersion other); - - /// - /// Calculates where the offset has moved in the other buffer version. - /// - /// Raised if 'other' belongs to a different document than this checkpoint. - int MoveOffsetTo(ITextSourceVersion other, int oldOffset, AnchorMovementType movement = AnchorMovementType.Default); - } - - /// - /// Implements the ITextSource interface using a string. - /// - [Serializable] - public class StringTextSource : ITextSource - { - /// - /// Gets a text source containing the empty string. - /// - public static readonly StringTextSource Empty = new StringTextSource(string.Empty); - - readonly string text; - readonly ITextSourceVersion version; - - /// - /// Creates a new StringTextSource with the given text. - /// - public StringTextSource(string text) - { - if (text == null) - throw new ArgumentNullException("text"); - this.text = text; - } - - /// - /// Creates a new StringTextSource with the given text. - /// - public StringTextSource(string text, ITextSourceVersion version) - { - if (text == null) - throw new ArgumentNullException("text"); - this.text = text; - this.version = version; - } - - /// - public ITextSourceVersion Version { - get { return version; } - } - - /// - public int TextLength { - get { return text.Length; } - } - - /// - public string Text { - get { return text; } - } - - /// - public ITextSource CreateSnapshot() - { - return this; // StringTextSource is immutable - } - - /// - public ITextSource CreateSnapshot(int offset, int length) - { - return new StringTextSource(text.Substring(offset, length)); - } - - /// - public TextReader CreateReader() - { - return new StringReader(text); - } - - /// - public TextReader CreateReader(int offset, int length) - { - return new StringReader(text.Substring(offset, length)); - } - - /// - public void WriteTextTo(TextWriter writer) - { - writer.Write(text); - } - - /// - public void WriteTextTo(TextWriter writer, int offset, int length) - { - writer.Write(text.Substring(offset, length)); - } - - /// - public char GetCharAt(int offset) - { - return text[offset]; - } - - /// - public string GetText(int offset, int length) - { - return text.Substring(offset, length); - } - - /// - public string GetText(ISegment segment) - { - if (segment == null) - throw new ArgumentNullException("segment"); - return text.Substring(segment.Offset, segment.Length); - } - - /// - public int IndexOf(char c, int startIndex, int count) - { - return text.IndexOf(c, startIndex, count); - } - - /// - public int IndexOfAny(char[] anyOf, int startIndex, int count) - { - return text.IndexOfAny(anyOf, startIndex, count); - } - - /// - public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) - { - return text.IndexOf(searchText, startIndex, count, comparisonType); - } - - /// - public int LastIndexOf(char c, int startIndex, int count) - { - return text.LastIndexOf(c, startIndex + count - 1, count); - } - - /// - public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) - { - return text.LastIndexOf(searchText, startIndex + count - 1, count, comparisonType); - } - } - #endif -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/IUndoableOperation.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/IUndoableOperation.cs deleted file mode 100644 index 50e95d5ba..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/IUndoableOperation.cs +++ /dev/null @@ -1,45 +0,0 @@ -// 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 -{ - /// - /// This Interface describes a the basic Undo/Redo operation - /// all Undo Operations must implement this interface. - /// - public interface IUndoableOperation - { - /// - /// Undo the last operation - /// - void Undo(); - - /// - /// Redo the last operation - /// - void Redo(); - } - - interface IUndoableOperationWithContext : IUndoableOperation - { - void Undo(UndoStack stack); - void Redo(UndoStack stack); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/LineManager.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/LineManager.cs deleted file mode 100644 index 7ff71d2eb..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/LineManager.cs +++ /dev/null @@ -1,318 +0,0 @@ -// 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 -{ - /// - /// Creates/Deletes lines when text is inserted/removed. - /// - sealed class LineManager - { - #region Constructor - readonly TextDocument document; - readonly DocumentLineTree documentLineTree; - - /// - /// 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) - /// - 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 deletedLines = new HashSet(); - readonly HashSet changedLines = new HashSet(); - HashSet deletedOrChangedLines = new HashSet(); - - /// - /// Gets the list of lines deleted since the last RetrieveChangedLines() call. - /// The returned list is unsorted. - /// - public ICollection RetrieveDeletedLines() - { - var r = deletedLines; - deletedLines = new HashSet(); - return r; - } - - /// - /// 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. - /// - public List RetrieveChangedLines() - { - var list = (from line in changedLines - where !line.IsDeleted - let number = line.LineNumber - orderby number - select line).ToList(); - changedLines.Clear(); - return list; - } - - /// - /// Gets the list of lines changed since the last RetrieveDeletedOrChangedLines() call. - /// The returned list is not sorted. - /// - public ICollection RetrieveDeletedOrChangedLines() - { - var r = deletedOrChangedLines; - deletedOrChangedLines = new HashSet(); - 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 lines = new List(); - 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 - /// - /// 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'. - /// - /// Usually returns , but if line was deleted due to - /// the "\r\n" merge, returns the previous line. - 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/LineNode.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/LineNode.cs deleted file mode 100644 index 83e6d935b..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/LineNode.cs +++ /dev/null @@ -1,98 +0,0 @@ -// 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 :) - - /// - /// Resets the line to enable its reuse after a document rebuild. - /// - 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; - } - } - - /// - /// The number of lines in this node and its child nodes. - /// Invariant: - /// nodeTotalCount = 1 + left.nodeTotalCount + right.nodeTotalCount - /// - internal int nodeTotalCount; - - /// - /// The total text length of this node and its child nodes. - /// Invariant: - /// nodeTotalLength = left.nodeTotalLength + documentLine.TotalLength + right.nodeTotalLength - /// - internal int nodeTotalLength; - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/NewLineFinder.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/NewLineFinder.cs deleted file mode 100644 index 07cb18a80..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/NewLineFinder.cs +++ /dev/null @@ -1,150 +0,0 @@ -// 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" }; - - /// - /// Gets the location of the next new line character, or SimpleSegment.Invalid - /// if none is found. - /// - 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; - } - - /// - /// Gets the location of the next new line character, or SimpleSegment.Invalid - /// if none is found. - /// - 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 - { - /// - /// Finds the next new line character starting at offset. - /// - /// The text source to search in. - /// The starting offset for the search. - /// The string representing the new line that was found, or null if no new line was found. - /// The position of the first new line starting at or after , - /// or -1 if no new line was found. - 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; - } - } - - /// - /// Gets whether the specified string is a newline sequence. - /// - public static bool IsNewLine(string newLine) - { - return newLine == "\r\n" || newLine == "\n" || newLine == "\r"; - } - - /// - /// Normalizes all new lines in to be . - /// - 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(); - } - - /// - /// Gets the newline sequence used in the document at the specified line. - /// - 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/OffsetChangeMap.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/OffsetChangeMap.cs deleted file mode 100644 index 5584392bb..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/OffsetChangeMap.cs +++ /dev/null @@ -1,364 +0,0 @@ -// 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 -{ - /// - /// Contains predefined offset change mapping types. - /// - public enum OffsetChangeMappingType - { - /// - /// 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. - /// - /// - /// 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. - /// - Normal, - /// - /// 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. - /// - /// - /// This is implemented as an OffsetChangeMap with two entries: the removal, and the insertion. - /// - RemoveAndInsert, - /// - /// 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. - /// - /// - /// 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 setting. - /// If the text keeps its old size, this is implemented as OffsetChangeMap.Empty. - /// - CharacterReplace, - /// - /// Like 'Normal', but anchors with = Default will stay in front of the - /// insertion instead of being moved behind it. - /// - KeepAnchorBeforeInsertion - } - - /// - /// Describes a series of offset changes. - /// - [Serializable] - [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", - Justification="It's a mapping old offsets -> new offsets")] - public sealed class OffsetChangeMap : Collection - { - /// - /// Immutable OffsetChangeMap that is empty. - /// - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", - Justification="The Empty instance is immutable")] - public static readonly OffsetChangeMap Empty = new OffsetChangeMap(Empty.Array, true); - - /// - /// Creates a new OffsetChangeMap with a single element. - /// - /// The entry. - /// Returns a frozen OffsetChangeMap with a single entry. - public static OffsetChangeMap FromSingleElement(OffsetChangeMapEntry entry) - { - return new OffsetChangeMap(new OffsetChangeMapEntry[] { entry }, true); - } - - bool isFrozen; - - /// - /// Creates a new OffsetChangeMap instance. - /// - public OffsetChangeMap() - { - } - - internal OffsetChangeMap(int capacity) - : base(new List(capacity)) - { - } - - private OffsetChangeMap(IList entries, bool isFrozen) - : base(entries) - { - this.isFrozen = isFrozen; - } - - /// - /// Gets the new offset where the specified offset moves after this document change. - /// - public int GetNewOffset(int offset, AnchorMovementType movementType = AnchorMovementType.Default) - { - IList items = this.Items; - int count = items.Count; - for (int i = 0; i < count; i++) { - offset = items[i].GetNewOffset(offset, movementType); - } - return offset; - } - - /// - /// Gets whether this OffsetChangeMap is a valid explanation for the specified document change. - /// - 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; - } - - /// - /// Calculates the inverted OffsetChangeMap (used for the undo operation). - /// - 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; - } - - /// - protected override void ClearItems() - { - CheckFrozen(); - base.ClearItems(); - } - - /// - protected override void InsertItem(int index, OffsetChangeMapEntry item) - { - CheckFrozen(); - base.InsertItem(index, item); - } - - /// - protected override void RemoveItem(int index) - { - CheckFrozen(); - base.RemoveItem(index); - } - - /// - 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."); - } - - /// - /// Gets if this instance is frozen. Frozen instances are immutable and thus thread-safe. - /// - public bool IsFrozen { - get { return isFrozen; } - } - - /// - /// Freezes this instance. - /// - public void Freeze() - { - isFrozen = true; - } - } - - /// - /// An entry in the OffsetChangeMap. - /// This represents the offset of a document change (either insertion or removal, not both at once). - /// - [Serializable] - public struct OffsetChangeMapEntry : IEquatable - { - readonly int offset; - - // MSB: DefaultAnchorMovementIsBeforeInsertion - readonly uint insertionLengthWithMovementFlag; - - // MSB: RemovalNeverCausesAnchorDeletion; other 31 bits: RemovalLength - readonly uint removalLengthWithDeletionFlag; - - /// - /// The offset at which the change occurs. - /// - public int Offset { - get { return offset; } - } - - /// - /// The number of characters inserted. - /// Returns 0 if this entry represents a removal. - /// - public int InsertionLength { - get { return (int)(insertionLengthWithMovementFlag & 0x7fffffff); } - } - - /// - /// The number of characters removed. - /// Returns 0 if this entry represents an insertion. - /// - public int RemovalLength { - get { return (int)(removalLengthWithDeletionFlag & 0x7fffffff); } - } - - /// - /// Gets whether the removal should not cause any anchor deletions. - /// - public bool RemovalNeverCausesAnchorDeletion { - get { return (removalLengthWithDeletionFlag & 0x80000000) != 0; } - } - - /// - /// Gets whether default anchor movement causes the anchor to stay in front of the caret. - /// - public bool DefaultAnchorMovementIsBeforeInsertion { - get { return (insertionLengthWithMovementFlag & 0x80000000) != 0; } - } - - /// - /// Gets the new offset where the specified offset moves after this document change. - /// - 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; - } - - /// - /// Creates a new OffsetChangeMapEntry instance. - /// - 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; - } - - /// - /// Creates a new OffsetChangeMapEntry instance. - /// - 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; - } - - /// - public override int GetHashCode() - { - unchecked { - return offset + 3559 * (int)insertionLengthWithMovementFlag + 3571 * (int)removalLengthWithDeletionFlag; - } - } - - /// - public override bool Equals(object obj) - { - return obj is OffsetChangeMapEntry && this.Equals((OffsetChangeMapEntry)obj); - } - - /// - public bool Equals(OffsetChangeMapEntry other) - { - return offset == other.offset && insertionLengthWithMovementFlag == other.insertionLengthWithMovementFlag && removalLengthWithDeletionFlag == other.removalLengthWithDeletionFlag; - } - - /// - /// Tests the two entries for equality. - /// - public static bool operator ==(OffsetChangeMapEntry left, OffsetChangeMapEntry right) - { - return left.Equals(right); - } - - /// - /// Tests the two entries for inequality. - /// - public static bool operator !=(OffsetChangeMapEntry left, OffsetChangeMapEntry right) - { - return !left.Equals(right); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/RopeTextSource.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/RopeTextSource.cs deleted file mode 100644 index 73a6f0b0c..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/RopeTextSource.cs +++ /dev/null @@ -1,169 +0,0 @@ -// 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 -{ - /// - /// Implements the ITextSource interface using a rope. - /// - [Serializable] - public sealed class RopeTextSource : ITextSource - { - readonly Rope rope; - readonly ITextSourceVersion version; - - /// - /// Creates a new RopeTextSource. - /// - public RopeTextSource(Rope rope) - { - if (rope == null) - throw new ArgumentNullException("rope"); - this.rope = rope.Clone(); - } - - /// - /// Creates a new RopeTextSource. - /// - public RopeTextSource(Rope rope, ITextSourceVersion version) - { - if (rope == null) - throw new ArgumentNullException("rope"); - this.rope = rope.Clone(); - this.version = version; - } - - /// - /// Returns a clone of the rope used for this text source. - /// - /// - /// RopeTextSource only publishes a copy of the contained rope to ensure that the underlying rope cannot be modified. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification="Not a property because it creates a clone")] - public Rope GetRope() - { - return rope.Clone(); - } - - /// - public string Text { - get { return rope.ToString(); } - } - - /// - public int TextLength { - get { return rope.Length; } - } - - /// - public char GetCharAt(int offset) - { - return rope[offset]; - } - - /// - public string GetText(int offset, int length) - { - return rope.ToString(offset, length); - } - - /// - public string GetText(ISegment segment) - { - return rope.ToString(segment.Offset, segment.Length); - } - - /// - public TextReader CreateReader() - { - return new RopeTextReader(rope); - } - - /// - public TextReader CreateReader(int offset, int length) - { - return new RopeTextReader(rope.GetRange(offset, length)); - } - - /// - public ITextSource CreateSnapshot() - { - return this; - } - - /// - public ITextSource CreateSnapshot(int offset, int length) - { - return new RopeTextSource(rope.GetRange(offset, length)); - } - - /// - public int IndexOf(char c, int startIndex, int count) - { - return rope.IndexOf(c, startIndex, count); - } - - /// - public int IndexOfAny(char[] anyOf, int startIndex, int count) - { - return rope.IndexOfAny(anyOf, startIndex, count); - } - - /// - public int LastIndexOf(char c, int startIndex, int count) - { - return rope.LastIndexOf(c, startIndex, count); - } - - /// - public ITextSourceVersion Version { - get { return version; } - } - - /// - public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) - { - return rope.IndexOf(searchText, startIndex, count, comparisonType); - } - - /// - public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) - { - return rope.LastIndexOf(searchText, startIndex, count, comparisonType); - } - - /// - public void WriteTextTo(TextWriter writer) - { - rope.WriteTo(writer, 0, rope.Length); - } - - /// - public void WriteTextTo(TextWriter writer, int offset, int length) - { - rope.WriteTo(writer, offset, length); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/SimpleSegment.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/SimpleSegment.cs deleted file mode 100644 index 27c646e40..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/SimpleSegment.cs +++ /dev/null @@ -1,197 +0,0 @@ -// 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 -{ - /// - /// Represents a simple segment (Offset,Length pair) that is not automatically updated - /// on document changes. - /// - struct SimpleSegment : IEquatable, ISegment - { - public static readonly SimpleSegment Invalid = new SimpleSegment(-1, -1); - - /// - /// Gets the overlapping portion of the segments. - /// Returns SimpleSegment.Invalid if the segments don't overlap. - /// - 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); - } - - /// - public override string ToString() - { - return "[Offset=" + Offset.ToString(CultureInfo.InvariantCulture) + ", Length=" + Length.ToString(CultureInfo.InvariantCulture) + "]"; - } - } - - /// - /// A segment using s as start and end positions. - /// - /// - /// - /// 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. - /// - /// - /// - /// - public sealed class AnchorSegment : ISegment - { - readonly TextAnchor start, end; - - /// - public int Offset { - get { return start.Offset; } - } - - /// - 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); - } - } - - /// - 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); - } - } - - /// - /// Creates a new AnchorSegment using the specified anchors. - /// The anchors must have set to true. - /// - 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; - } - - /// - /// Creates a new AnchorSegment that creates new anchors. - /// - public AnchorSegment(TextDocument document, ISegment segment) - : this(document, ThrowUtil.CheckNotNull(segment, "segment").Offset, segment.Length) - { - } - - /// - /// Creates a new AnchorSegment that creates new anchors. - /// - 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; - } - - /// - public override string ToString() - { - return "[Offset=" + Offset.ToString(CultureInfo.InvariantCulture) + ", EndOffset=" + EndOffset.ToString(CultureInfo.InvariantCulture) + "]"; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextAnchor.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextAnchor.cs deleted file mode 100644 index 45bddde16..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextAnchor.cs +++ /dev/null @@ -1,158 +0,0 @@ -// 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 -{ - /// - /// 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. - /// - /// - /// Use the property to get the offset from a text anchor. - /// Use the method to create an anchor from an offset. - /// - /// - /// 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. - /// - /// 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 property also runs in O(lg N). - /// - /// - /// If you want to track a segment, you can use the class which - /// implements using two text anchors. - /// - /// - /// Usage: - /// TextAnchor anchor = document.CreateAnchor(offset); - /// ChangeMyDocument(); - /// int newOffset = anchor.Offset; - /// - /// - public sealed class TextAnchor : ITextAnchor - { - readonly TextDocument document; - internal TextAnchorNode node; - - internal TextAnchor(TextDocument document) - { - this.document = document; - } - - /// - /// Gets the document owning the anchor. - /// - public TextDocument Document { - get { return document; } - } - - /// - public AnchorMovementType MovementType { get; set; } - - /// - public bool SurviveDeletion { get; set; } - - /// - public bool IsDeleted { - get { - document.DebugVerifyAccess(); - return node == null; - } - } - - /// - public event EventHandler Deleted; - - internal void OnDeleted(DelayedEvents delayedEvents) - { - node = null; - delayedEvents.DelayedRaise(Deleted, this, EventArgs.Empty); - } - - /// - /// Gets the offset of the text anchor. - /// - /// Thrown when trying to get the Offset from a deleted anchor. - 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; - } - } - - /// - /// Gets the line number of the anchor. - /// - /// Thrown when trying to get the Offset from a deleted anchor. - public int Line { - get { - return document.GetLineByOffset(this.Offset).LineNumber; - } - } - - /// - /// Gets the column number of this anchor. - /// - /// Thrown when trying to get the Offset from a deleted anchor. - public int Column { - get { - int offset = this.Offset; - return offset - document.GetLineByOffset(offset).Offset + 1; - } - } - - /// - /// Gets the text location of this anchor. - /// - /// Thrown when trying to get the Offset from a deleted anchor. - public TextLocation Location { - get { - return document.GetLocation(this.Offset); - } - } - - /// - public override string ToString() - { - return "[TextAnchor Offset=" + Offset + "]"; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextAnchorNode.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextAnchorNode.cs deleted file mode 100644 index cd99ae4fc..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextAnchorNode.cs +++ /dev/null @@ -1,102 +0,0 @@ -// 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 -{ - /// - /// 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) - /// - 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; - } - } - - /// - /// Gets the inorder successor of the node. - /// - 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; - } - } - } - - /// - /// Gets the inorder predecessor of the node. - /// - 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 + "]"; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextAnchorTree.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextAnchorTree.cs deleted file mode 100644 index 5c285d47c..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextAnchorTree.cs +++ /dev/null @@ -1,770 +0,0 @@ -// 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 -{ - /// - /// A tree of TextAnchorNodes. - /// - 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 nodesToDelete = new List(); - 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 beforeInsert = new List(); - //List afterInsert = new List(); - 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); - } - } - - /// - /// Swaps the anchors stored in the two nodes. - /// - 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 - /// - /// Finds the node at the specified offset. - /// After the method has run, offset is relative to the beginning of the returned node. - /// - 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 ""; - 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextDocument.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextDocument.cs deleted file mode 100644 index ce22970cd..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextDocument.cs +++ /dev/null @@ -1,1153 +0,0 @@ -// 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 -{ - /// - /// This class is the main class of the text model. Basically, it is a with events. - /// - /// - /// Thread safety: - /// - /// However, there is a single method that is thread-safe: (and its overloads). - /// - public sealed class TextDocument : IDocument, INotifyPropertyChanged - { - #region Thread ownership - readonly object lockObject = new object(); - Thread owner = Thread.CurrentThread; - - /// - /// Verifies that the current thread is the documents owner thread. - /// Throws an if the wrong thread accesses the TextDocument. - /// - /// - /// The TextDocument class is not thread-safe. A document instance expects to have a single owner thread - /// and will throw an when accessed from another thread. - /// It is possible to change the owner thread using the method. - /// - public void VerifyAccess() - { - if (Thread.CurrentThread != owner) - throw new InvalidOperationException("TextDocument can be accessed only from the thread that owns it."); - } - - /// - /// 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. - /// - /// - /// - /// - /// 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 . - /// - /// - 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 rope; - readonly DocumentLineTree lineTree; - readonly LineManager lineManager; - readonly TextAnchorTree anchorTree; - readonly TextSourceVersionProvider versionProvider = new TextSourceVersionProvider(); - - /// - /// Create an empty text document. - /// - public TextDocument() - : this(string.Empty) - { - } - - /// - /// Create a new text document with the specified initial text. - /// - public TextDocument(IEnumerable initialText) - { - if (initialText == null) - throw new ArgumentNullException("initialText"); - rope = new Rope(initialText); - lineTree = new DocumentLineTree(this); - lineManager = new LineManager(lineTree, this); - lineTrackers.CollectionChanged += delegate { - lineManager.UpdateListOfLineTrackers(); - }; - - anchorTree = new TextAnchorTree(this); - undoStack = new UndoStack(); - FireChangeEvents(); - } - - /// - /// Create a new text document with the specified initial text. - /// - public TextDocument(ITextSource initialText) - : this(GetTextFromTextSource(initialText)) - { - } - - // gets the text from a text source, directly retrieving the underlying rope where possible - static IEnumerable 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)); - } - } - - /// - public string GetText(int offset, int length) - { - VerifyAccess(); - return rope.ToString(offset, length); - } - - /// - /// Retrieves the text for a portion of the document. - /// - public string GetText(ISegment segment) - { - if (segment == null) - throw new ArgumentNullException("segment"); - return GetText(segment.Offset, segment.Length); - } - - /// - public int IndexOf(char c, int startIndex, int count) - { - DebugVerifyAccess(); - return rope.IndexOf(c, startIndex, count); - } - - /// - public int LastIndexOf(char c, int startIndex, int count) - { - DebugVerifyAccess(); - return rope.LastIndexOf(c, startIndex, count); - } - - /// - 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); - } - - /// - public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) - { - DebugVerifyAccess(); - return rope.IndexOf(searchText, startIndex, count, comparisonType); - } - - /// - public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) - { - DebugVerifyAccess(); - return rope.LastIndexOf(searchText, startIndex, count, comparisonType); - } - - /// - public char GetCharAt(int offset) - { - DebugVerifyAccess(); // frequently called, so must be fast in release builds - return rope[offset]; - } - - WeakReference cachedText; - - /// - /// Gets/Sets the text of the whole document. - /// - 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); - } - } - - /// - /// This event is called after a group of changes is completed. - /// - /// - public event EventHandler TextChanged; - - event EventHandler IDocument.ChangeCompleted { - add { this.TextChanged += value; } - remove { this.TextChanged -= value; } - } - - /// - public int TextLength { - get { - VerifyAccess(); - return rope.Length; - } - } - - /// - /// Is raised when the TextLength property changes. - /// - /// - [Obsolete("This event will be removed in a future version; use the PropertyChanged event instead")] - public event EventHandler TextLengthChanged; - - /// - /// Is raised when one of the properties , , , - /// changes. - /// - /// - public event PropertyChangedEventHandler PropertyChanged; - - /// - /// Is raised before the document changes. - /// - /// - /// Here is the order in which events are raised during a document update: - /// - /// BeginUpdate() - /// - /// Start of change group (on undo stack) - /// event is raised - /// - /// Insert() / Remove() / Replace() - /// - /// event is raised - /// The document is changed - /// TextAnchor.Deleted event is raised if anchors were - /// in the deleted text portion - /// event is raised - /// - /// EndUpdate() - /// - /// event is raised - /// event is raised (for the Text, TextLength, LineCount properties, in that order) - /// End of change group (on undo stack) - /// event is raised - /// - /// - /// - /// If the insert/remove/replace methods are called without a call to BeginUpdate(), - /// they will call BeginUpdate() and EndUpdate() to ensure no change happens outside of UpdateStarted/UpdateFinished. - /// - /// There can be multiple document changes between the BeginUpdate() and EndUpdate() calls. - /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. - /// - /// The listens to the UpdateStarted and UpdateFinished events to group all changes into a single undo step. - /// - /// - public event EventHandler Changing; - - // Unfortunately EventHandler is invariant, so we have to use two separate events - private event EventHandler textChanging; - - event EventHandler IDocument.TextChanging { - add { textChanging += value; } - remove { textChanging -= value; } - } - - /// - /// Is raised after the document has changed. - /// - /// - public event EventHandler Changed; - - private event EventHandler textChanged; - - event EventHandler IDocument.TextChanged { - add { textChanged += value; } - remove { textChanged -= value; } - } - - /// - /// Creates a snapshot of the current text. - /// - /// - /// 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. - /// - /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other - /// classes implementing ITextSource.CreateSnapshot(). - /// - /// - /// - public ITextSource CreateSnapshot() - { - lock (lockObject) { - return new RopeTextSource(rope, versionProvider.CurrentVersion); - } - } - - /// - /// Creates a snapshot of a part of the current text. - /// - /// - public ITextSource CreateSnapshot(int offset, int length) - { - lock (lockObject) { - return new RopeTextSource(rope.GetRange(offset, length)); - } - } - - #if NREFACTORY - /// - public IDocument CreateDocumentSnapshot() - { - return new ReadOnlyDocument(this, fileName); - } - #endif - - /// - public ITextSourceVersion Version { - get { return versionProvider.CurrentVersion; } - } - - /// - public System.IO.TextReader CreateReader() - { - lock (lockObject) { - return new RopeTextReader(rope); - } - } - - /// - public System.IO.TextReader CreateReader(int offset, int length) - { - lock (lockObject) { - return new RopeTextReader(rope.GetRange(offset, length)); - } - } - - /// - public void WriteTextTo(System.IO.TextWriter writer) - { - VerifyAccess(); - rope.WriteTo(writer, 0, rope.Length); - } - - /// - public void WriteTextTo(System.IO.TextWriter writer, int offset, int length) - { - VerifyAccess(); - rope.WriteTo(writer, offset, length); - } - #endregion - - #region BeginUpdate / EndUpdate - int beginUpdateCount; - - /// - /// Gets if an update is running. - /// - /// - public bool IsInUpdate { - get { - VerifyAccess(); - return beginUpdateCount > 0; - } - } - - /// - /// Immediately calls , - /// and returns an IDisposable that calls . - /// - /// - public IDisposable RunUpdate() - { - BeginUpdate(); - return new CallbackOnDispose(EndUpdate); - } - - /// - /// Begins a group of document changes. - /// Some events are suspended until EndUpdate is called, and the will - /// group all changes into a single action. - /// Calling BeginUpdate several times increments a counter, only after the appropriate number - /// of EndUpdate calls the events resume their work. - /// - /// - 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); - } - } - - /// - /// Ends a group of document changes. - /// - /// - 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; - } - } - - /// - /// Occurs when a document change starts. - /// - /// - public event EventHandler UpdateStarted; - - /// - /// Occurs when a document change is finished. - /// - /// - 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; - - /// - /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. - /// - 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 - /// - /// Inserts text. - /// - /// The offset at which the text is inserted. - /// The new text. - /// - /// 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. - /// - public void Insert(int offset, string text) - { - Replace(offset, 0, new StringTextSource(text), null); - } - - /// - /// Inserts text. - /// - /// The offset at which the text is inserted. - /// The new text. - /// - /// 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. - /// - public void Insert(int offset, ITextSource text) - { - Replace(offset, 0, text, null); - } - - /// - /// Inserts text. - /// - /// The offset at which the text is inserted. - /// The new text. - /// - /// 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 parameter. - /// - 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); - } - } - - /// - /// Inserts text. - /// - /// The offset at which the text is inserted. - /// The new text. - /// - /// 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 parameter. - /// - 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); - } - } - - /// - /// Removes text. - /// - public void Remove(ISegment segment) - { - Replace(segment, string.Empty); - } - - /// - /// Removes text. - /// - /// Starting offset of the text to be removed. - /// Length of the text to be removed. - public void Remove(int offset, int length) - { - Replace(offset, length, StringTextSource.Empty); - } - - internal bool inDocumentChanging; - - /// - /// Replaces text. - /// - public void Replace(ISegment segment, string text) - { - if (segment == null) - throw new ArgumentNullException("segment"); - Replace(segment.Offset, segment.Length, new StringTextSource(text), null); - } - - /// - /// Replaces text. - /// - public void Replace(ISegment segment, ITextSource text) - { - if (segment == null) - throw new ArgumentNullException("segment"); - Replace(segment.Offset, segment.Length, text, null); - } - - /// - /// Replaces text. - /// - /// The starting offset of the text to be replaced. - /// The length of the text to be replaced. - /// The new text. - public void Replace(int offset, int length, string text) - { - Replace(offset, length, new StringTextSource(text), null); - } - - /// - /// Replaces text. - /// - /// The starting offset of the text to be replaced. - /// The length of the text to be replaced. - /// The new text. - public void Replace(int offset, int length, ITextSource text) - { - Replace(offset, length, text, null); - } - - /// - /// Replaces text. - /// - /// The starting offset of the text to be replaced. - /// The length of the text to be replaced. - /// The new text. - /// 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. - public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) - { - Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); - } - - /// - /// Replaces text. - /// - /// The starting offset of the text to be replaced. - /// The length of the text to be replaced. - /// The new text. - /// 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. - 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"); - } - } - - /// - /// Replaces text. - /// - /// The starting offset of the text to be replaced. - /// The length of the text to be replaced. - /// The new text. - /// 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 . - /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting - /// DocumentChangeEventArgs instance. - /// - public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) - { - Replace(offset, length, new StringTextSource(text), offsetChangeMap); - } - - /// - /// Replaces text. - /// - /// The starting offset of the text to be replaced. - /// The length of the text to be replaced. - /// The new text. - /// 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 . - /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting - /// DocumentChangeEventArgs instance. - /// - 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... - /// - /// Gets a read-only list of lines. - /// - /// - public IList Lines { - get { return lineTree; } - } - - /// - /// Gets a line by the line number: O(log n) - /// - 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); - } - - /// - /// Gets a document lines by offset. - /// Runtime: O(log n) - /// - [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 - /// - /// Gets the offset from a text location. - /// - /// - public int GetOffset(TextLocation location) - { - return GetOffset(location.Line, location.Column); - } - - /// - /// Gets the offset from a text location. - /// - /// - 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; - } - - /// - /// Gets the location from an offset. - /// - /// - public TextLocation GetLocation(int offset) - { - DocumentLine line = GetLineByOffset(offset); - return new TextLocation(line.LineNumber, offset - line.Offset + 1); - } - #endregion - - #region Line Trackers - readonly ObservableCollection lineTrackers = new ObservableCollection(); - - /// - /// Gets the list of s attached to this document. - /// You can add custom line trackers to this list. - /// - public IList LineTrackers { - get { - VerifyAccess(); - return lineTrackers; - } - } - #endregion - - #region UndoStack - UndoStack undoStack; - - /// - /// Gets the of the document. - /// - /// This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents. - 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 - /// - /// Creates a new at the specified offset. - /// - /// - 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 - /// - /// Gets the total number of lines in the document. - /// Runtime: O(1). - /// - public int LineCount { - get { - VerifyAccess(); - return lineTree.LineCount; - } - } - - /// - /// Is raised when the LineCount property changes. - /// - [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(); - } - - /// - /// Gets the document lines tree in string form. - /// - [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 - } - - /// - /// Gets the text anchor tree in string form. - /// - [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; - - /// - /// Gets/Sets the service provider associated with this document. - /// By default, every TextDocument has its own ServiceContainer; and has the document itself - /// registered as and . - /// - 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; - - /// - public event EventHandler FileNameChanged; - - void OnFileNameChanged(EventArgs e) - { - EventHandler handler = this.FileNameChanged; - if (handler != null) - handler(this, e); - } - - /// - public string FileName { - get { return fileName; } - set { - if (fileName != value) { - fileName = value; - OnFileNameChanged(EventArgs.Empty); - } - } - } - #endregion - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextDocumentWeakEventManager.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextDocumentWeakEventManager.cs deleted file mode 100644 index 52d9c6fbc..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextDocumentWeakEventManager.cs +++ /dev/null @@ -1,167 +0,0 @@ -// 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 -{ - /// - /// Contains weak event managers for the TextDocument events. - /// - public static class TextDocumentWeakEventManager - { - /// - /// Weak event manager for the event. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public sealed class UpdateStarted : WeakEventManagerBase - { - /// - protected override void StartListening(TextDocument source) - { - source.UpdateStarted += DeliverEvent; - } - - /// - protected override void StopListening(TextDocument source) - { - source.UpdateStarted -= DeliverEvent; - } - } - - /// - /// Weak event manager for the event. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public sealed class UpdateFinished : WeakEventManagerBase - { - /// - protected override void StartListening(TextDocument source) - { - source.UpdateFinished += DeliverEvent; - } - - /// - protected override void StopListening(TextDocument source) - { - source.UpdateFinished -= DeliverEvent; - } - } - - /// - /// Weak event manager for the event. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public sealed class Changing : WeakEventManagerBase - { - /// - protected override void StartListening(TextDocument source) - { - source.Changing += DeliverEvent; - } - - /// - protected override void StopListening(TextDocument source) - { - source.Changing -= DeliverEvent; - } - } - - /// - /// Weak event manager for the event. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public sealed class Changed : WeakEventManagerBase - { - /// - protected override void StartListening(TextDocument source) - { - source.Changed += DeliverEvent; - } - - /// - protected override void StopListening(TextDocument source) - { - source.Changed -= DeliverEvent; - } - } - - /// - /// Weak event manager for the event. - /// - [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 - { - /// - protected override void StartListening(TextDocument source) - { - source.LineCountChanged += DeliverEvent; - } - - /// - protected override void StopListening(TextDocument source) - { - source.LineCountChanged -= DeliverEvent; - } - } - - /// - /// Weak event manager for the event. - /// - [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 - { - /// - protected override void StartListening(TextDocument source) - { - source.TextLengthChanged += DeliverEvent; - } - - /// - protected override void StopListening(TextDocument source) - { - source.TextLengthChanged -= DeliverEvent; - } - } - - /// - /// Weak event manager for the event. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public sealed class TextChanged : WeakEventManagerBase - { - /// - protected override void StartListening(TextDocument source) - { - source.TextChanged += DeliverEvent; - } - - /// - protected override void StopListening(TextDocument source) - { - source.TextChanged -= DeliverEvent; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextLocation.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextLocation.cs deleted file mode 100644 index f2950e64a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextLocation.cs +++ /dev/null @@ -1,271 +0,0 @@ -// 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 - /// - /// A line/column position. - /// Text editor lines/columns are counted started from one. - /// - /// - /// The document provides the methods and - /// to convert between offsets and TextLocations. - /// - [Serializable] - [TypeConverter(typeof(TextLocationConverter))] - public struct TextLocation : IComparable, IEquatable - { - /// - /// Represents no text location (0, 0). - /// - public static readonly TextLocation Empty = new TextLocation(0, 0); - - /// - /// Creates a TextLocation instance. - /// - public TextLocation(int line, int column) - { - this.line = line; - this.column = column; - } - - readonly int column, line; - - /// - /// Gets the line number. - /// - public int Line { - get { return line; } - } - - /// - /// Gets the column number. - /// - public int Column { - get { return column; } - } - - /// - /// Gets whether the TextLocation instance is empty. - /// - public bool IsEmpty { - get { - return column <= 0 && line <= 0; - } - } - - /// - /// Gets a string representation for debugging purposes. - /// - public override string ToString() - { - return string.Format(CultureInfo.InvariantCulture, "(Line {1}, Col {0})", this.column, this.line); - } - - /// - /// Gets a hash code. - /// - public override int GetHashCode() - { - return unchecked (191 * column.GetHashCode() ^ line.GetHashCode()); - } - - /// - /// Equality test. - /// - public override bool Equals(object obj) - { - if (!(obj is TextLocation)) return false; - return (TextLocation)obj == this; - } - - /// - /// Equality test. - /// - public bool Equals(TextLocation other) - { - return this == other; - } - - /// - /// Equality test. - /// - public static bool operator ==(TextLocation left, TextLocation right) - { - return left.column == right.column && left.line == right.line; - } - - /// - /// Inequality test. - /// - public static bool operator !=(TextLocation left, TextLocation right) - { - return left.column != right.column || left.line != right.line; - } - - /// - /// Compares two text locations. - /// - 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; - } - - /// - /// Compares two text locations. - /// - 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; - } - - /// - /// Compares two text locations. - /// - public static bool operator <=(TextLocation left, TextLocation right) - { - return !(left > right); - } - - /// - /// Compares two text locations. - /// - public static bool operator >=(TextLocation left, TextLocation right) - { - return !(left < right); - } - - /// - /// Compares two text locations. - /// - public int CompareTo(TextLocation other) - { - if (this == other) - return 0; - if (this < other) - return -1; - else - return 1; - } - } - - /// - /// Converts strings of the form '0+[;,]0+' to a . - /// - 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], culture), int.Parse(parts[1], culture)); - } - } - return base.ConvertFrom(context, culture, value); - } - - /// - 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); - } - } - - /// - /// An (Offset,Length)-pair. - /// - public interface ISegment - { - /// - /// Gets the start offset of the segment. - /// - int Offset { get; } - - /// - /// Gets the length of the segment. - /// - /// For line segments (IDocumentLine), the length does not include the line delimeter. - int Length { get; } - - /// - /// Gets the end offset of the segment. - /// - /// EndOffset = Offset + Length; - int EndOffset { get; } - } - - /// - /// Extension methods for . - /// - public static class ISegmentExtensions - { - /// - /// Gets whether fully contains the specified segment. - /// - /// - /// Use segment.Contains(offset, 0) to detect whether a segment (end inclusive) contains offset; - /// use segment.Contains(offset, 1) to detect whether a segment (end exclusive) contains offset. - /// - public static bool Contains (this ISegment segment, int offset, int length) - { - return segment.Offset <= offset && offset + length <= segment.EndOffset; - } - - /// - /// Gets whether fully contains the specified segment. - /// - public static bool Contains (this ISegment thisSegment, ISegment segment) - { - return segment != null && thisSegment.Offset <= segment.Offset && segment.EndOffset <= thisSegment.EndOffset; - } - } - #endif -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextSegment.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextSegment.cs deleted file mode 100644 index e0d8873c2..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextSegment.cs +++ /dev/null @@ -1,266 +0,0 @@ -// 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 -{ - /// - /// A segment that can be put into a . - /// - /// - /// - /// A can be stand-alone or part of a . - /// If the segment is stored inside a TextSegmentCollection, its Offset and Length will be updated by that collection. - /// - /// - /// When the document changes, the offsets of all text segments in the TextSegmentCollection will be adjusted accordingly. - /// Start offsets move like AnchorMovementType.AfterInsertion, - /// end offsets move like AnchorMovementType.BeforeInsertion - /// (i.e. the segment will always stay as small as possible). - /// - /// 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 AfterInsertion. - /// - /// - /// Thread-safety: a TextSegmentCollection that is connected to a 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. - /// - /// - /// - /// - /// - public class TextSegment : ISegment - { - internal ISegmentTree ownerTree; - internal TextSegment left, right, parent; - - /// - /// The color of the segment in the red/black tree. - /// - internal bool color; - - /// - /// The "length" of the node (distance to previous node) - /// - internal int nodeLength; - - /// - /// The total "length" of this subtree. - /// - internal int totalNodeLength; // totalNodeLength = nodeLength + left.totalNodeLength + right.totalNodeLength - - /// - /// The length of the segment (do not confuse with nodeLength). - /// - internal int segmentLength; - - /// - /// distanceToMaxEnd = Max(segmentLength, - /// left.distanceToMaxEnd + left.Offset - Offset, - /// left.distanceToMaxEnd + right.Offset - Offset) - /// - internal int distanceToMaxEnd; - - int ISegment.Offset { - get { return StartOffset; } - } - - /// - /// Gets whether this segment is connected to a TextSegmentCollection and will automatically - /// update its offsets. - /// - protected bool IsConnectedToCollection { - get { - return ownerTree != null; - } - } - - /// - /// Gets/Sets the start offset of the segment. - /// - /// - /// When setting the start offset, the end offset will change, too: the Length of the segment will stay constant. - /// - 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(); - } - } - } - - /// - /// Gets/Sets the end offset of the segment. - /// - /// - /// Setting the end offset will change the length, the start offset will stay constant. - /// - 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; - } - } - - /// - /// Gets/Sets the length of the segment. - /// - /// - /// Setting the length will change the end offset, the start offset will stay constant. - /// - 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(); - } - } - } - - /// - /// 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 - /// - 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; - } - } - - /// - /// Gets the inorder successor of the node. - /// - 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; - } - } - } - - /// - /// Gets the inorder predecessor of the node. - /// - 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 - - /// - public override string ToString() - { - return "[" + GetType().Name + " Offset=" + StartOffset + " Length=" + Length + " EndOffset=" + EndOffset + "]"; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextSegmentCollection.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextSegmentCollection.cs deleted file mode 100644 index 88861db9f..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextSegmentCollection.cs +++ /dev/null @@ -1,989 +0,0 @@ -// 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 -{ - /// - /// Interface to allow TextSegments to access the TextSegmentCollection - we cannot use a direct reference - /// because TextSegmentCollection is generic. - /// - interface ISegmentTree - { - void Add(TextSegment s); - void Remove(TextSegment s); - void UpdateAugmentedData(TextSegment s); - } - - /// - /// - /// A collection of text segments that supports efficient lookup of segments - /// intersecting with another segment. - /// - /// - /// - /// - public sealed class TextSegmentCollection : ICollection, 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 - /// - /// Creates a new TextSegmentCollection that needs manual calls to . - /// - public TextSegmentCollection() - { - } - - /// - /// Creates a new TextSegmentCollection that updates the offsets automatically. - /// - /// 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. - 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; - } - - /// - /// Updates the start and end offsets of all segments stored in this collection. - /// - /// DocumentChangeEventArgs instance describing the change to the document. - 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()); - } - } - - /// - /// Updates the start and end offsets of all segments stored in this collection. - /// - /// OffsetChangeMapEntry instance describing the change to the document. - 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 - /// - /// Adds the specified segment to the tree. This will cause the segment to update when the - /// document changes. - /// - 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 - /// - /// Gets the next segment after the specified segment. - /// Segments are sorted by their start offset. - /// Returns null if segment is the last segment. - /// - public T GetNextSegment(T segment) - { - if (!Contains(segment)) - throw new ArgumentException("segment is not inside the segment tree"); - return (T)segment.Successor; - } - - /// - /// Gets the previous segment before the specified segment. - /// Segments are sorted by their start offset. - /// Returns null if segment is the first segment. - /// - 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 - /// - /// Returns the first segment in the collection or null, if the collection is empty. - /// - public T FirstSegment { - get { - return root == null ? null : (T)root.LeftMost; - } - } - - /// - /// Returns the last segment in the collection or null, if the collection is empty. - /// - public T LastSegment { - get { - return root == null ? null : (T)root.RightMost; - } - } - #endregion - - #region FindFirstSegmentWithStartAfter - /// - /// Gets the first segment with a start offset greater or equal to . - /// Returns null if no such segment is found. - /// - 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; - } - - /// - /// Finds the node at the specified offset. - /// After the method has run, offset is relative to the beginning of the returned node. - /// - 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 - /// - /// Finds all segments that contain the given offset. - /// (StartOffset <= offset <= EndOffset) - /// Segments are returned in the order given by GetNextSegment/GetPreviousSegment. - /// - /// 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. - public ReadOnlyCollection FindSegmentsContaining(int offset) - { - return FindOverlappingSegments(offset, 0); - } - - /// - /// Finds all segments that overlap with the given segment (including touching segments). - /// - /// 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. - public ReadOnlyCollection FindOverlappingSegments(ISegment segment) - { - if (segment == null) - throw new ArgumentNullException("segment"); - return FindOverlappingSegments(segment.Offset, segment.Length); - } - - /// - /// Finds all segments that overlap with the given segment (including touching segments). - /// Segments are returned in the order given by GetNextSegment/GetPreviousSegment. - /// - /// 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. - public ReadOnlyCollection FindOverlappingSegments(int offset, int length) - { - ThrowUtil.CheckNotNegative(length, "length"); - List results = new List(); - if (root != null) { - FindOverlappingSegments(results, root, offset, offset + length); - } - return results.AsReadOnly(); - } - - void FindOverlappingSegments(List 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 - /// - /// Removes the specified segment from the tree. This will cause the segment to not update - /// anymore when the document changes. - /// - 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--; - } - - /// - /// Removes all segments from the tree. - /// - 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 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 implementation - /// - /// Gets the number of segments in the tree. - /// - public int Count { - get { return count; } - } - - bool ICollection.IsReadOnly { - get { return false; } - } - - /// - /// Gets whether this tree contains the specified item. - /// - public bool Contains(T item) - { - return item != null && item.ownerTree == this; - } - - /// - /// Copies all segments in this SegmentTree to the specified array. - /// - 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; - } - } - - /// - /// Gets an enumerator to enumerate the segments. - /// - public IEnumerator 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextSourceVersionProvider.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextSourceVersionProvider.cs deleted file mode 100644 index c2dffc19a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextSourceVersionProvider.cs +++ /dev/null @@ -1,136 +0,0 @@ -// 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 - /// - /// Provides ITextSourceVersion instances. - /// - public class TextSourceVersionProvider - { - Version currentVersion; - - /// - /// Creates a new TextSourceVersionProvider instance. - /// - public TextSourceVersionProvider() - { - this.currentVersion = new Version(this); - } - - /// - /// Gets the current version. - /// - public ITextSourceVersion CurrentVersion { - get { return currentVersion; } - } - - /// - /// Replaces the current version with a new version. - /// - /// Change from current version to new version - 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 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.Array; - } - - IEnumerable 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 -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextUtilities.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextUtilities.cs deleted file mode 100644 index 2d6f75784..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextUtilities.cs +++ /dev/null @@ -1,422 +0,0 @@ -// 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 -{ - /// - /// Specifies the mode for getting the next caret position. - /// - public enum CaretPositioningMode - { - /// - /// Normal positioning (stop after every grapheme) - /// - Normal, - /// - /// Stop only on word borders. - /// - WordBorder, - /// - /// Stop only at the beginning of words. This is used for Ctrl+Left/Ctrl+Right. - /// - WordStart, - /// - /// Stop only at the beginning of words, and anywhere in the middle of symbols. - /// - WordStartOrSymbol, - /// - /// Stop only on word borders, and anywhere in the middle of symbols. - /// - WordBorderOrSymbol, - /// - /// Stop between every Unicode codepoint, even within the same grapheme. - /// This is used to implement deleting the previous grapheme when Backspace is pressed. - /// - EveryCodepoint - } - - /// - /// Static helper methods for working with text. - /// - 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" - }; - - /// - /// Gets the name of the control character. - /// For unknown characters, the unicode codepoint is returned as 4-digit hexadecimal value. - /// - 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 - /// - /// Gets all whitespace (' ' and '\t', but no newlines) after offset. - /// - /// The text source. - /// The offset where the whitespace starts. - /// The segment containing the whitespace. - [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); - } - - /// - /// Gets all whitespace (' ' and '\t', but no newlines) before offset. - /// - /// The text source. - /// The offset where the whitespace ends. - /// The segment containing the whitespace. - [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); - } - - /// - /// Gets the leading whitespace segment on the document line. - /// - [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); - } - - /// - /// Gets the trailing whitespace segment on the document line. - /// - [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 - /// - /// Gets a single indentation segment starting at - at most one tab - /// or spaces. - /// - /// The text source. - /// The offset where the indentation segment starts. - /// The size of an indentation unit. See . - /// The indentation segment. - /// If there is no indentation character at the specified , - /// an empty segment is returned. - 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) - /// Gets whether the character is whitespace, part of an identifier, or line terminator. - /// - [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 - /// - /// Gets the next caret position. - /// - /// The text source. - /// The start offset inside the text source. - /// The search direction (forwards or backwards). - /// The mode for caret positioning. - /// The offset of the next caret position, or -1 if there is no further caret position - /// in the text source. - /// - /// 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. - /// - 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 - } - - /// - /// Classifies a character as whitespace, line terminator, part of an identifier, or other. - /// - public enum CharacterClass - { - /// - /// The character is not whitespace, line terminator or part of an identifier. - /// - Other, - /// - /// The character is whitespace (but not line terminator). - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace", - Justification = "WPF uses 'Whitespace'")] - Whitespace, - /// - /// The character can be part of an identifier (Letter, digit or underscore). - /// - IdentifierPart, - /// - /// The character is line terminator (\r or \n). - /// - LineTerminator, - /// - /// The character is a unicode combining mark that modifies the previous character. - /// Corresponds to the Unicode designations "Mn", "Mc" and "Me". - /// - CombiningMark - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/UndoOperationGroup.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/UndoOperationGroup.cs deleted file mode 100644 index 7346ada9b..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/UndoOperationGroup.cs +++ /dev/null @@ -1,76 +0,0 @@ -// 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 -{ - /// - /// This class stacks the last x operations from the undostack and makes - /// one undo/redo operation from it. - /// - sealed class UndoOperationGroup : IUndoableOperationWithContext - { - IUndoableOperation[] undolist; - - public UndoOperationGroup(Deque 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]); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/UndoStack.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/UndoStack.cs deleted file mode 100644 index 2db351f1a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/UndoStack.cs +++ /dev/null @@ -1,458 +0,0 @@ -// 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 -{ - /// - /// Undo stack implementation. - /// - [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 undostack = new Deque(); - Deque redostack = new Deque(); - 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 - - /// - /// 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 - /// - int elementsOnUndoUntilOriginalFile; - - bool isOriginalFile = true; - - /// - /// Gets whether the document is currently in its original state (no modifications). - /// - public bool IsOriginalFile { - get { return isOriginalFile; } - } - - void RecalcIsOriginalFile() - { - bool newIsOriginalFile = (elementsOnUndoUntilOriginalFile == 0); - if (newIsOriginalFile != isOriginalFile) { - isOriginalFile = newIsOriginalFile; - NotifyPropertyChanged("IsOriginalFile"); - } - } - - /// - /// Marks the current state as original. Discards any previous "original" markers. - /// - public void MarkAsOriginalFile() - { - elementsOnUndoUntilOriginalFile = 0; - RecalcIsOriginalFile(); - } - - /// - /// Discards the current "original" marker. - /// - 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 - - /// - /// Gets if the undo stack currently accepts changes. - /// Is false while an undo action is running. - /// - public bool AcceptChanges { - get { return state == StateListen; } - } - - /// - /// Gets if there are actions on the undo stack. - /// Use the PropertyChanged event to listen to changes of this property. - /// - public bool CanUndo { - get { return undostack.Count > 0; } - } - - /// - /// Gets if there are actions on the redo stack. - /// Use the PropertyChanged event to listen to changes of this property. - /// - public bool CanRedo { - get { return redostack.Count > 0; } - } - - /// - /// Gets/Sets the limit on the number of items on the undo stack. - /// - /// 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. - 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(); - } - - /// - /// 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. - /// - /// 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 if you - /// want to join the undo groups. - public object LastGroupDescriptor { - get { return lastGroupDescriptor; } - } - - /// - /// Starts grouping changes. - /// Maintains a counter so that nested calls are possible. - /// - public void StartUndoGroup() - { - StartUndoGroup(null); - } - - /// - /// Starts grouping changes. - /// Maintains a counter so that nested calls are possible. - /// - /// An object that is stored with the undo group. - /// If this is not a top-level undo group, the parameter is ignored. - public void StartUndoGroup(object groupDescriptor) - { - if (undoGroupDepth == 0) { - actionCountInUndoGroup = 0; - optionalActionCount = 0; - lastGroupDescriptor = groupDescriptor; - } - undoGroupDepth++; - //Util.LoggingService.Debug("Open undo group (new depth=" + undoGroupDepth + ")"); - } - - /// - /// 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 , only top-level calls can continue existing undo groups. - /// - /// An object that is stored with the undo group. - /// If this is not a top-level undo group, the parameter is ignored. - 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 + ")"); - } - - /// - /// Stops grouping changes. - /// - 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 - //} - } - } - - /// - /// Throws an InvalidOperationException if an undo group is current open. - /// - 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 affectedDocuments; - - internal void RegisterAffectedDocument(TextDocument document) - { - if (affectedDocuments == null) - affectedDocuments = new List(); - if (!affectedDocuments.Contains(document)) { - affectedDocuments.Add(document); - document.BeginUpdate(); - } - } - - void CallEndUpdateOnAffectedDocuments() - { - if (affectedDocuments != null) { - foreach (TextDocument doc in affectedDocuments) { - doc.EndUpdate(); - } - affectedDocuments = null; - } - } - - /// - /// Call this method to undo the last operation on the stack - /// - 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(); - } - - /// - /// Call this method to redo the last undone operation - /// - 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(); - } - - /// - /// Call this method to push an UndoableOperation on the undostack. - /// The redostack will be cleared if you use this method. - /// - public void Push(IUndoableOperation operation) - { - Push(operation, false); - } - - /// - /// 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. - /// - 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(); - } - } - - /// - /// Call this method, if you want to clear the redo stack - /// - 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; - } - } - - /// - /// Clears both the undo and redo stack. - /// - 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)); - } - - /// - /// Is raised when a property (CanUndo, CanRedo) changed. - /// - public event PropertyChangedEventHandler PropertyChanged; - - void NotifyPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Document/WeakLineTracker.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Document/WeakLineTracker.cs deleted file mode 100644 index 7be0129e3..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Document/WeakLineTracker.cs +++ /dev/null @@ -1,109 +0,0 @@ -// 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 -{ - /// - /// Allows registering a line tracker on a TextDocument using a weak reference from the document to the line tracker. - /// - public sealed class WeakLineTracker : ILineTracker - { - TextDocument textDocument; - WeakReference targetObject; - - private WeakLineTracker(TextDocument textDocument, ILineTracker targetTracker) - { - this.textDocument = textDocument; - this.targetObject = new WeakReference(targetTracker); - } - - /// - /// Registers the as line tracker for the . - /// A weak reference to the target tracker will be used, and the WeakLineTracker will deregister itself - /// when the target tracker is garbage collected. - /// - 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; - } - - /// - /// Deregisters the weak line tracker. - /// - 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(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/AbstractMargin.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/AbstractMargin.cs deleted file mode 100644 index ba430639e..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/AbstractMargin.cs +++ /dev/null @@ -1,117 +0,0 @@ -// 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 -{ - /// - /// 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! - /// - public abstract class AbstractMargin : FrameworkElement, ITextViewConnect - { - /// - /// TextView property. - /// - public static readonly DependencyProperty TextViewProperty = - DependencyProperty.Register("TextView", typeof(TextView), typeof(AbstractMargin), - new FrameworkPropertyMetadata(OnTextViewChanged)); - - /// - /// Gets/sets the text view for which line numbers are displayed. - /// - /// Adding a margin to will automatically set this property to the text area's TextView. - 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; - - /// - /// Gets the document associated with the margin. - /// - public TextDocument Document { - get { return document; } - } - - /// - /// Called when the is changing. - /// - 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); - } - - /// - /// Called when the is changing. - /// - protected virtual void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument) - { - document = newDocument; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/Caret.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/Caret.cs deleted file mode 100644 index 7f33289f1..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/Caret.cs +++ /dev/null @@ -1,538 +0,0 @@ -// 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 -{ - /// - /// Helper class with caret-related methods. - /// - 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; - - /// - /// Gets/Sets the position of the caret. - /// Retrieving this property will validate the visual column (which can be expensive). - /// Use the property instead if you don't need the visual column. - /// - 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(); - } - } - } - - /// - /// Gets the caret position without validating it. - /// - internal TextViewPosition NonValidatedPosition { - get { - return position; - } - } - - /// - /// Gets/Sets the location of the caret. - /// The getter of this property is faster than because it doesn't have - /// to validate the visual column. - /// - public TextLocation Location { - get { - return position.Location; - } - set { - this.Position = new TextViewPosition(value); - } - } - - /// - /// Gets/Sets the caret line. - /// - public int Line { - get { return position.Line; } - set { - this.Position = new TextViewPosition(value, position.Column); - } - } - - /// - /// Gets/Sets the caret column. - /// - public int Column { - get { return position.Column; } - set { - this.Position = new TextViewPosition(position.Line, value); - } - } - - /// - /// Gets/Sets the caret visual column. - /// - public int VisualColumn { - get { - ValidateVisualColumn(); - return position.VisualColumn; - } - set { - this.Position = new TextViewPosition(position.Line, position.Column, value); - } - } - - bool isInVirtualSpace; - - /// - /// Gets whether the caret is in virtual space. - /// - 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; - } - - /// - /// Gets/Sets the caret offset. - /// Setting the caret offset has the side effect of setting the to NaN. - /// - 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; - } - } - } - - /// - /// Gets/Sets the desired x-position of the caret, in device-independent pixels. - /// This property is NaN if the caret has no desired position. - /// - 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; - } - } - } - } - - /// - /// 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. - /// - 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; - } - - /// - /// Validates the visual column of the caret using the specified visual line. - /// The visual line must contain the caret offset. - /// - 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; - } - - /// - /// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document. - /// - 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; - } - } - - /// - /// Minimum distance of the caret to the view border. - /// - internal const double MinimumDistanceToViewBorder = 30; - - /// - /// Scrolls the text view so that the caret is visible. - /// - public void BringCaretToView() - { - BringCaretToView(MinimumDistanceToViewBorder); - } - - internal void BringCaretToView(double border) - { - Rect caretRectangle = CalculateCaretRectangle(); - if (!caretRectangle.IsEmpty) { - caretRectangle.Inflate(border, border); - textView.MakeVisible(caretRectangle); - } - } - - /// - /// Makes the caret visible and updates its on-screen position. - /// - 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(); - } - } - } - - /// - /// Makes the caret invisible. - /// - 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); - } - - /// - /// Gets/Sets the color of the caret. - /// - public Brush CaretBrush { - get { return caretAdorner.CaretBrush; } - set { caretAdorner.CaretBrush = value; } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretLayer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretLayer.cs deleted file mode 100644 index 266fbb128..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretLayer.cs +++ /dev/null @@ -1,115 +0,0 @@ -// 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))); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretNavigationCommandHandler.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretNavigationCommandHandler.cs deleted file mode 100644 index c47d6d5c9..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretNavigationCommandHandler.cs +++ /dev/null @@ -1,392 +0,0 @@ -// 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 - { - /// - /// Creates a new for the text area. - /// - public static TextAreaInputHandler Create(TextArea textArea) - { - TextAreaInputHandler handler = new TextAreaInputHandler(textArea); - handler.CommandBindings.AddRange(CommandBindings); - handler.InputBindings.AddRange(InputBindings); - return handler; - } - - static readonly List CommandBindings = new List(); - static readonly List InputBindings = new List(); - - 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretWeakEventHandler.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretWeakEventHandler.cs deleted file mode 100644 index 2c8a03eef..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretWeakEventHandler.cs +++ /dev/null @@ -1,48 +0,0 @@ -// 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 -{ - /// - /// Contains classes for handling weak events on the Caret class. - /// - public static class CaretWeakEventManager - { - /// - /// Handles the Caret.PositionChanged event. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public sealed class PositionChanged : WeakEventManagerBase - { - /// - protected override void StartListening(Caret source) - { - source.PositionChanged += DeliverEvent; - } - - /// - protected override void StopListening(Caret source) - { - source.PositionChanged -= DeliverEvent; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/DottedLineMargin.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/DottedLineMargin.cs deleted file mode 100644 index 4b7329fcf..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/DottedLineMargin.cs +++ /dev/null @@ -1,78 +0,0 @@ -// 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 -{ - /// - /// Margin for use with the text area. - /// A vertical dotted line to separate the line numbers from the text view. - /// - public static class DottedLineMargin - { - static readonly object tag = new object(); - - /// - /// Creates a vertical dotted line to separate the line numbers from the text view. - /// - 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; - } - - /// - /// Creates a vertical dotted line to separate the line numbers from the text view. - /// - [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; - } - - /// - /// Gets whether the specified UIElement is the result of a DottedLineMargin.Create call. - /// - public static bool IsDottedLineMargin(UIElement element) - { - Line l = element as Line; - return l != null && l.Tag == tag; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/DragDropException.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/DragDropException.cs deleted file mode 100644 index 35aa109e3..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/DragDropException.cs +++ /dev/null @@ -1,61 +0,0 @@ -// 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 -{ - /// - /// 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. - /// - [Serializable()] - public class DragDropException : Exception - { - /// - /// Creates a new DragDropException. - /// - public DragDropException() : base() - { - } - - /// - /// Creates a new DragDropException. - /// - public DragDropException(string message) : base(message) - { - } - - /// - /// Creates a new DragDropException. - /// - public DragDropException(string message, Exception innerException) : base(message, innerException) - { - } - - /// - /// Deserializes a DragDropException. - /// - protected DragDropException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/EditingCommandHandler.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/EditingCommandHandler.cs deleted file mode 100644 index 8fa9500de..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/EditingCommandHandler.cs +++ /dev/null @@ -1,644 +0,0 @@ -// 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 -{ - /// - /// We re-use the CommandBinding and InputBinding instances between multiple text areas, - /// so this class is static. - /// - static class EditingCommandHandler - { - /// - /// Creates a new for the text area. - /// - public static TextAreaInputHandler Create(TextArea textArea) - { - TextAreaInputHandler handler = new TextAreaInputHandler(textArea); - handler.CommandBindings.AddRange(CommandBindings); - handler.InputBindings.AddRange(InputBindings); - return handler; - } - - static readonly List CommandBindings = new List(); - static readonly List InputBindings = new List(); - - 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 - } - - /// - /// Calls transformLine on all lines in the selected range. - /// transformLine needs to handle read-only segments! - /// - static void TransformSelectedLines(Action 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; - } - } - - /// - /// Calls transformLine on all writable segment in the selected range. - /// - static void TransformSelectedSegments(Action transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) - { - TextArea textArea = GetTextArea(target); - if (textArea != null && textArea.Document != null) { - using (textArea.Document.RunUpdate()) { - IEnumerable 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(); - } else { - segments = null; - } - } else { - segments = textArea.Selection.Segments.Cast(); - } - 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. - } - - 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; - - var pastingEventArgs = new DataObjectPastingEventArgs(dataObject, false, DataFormats.UnicodeText); - textArea.RaiseEvent(pastingEventArgs); - if (pastingEventArgs.CommandCancelled) - return; - - dataObject = pastingEventArgs.DataObject; - if (dataObject == null) - return; - - // convert text back to correct newlines for this document - string newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); - string text; - try { - // Try retrieving the text as one of: - // - the FormatToApply - // - UnicodeText - // - Text - // (but don't try the same format twice) - if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) - text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); - else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && dataObject.GetDataPresent(DataFormats.UnicodeText)) - text = (string)dataObject.GetData(DataFormats.UnicodeText); - else if (pastingEventArgs.FormatToApply != DataFormats.Text && dataObject.GetDataPresent(DataFormats.Text)) - text = (string)dataObject.GetData(DataFormats.Text); - else - return; // no text data format - text = TextUtilities.NormalizeNewLines(text, newLine); - } catch (OutOfMemoryException) { - // may happen when trying to paste a huge string - return; - } - - if (!string.IsNullOrEmpty(text)) { - bool fullLine = textArea.Options.CutCopyWholeLine && dataObject.GetDataPresent(LineSelectedType); - bool rectangular = dataObject.GetDataPresent(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 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; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/EmptySelection.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/EmptySelection.cs deleted file mode 100644 index 1f4320618..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/EmptySelection.cs +++ /dev/null @@ -1,105 +0,0 @@ -// 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 Segments { - get { return Empty.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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/IReadOnlySectionProvider.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/IReadOnlySectionProvider.cs deleted file mode 100644 index 5f37fc366..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/IReadOnlySectionProvider.cs +++ /dev/null @@ -1,51 +0,0 @@ -// 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 -{ - /// - /// Determines whether the document can be modified. - /// - public interface IReadOnlySectionProvider - { - /// - /// Gets whether insertion is possible at the specified offset. - /// - bool CanInsert(int offset); - - /// - /// Gets the deletable segments inside the given segment. - /// - /// - /// 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. - /// - IEnumerable GetDeletableSegments(ISegment segment); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/ImeNativeWrapper.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/ImeNativeWrapper.cs deleted file mode 100644 index 3a7157787..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/ImeNativeWrapper.cs +++ /dev/null @@ -1,221 +0,0 @@ -// 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 -{ - /// - /// Native API required for IME support. - /// - 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); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/ImeSupport.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/ImeSupport.cs deleted file mode 100644 index 591ee90ca..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/ImeSupport.cs +++ /dev/null @@ -1,165 +0,0 @@ -// 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); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/LineNumberMargin.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/LineNumberMargin.cs deleted file mode 100644 index 8a4c1be35..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/LineNumberMargin.cs +++ /dev/null @@ -1,263 +0,0 @@ -// 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 -{ - /// - /// Margin showing line numbers. - /// - public class LineNumberMargin : AbstractMargin, IWeakEventListener - { - static LineNumberMargin() - { - DefaultStyleKeyProperty.OverrideMetadata(typeof(LineNumberMargin), - new FrameworkPropertyMetadata(typeof(LineNumberMargin))); - } - - TextArea textArea; - - /// - /// The typeface used for rendering the line number margin. - /// This field is calculated in MeasureOverride() based on the FontFamily etc. properties. - /// - protected Typeface typeface; - - /// - /// The font size used for rendering the line number margin. - /// This field is calculated in MeasureOverride() based on the FontFamily etc. properties. - /// - protected double emSize; - - /// - 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); - } - - /// - 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)); - } - } - } - - /// - 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(); - } - - /// - 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(); - } - - /// - 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); - } - - /// - /// Maximum length of a line number, in characters - /// - 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; - - /// - 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); - } - textArea.Caret.BringCaretToView(5.0); - } - } - } - - SimpleSegment GetTextLineSegment(MouseEventArgs e) - { - Point pos = e.GetPosition(TextView); - pos.X = 0; - pos.Y = pos.Y.CoerceValue(0, TextView.ActualHeight); - 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); - } - } - - /// - 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); - textArea.Caret.BringCaretToView(5.0); - } - base.OnMouseMove(e); - } - - /// - protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) - { - if (selecting) { - selecting = false; - selectionStart = null; - ReleaseMouseCapture(); - e.Handled = true; - } - base.OnMouseLeftButtonUp(e); - } - - /// - protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters) - { - // accept clicks even when clicking on the background - return new PointHitTestResult(this, hitTestParameters.HitPoint); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/NoReadOnlySections.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/NoReadOnlySections.cs deleted file mode 100644 index dbafa600f..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/NoReadOnlySections.cs +++ /dev/null @@ -1,66 +0,0 @@ -// 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 -{ - /// - /// that has no read-only sections; all text is editable. - /// - sealed class NoReadOnlySections : IReadOnlySectionProvider - { - public static readonly NoReadOnlySections Instance = new NoReadOnlySections(); - - public bool CanInsert(int offset) - { - return true; - } - - public IEnumerable GetDeletableSegments(ISegment segment) - { - if (segment == null) - throw new ArgumentNullException("segment"); - // the segment is always deletable - return ExtensionMethods.Sequence(segment); - } - } - - /// - /// that completely disables editing. - /// - sealed class ReadOnlySectionDocument : IReadOnlySectionProvider - { - public static readonly ReadOnlySectionDocument Instance = new ReadOnlySectionDocument(); - - public bool CanInsert(int offset) - { - return false; - } - - public IEnumerable GetDeletableSegments(ISegment segment) - { - return Enumerable.Empty(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/RectangleSelection.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/RectangleSelection.cs deleted file mode 100644 index 8d6a99138..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/RectangleSelection.cs +++ /dev/null @@ -1,417 +0,0 @@ -// 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 -{ - /// - /// Rectangular selection ("box selection"). - /// - public sealed class RectangleSelection : Selection - { - #region Commands - /// - /// Expands the selection left by one character, creating a rectangular selection. - /// Key gesture: Alt+Shift+Left - /// - public static readonly RoutedUICommand BoxSelectLeftByCharacter = Command("BoxSelectLeftByCharacter"); - - /// - /// Expands the selection right by one character, creating a rectangular selection. - /// Key gesture: Alt+Shift+Right - /// - public static readonly RoutedUICommand BoxSelectRightByCharacter = Command("BoxSelectRightByCharacter"); - - /// - /// Expands the selection left by one word, creating a rectangular selection. - /// Key gesture: Ctrl+Alt+Shift+Left - /// - public static readonly RoutedUICommand BoxSelectLeftByWord = Command("BoxSelectLeftByWord"); - - /// - /// Expands the selection left by one word, creating a rectangular selection. - /// Key gesture: Ctrl+Alt+Shift+Right - /// - public static readonly RoutedUICommand BoxSelectRightByWord = Command("BoxSelectRightByWord"); - - /// - /// Expands the selection up by one line, creating a rectangular selection. - /// Key gesture: Alt+Shift+Up - /// - public static readonly RoutedUICommand BoxSelectUpByLine = Command("BoxSelectUpByLine"); - - /// - /// Expands the selection up by one line, creating a rectangular selection. - /// Key gesture: Alt+Shift+Down - /// - public static readonly RoutedUICommand BoxSelectDownByLine = Command("BoxSelectDownByLine"); - - /// - /// Expands the selection to the start of the line, creating a rectangular selection. - /// Key gesture: Alt+Shift+Home - /// - public static readonly RoutedUICommand BoxSelectToLineStart = Command("BoxSelectToLineStart"); - - /// - /// Expands the selection to the end of the line, creating a rectangular selection. - /// Key gesture: Alt+Shift+End - /// - 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 segments = new List(); - - #region Constructors - /// - /// Creates a new rectangular selection. - /// - 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 - - /// - 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(); - } - - /// - public override Selection StartSelectionOrSetEndpoint(TextViewPosition startPosition, TextViewPosition endPosition) - { - return SetEndpoint(endPosition); - } - - /// - public override int Length { - get { - return this.Segments.Sum(s => s.Length); - } - } - - /// - public override bool EnableVirtualSpace { - get { return true; } - } - - /// - public override ISegment SurroundingSegment { - get { - return new SimpleSegment(topLeftOffset, bottomRightOffset - topLeftOffset); - } - } - - /// - public override IEnumerable Segments { - get { return segments; } - } - - /// - public override TextViewPosition StartPosition { - get { return start; } - } - - /// - public override TextViewPosition EndPosition { - get { return end; } - } - - /// - 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; - } - - /// - public override int GetHashCode() - { - return topLeftOffset ^ bottomRightOffset; - } - - /// - 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); - } - - /// - 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))); - } - - /// - 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; - } - - /// - /// Performs a rectangular paste operation. - /// - 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; - } - - /// - /// Gets the name of the entry in the DataObject that signals rectangle selections. - /// - public const string RectangularSelectionDataType = "AvalonEditRectangularSelection"; - - /// - 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; - } - - /// - 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/Selection.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/Selection.cs deleted file mode 100644 index b25a31b05..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/Selection.cs +++ /dev/null @@ -1,302 +0,0 @@ -// 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 -{ - /// - /// Base class for selections. - /// - public abstract class Selection - { - /// - /// Creates a new simple selection that selects the text from startOffset to endOffset. - /// - 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); - } - - /// - /// Creates a new simple selection that selects the text in the specified segment. - /// - 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; - - /// - /// Constructor for Selection. - /// - protected Selection(TextArea textArea) - { - if (textArea == null) - throw new ArgumentNullException("textArea"); - this.textArea = textArea; - } - - /// - /// Gets the start position of the selection. - /// - public abstract TextViewPosition StartPosition { get; } - - /// - /// Gets the end position of the selection. - /// - public abstract TextViewPosition EndPosition { get; } - - /// - /// Gets the selected text segments. - /// - public abstract IEnumerable Segments { get; } - - /// - /// Gets the smallest segment that contains all segments in this selection. - /// May return null if the selection is empty. - /// - public abstract ISegment SurroundingSegment { get; } - - /// - /// Replaces the selection with the specified text. - /// - 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; - } - - /// - /// Updates the selection when the document changes. - /// - public abstract Selection UpdateOnDocumentChange(DocumentChangeEventArgs e); - - /// - /// Gets whether the selection is empty. - /// - public virtual bool IsEmpty { - get { return Length == 0; } - } - - /// - /// Gets whether virtual space is enabled for this selection. - /// - public virtual bool EnableVirtualSpace { - get { return textArea.Options.EnableVirtualSpace; } - } - - /// - /// Gets the selection length. - /// - public abstract int Length { get; } - - /// - /// Returns a new selection with the changed end point. - /// - /// Cannot set endpoint for empty selection - public abstract Selection SetEndpoint(TextViewPosition endPosition); - - /// - /// If this selection is empty, starts a new selection from to - /// , otherwise, changes the endpoint of this selection. - /// - public abstract Selection StartSelectionOrSetEndpoint(TextViewPosition startPosition, TextViewPosition endPosition); - - /// - /// Gets whether the selection is multi-line. - /// - 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); - } - } - - /// - /// Gets the selected text. - /// - 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; - } - } - - /// - /// Creates a HTML fragment for the selected text. - /// - 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("
"); - html.Append(HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, selectedSegment, options)); - } - return html.ToString(); - } - - /// - public abstract override bool Equals(object obj); - - /// - public abstract override int GetHashCode(); - - /// - /// Gets whether the specified offset is included in the selection. - /// - /// True, if the selection contains the offset (selection borders inclusive); - /// otherwise, false. - 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; - } - - /// - /// Creates a data object containing the selection's text. - /// - 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionColorizer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionColorizer.cs deleted file mode 100644 index 3c6be06c8..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionColorizer.cs +++ /dev/null @@ -1,74 +0,0 @@ -// 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); - }); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionLayer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionLayer.cs deleted file mode 100644 index ea13814ad..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionLayer.cs +++ /dev/null @@ -1,68 +0,0 @@ -// 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); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionMouseHandler.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionMouseHandler.cs deleted file mode 100644 index dcb2f1614..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionMouseHandler.cs +++ /dev/null @@ -1,676 +0,0 @@ -// 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 -{ - /// - /// Handles selection of text using the mouse. - /// - sealed class SelectionMouseHandler : ITextAreaInputHandler - { - #region enum SelectionMode - enum SelectionMode - { - /// - /// no selection (no mouse button down) - /// - None, - /// - /// left mouse button down on selection, might be normal click - /// or might be drag'n'drop - /// - PossibleDragStart, - /// - /// dragging text - /// - Drag, - /// - /// normal selection (click+drag) - /// - Normal, - /// - /// whole-word selection (double click+drag or ctrl+click+drag) - /// - WholeWord, - /// - /// whole-line selection (triple click+drag) - /// - WholeLine, - /// - /// rectangular selection (alt+click+drag) - /// - 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionSegment.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionSegment.cs deleted file mode 100644 index 6c0b1e7a3..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SelectionSegment.cs +++ /dev/null @@ -1,108 +0,0 @@ -// 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 -{ - /// - /// Represents a selected segment. - /// - public class SelectionSegment : ISegment - { - readonly int startOffset, endOffset; - readonly int startVC, endVC; - - /// - /// Creates a SelectionSegment from two offsets. - /// - public SelectionSegment(int startOffset, int endOffset) - { - this.startOffset = Math.Min(startOffset, endOffset); - this.endOffset = Math.Max(startOffset, endOffset); - this.startVC = this.endVC = -1; - } - - /// - /// Creates a SelectionSegment from two offsets and visual columns. - /// - 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; - } - } - - /// - /// Gets the start offset. - /// - public int StartOffset { - get { return startOffset; } - } - - /// - /// Gets the end offset. - /// - public int EndOffset { - get { return endOffset; } - } - - /// - /// Gets the start visual column. - /// - public int StartVisualColumn { - get { return startVC; } - } - - /// - /// Gets the end visual column. - /// - public int EndVisualColumn { - get { return endVC; } - } - - /// - int ISegment.Offset { - get { return startOffset; } - } - - /// - public int Length { - get { return endOffset - startOffset; } - } - - /// - public override string ToString() - { - return string.Format("[SelectionSegment StartOffset={0}, EndOffset={1}, StartVC={2}, EndVC={3}]", startOffset, endOffset, startVC, endVC); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SimpleSelection.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SimpleSelection.cs deleted file mode 100644 index 24f27825d..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SimpleSelection.cs +++ /dev/null @@ -1,174 +0,0 @@ -// 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 -{ - /// - /// A simple selection. - /// - sealed class SimpleSelection : Selection - { - readonly TextViewPosition start, end; - readonly int startOffset, endOffset; - - /// - /// Creates a new SimpleSelection instance. - /// - internal 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); - } - - /// - public override IEnumerable Segments { - get { - return ExtensionMethods.Sequence(new SelectionSegment(startOffset, start.VisualColumn, endOffset, end.VisualColumn)); - } - } - - /// - public override ISegment SurroundingSegment { - get { - return new SelectionSegment(startOffset, endOffset); - } - } - - /// - 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; } - } - - /// - 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) - ); - } - - /// - public override bool IsEmpty { - get { return startOffset == endOffset && start.VisualColumn == end.VisualColumn; } - } - - /// - public override int Length { - get { - return Math.Abs(endOffset - startOffset); - } - } - - /// - 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); - } - - /// - public override int GetHashCode() - { - unchecked { - return startOffset * 27811 + endOffset + textArea.GetHashCode(); - } - } - - /// - 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; - } - - /// - public override string ToString() - { - return "[SimpleSelection Start=" + start + " End=" + end + "]"; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextArea.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextArea.cs deleted file mode 100644 index 11dcf3e70..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextArea.cs +++ /dev/null @@ -1,1138 +0,0 @@ -// 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 -{ - /// - /// Control that wraps a TextView and adds support for user input and the caret. - /// - 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)); - } - - /// - /// Creates a new TextArea instance. - /// - public TextArea() : this(new TextView()) - { - } - - /// - /// Creates a new TextArea instance. - /// - 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 - /// - /// Gets the default input handler. - /// - /// - public TextAreaDefaultInputHandler DefaultInputHandler { get; private set; } - - ITextAreaInputHandler activeInputHandler; - bool isChangingInputHandler; - - /// - /// Gets/Sets the active input handler. - /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. - /// - /// - 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); - } - } - } - - /// - /// Occurs when the ActiveInputHandler property changes. - /// - public event EventHandler ActiveInputHandlerChanged; - - ImmutableStack stackedInputHandlers = ImmutableStack.Empty; - - /// - /// Gets the list of currently active stacked input handlers. - /// - /// - public ImmutableStack StackedInputHandlers { - get { return stackedInputHandlers; } - } - - /// - /// Pushes an input handler onto the list of stacked input handlers. - /// - /// - public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) - { - if (inputHandler == null) - throw new ArgumentNullException("inputHandler"); - stackedInputHandlers = stackedInputHandlers.Push(inputHandler); - inputHandler.Attach(); - } - - /// - /// Pops the stacked input handler (and all input handlers above it). - /// If is not found in the currently stacked input handlers, or is null, this method - /// does nothing. - /// - /// - 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 - /// - /// Document property. - /// - public static readonly DependencyProperty DocumentProperty - = TextView.DocumentProperty.AddOwner(typeof(TextArea), new FrameworkPropertyMetadata(OnDocumentChanged)); - - /// - /// Gets/Sets the document displayed by the text editor. - /// - public TextDocument Document { - get { return (TextDocument)GetValue(DocumentProperty); } - set { SetValue(DocumentProperty, value); } - } - - /// - 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 - /// - /// Options property. - /// - public static readonly DependencyProperty OptionsProperty - = TextView.OptionsProperty.AddOwner(typeof(TextArea), new FrameworkPropertyMetadata(OnOptionsChanged)); - - /// - /// Gets/Sets the document displayed by the text editor. - /// - public TextEditorOptions Options { - get { return (TextEditorOptions)GetValue(OptionsProperty); } - set { SetValue(OptionsProperty, value); } - } - - /// - /// Occurs when a text editor option has changed. - /// - public event PropertyChangedEventHandler OptionChanged; - - /// - /// Raises the event. - /// - 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 - /// - 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; - - /// - /// Gets the text view used to display text in this text area. - /// - public TextView TextView { - get { - return textView; - } - } - /// - public override void OnApplyTemplate() - { - base.OnApplyTemplate(); - scrollInfo = textView; - ApplyScrollInfo(); - } - #endregion - - #region Selection property - internal readonly Selection emptySelection; - Selection selection; - - /// - /// Occurs when the selection has changed. - /// - public event EventHandler SelectionChanged; - - /// - /// Gets/Sets the selection in this text area. - /// - - 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(); - } - } - } - - /// - /// Clears the current selection. - /// - public void ClearSelection() - { - this.Selection = emptySelection; - } - - /// - /// The property. - /// - public static readonly DependencyProperty SelectionBrushProperty = - DependencyProperty.Register("SelectionBrush", typeof(Brush), typeof(TextArea)); - - /// - /// Gets/Sets the background brush used for the selection. - /// - public Brush SelectionBrush { - get { return (Brush)GetValue(SelectionBrushProperty); } - set { SetValue(SelectionBrushProperty, value); } - } - - /// - /// The property. - /// - public static readonly DependencyProperty SelectionForegroundProperty = - DependencyProperty.Register("SelectionForeground", typeof(Brush), typeof(TextArea)); - - /// - /// Gets/Sets the foreground brush used selected text. - /// - public Brush SelectionForeground { - get { return (Brush)GetValue(SelectionForegroundProperty); } - set { SetValue(SelectionForegroundProperty, value); } - } - - /// - /// The property. - /// - public static readonly DependencyProperty SelectionBorderProperty = - DependencyProperty.Register("SelectionBorder", typeof(Pen), typeof(TextArea)); - - /// - /// Gets/Sets the background brush used for the selection. - /// - public Pen SelectionBorder { - get { return (Pen)GetValue(SelectionBorderProperty); } - set { SetValue(SelectionBorderProperty, value); } - } - - /// - /// The property. - /// - public static readonly DependencyProperty SelectionCornerRadiusProperty = - DependencyProperty.Register("SelectionCornerRadius", typeof(double), typeof(TextArea), - new FrameworkPropertyMetadata(3.0)); - - /// - /// Gets/Sets the corner radius of the selection. - /// - 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)); - } - } - - /// - /// 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. - /// - void EnsureSelectionValid() - { - ensureSelectionValidRequested = false; - if (allowCaretOutsideSelection == 0) { - if (!selection.IsEmpty && !selection.Contains(caret.Offset)) { - Debug.WriteLine("Resetting selection because caret is outside"); - this.ClearSelection(); - } - } - } - - /// - /// Temporarily allows positioning the caret outside the selection. - /// Dispose the returned IDisposable to revert the allowance. - /// - /// - /// 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. - /// - public IDisposable AllowCaretOutsideSelection() - { - VerifyAccess(); - allowCaretOutsideSelection++; - return new CallbackOnDispose( - delegate { - VerifyAccess(); - allowCaretOutsideSelection--; - RequestSelectionValidation(); - }); - } - #endregion - - #region Properties - readonly Caret caret; - - /// - /// Gets the Caret used for this text area. - /// - public Caret Caret { - get { return caret; } - } - - void CaretPositionChanged(object sender, EventArgs e) - { - if (textView == null) - return; - - this.textView.HighlightedLine = this.Caret.Line; - } - - ObservableCollection leftMargins = new ObservableCollection(); - - /// - /// Gets the collection of margins displayed to the left of the text view. - /// - public ObservableCollection LeftMargins { - get { - return leftMargins; - } - } - - void leftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) - { - if (e.OldItems != null) { - foreach (ITextViewConnect c in e.OldItems.OfType()) { - c.RemoveFromTextView(textView); - } - } - if (e.NewItems != null) { - foreach (ITextViewConnect c in e.NewItems.OfType()) { - c.AddToTextView(textView); - } - } - } - - IReadOnlySectionProvider readOnlySectionProvider = NoReadOnlySections.Instance; - - /// - /// Gets/Sets an object that provides read-only sections for the text area. - /// - 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) - /// - protected override void OnMouseDown(MouseButtonEventArgs e) - { - base.OnMouseDown(e); - Focus(); - } - - /// - protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e) - { - base.OnGotKeyboardFocus(e); - // First activate IME, then show caret - ime.OnGotKeyboardFocus(e); - caret.Show(); - } - - /// - protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e) - { - base.OnLostKeyboardFocus(e); - caret.Hide(); - ime.OnLostKeyboardFocus(e); - } - #endregion - - #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText - /// - /// Occurs when the TextArea receives text input. - /// This is like the event, - /// but occurs immediately before the TextArea handles the TextInput event. - /// - public event TextCompositionEventHandler TextEntering; - - /// - /// Occurs when the TextArea receives text input. - /// This is like the event, - /// but occurs immediately after the TextArea handles the TextInput event. - /// - public event TextCompositionEventHandler TextEntered; - - /// - /// Raises the TextEntering event. - /// - protected virtual void OnTextEntering(TextCompositionEventArgs e) - { - if (TextEntering != null) { - TextEntering(this, e); - } - } - - /// - /// Raises the TextEntered event. - /// - protected virtual void OnTextEntered(TextCompositionEventArgs e) - { - if (TextEntered != null) { - TextEntered(this, e); - } - } - - /// - 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; - } - } - - /// - /// Performs text input. - /// This raises the event, replaces the selection with the text, - /// and then raises the event. - /// - 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); - } - - /// - /// Performs text input. - /// This raises the event, replaces the selection with the text, - /// and then raises the event. - /// - 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 - /// - /// IndentationStrategy property. - /// - public static readonly DependencyProperty IndentationStrategyProperty = - DependencyProperty.Register("IndentationStrategy", typeof(IIndentationStrategy), typeof(TextArea), - new FrameworkPropertyMetadata(new DefaultIndentationStrategy())); - - /// - /// Gets/Sets the indentation strategy used when inserting new lines. - /// - public IIndentationStrategy IndentationStrategy { - get { return (IIndentationStrategy)GetValue(IndentationStrategyProperty); } - set { SetValue(IndentationStrategyProperty, value); } - } - #endregion - - #region OnKeyDown/OnKeyUp - /// - 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); - } - } - - /// - 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. - /// - protected override void OnKeyDown(KeyEventArgs e) - { - base.OnKeyDown(e); - TextView.InvalidateCursorIfMouseWithinTextView(); - } - - /// - 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 - - /// - /// The dependency property. - /// - public static readonly DependencyProperty OverstrikeModeProperty = - DependencyProperty.Register("OverstrikeMode", typeof(bool), typeof(TextArea), - new FrameworkPropertyMetadata(Boxes.False)); - - /// - /// Gets/Sets whether overstrike mode is active. - /// - public bool OverstrikeMode { - get { return (bool)GetValue(OverstrikeModeProperty); } - set { SetValue(OverstrikeModeProperty, value); } - } - - #endregion - - /// - protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters) - { - // accept clicks even where the text area draws no background - return new PointHitTestResult(this, hitTestParameters.HitPoint); - } - - /// - 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(); - } - } - - /// - /// Gets the requested service. - /// - /// Returns the requested service instance, or null if the service cannot be found. - public virtual object GetService(Type serviceType) - { - return textView.GetService(serviceType); - } - - /// - /// Occurs when text inside the TextArea was copied. - /// - public event EventHandler TextCopied; - - internal void OnTextCopied(TextEventArgs e) - { - if (TextCopied != null) - TextCopied(this, e); - } - } - - /// - /// EventArgs with text. - /// - [Serializable] - public class TextEventArgs : EventArgs - { - string text; - - /// - /// Gets the text. - /// - public string Text { - get { - return text; - } - } - - /// - /// Creates a new TextEventArgs instance. - /// - public TextEventArgs(string text) - { - if (text == null) - throw new ArgumentNullException("text"); - this.text = text; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextAreaDefaultInputHandlers.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextAreaDefaultInputHandlers.cs deleted file mode 100644 index 432138fd3..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextAreaDefaultInputHandlers.cs +++ /dev/null @@ -1,135 +0,0 @@ -// 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 -{ - /// - /// Contains the predefined input handlers. - /// - public class TextAreaDefaultInputHandler : TextAreaInputHandler - { - /// - /// Gets the caret navigation input handler. - /// - public TextAreaInputHandler CaretNavigation { get; private set; } - - /// - /// Gets the editing input handler. - /// - public TextAreaInputHandler Editing { get; private set; } - - /// - /// Gets the mouse selection input handler. - /// - public ITextAreaInputHandler MouseSelection { get; private set; } - - /// - /// Creates a new TextAreaDefaultInputHandler instance. - /// - 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 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextAreaInputHandler.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextAreaInputHandler.cs deleted file mode 100644 index 22ee7564f..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextAreaInputHandler.cs +++ /dev/null @@ -1,257 +0,0 @@ -// 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 -{ - /// - /// A set of input bindings and event handlers for the text area. - /// - /// - /// - /// There is one active input handler per text area (), plus - /// a number of active stacked input handlers. - /// - /// - /// The text area also stores a reference to a default input handler, but that is not necessarily active. - /// - /// - /// 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. - /// - /// - public interface ITextAreaInputHandler - { - /// - /// Gets the text area that the input handler belongs to. - /// - TextArea TextArea { - get; - } - - /// - /// Attaches an input handler to the text area. - /// - void Attach(); - - /// - /// Detaches the input handler from the text area. - /// - void Detach(); - } - - /// - /// Stacked input handler. - /// Uses OnEvent-methods instead of registering event handlers to ensure that the events are handled in the correct order. - /// - public abstract class TextAreaStackedInputHandler : ITextAreaInputHandler - { - readonly TextArea textArea; - - /// - public TextArea TextArea { - get { return textArea; } - } - - /// - /// Creates a new TextAreaInputHandler. - /// - protected TextAreaStackedInputHandler(TextArea textArea) - { - if (textArea == null) - throw new ArgumentNullException("textArea"); - this.textArea = textArea; - } - - /// - public virtual void Attach() - { - } - - /// - public virtual void Detach() - { - } - - /// - /// Called for the PreviewKeyDown event. - /// - public virtual void OnPreviewKeyDown(KeyEventArgs e) - { - } - - /// - /// Called for the PreviewKeyUp event. - /// - public virtual void OnPreviewKeyUp(KeyEventArgs e) - { - } - } - - /// - /// Default-implementation of . - /// - /// - public class TextAreaInputHandler : ITextAreaInputHandler - { - readonly ObserveAddRemoveCollection commandBindings; - readonly ObserveAddRemoveCollection inputBindings; - readonly ObserveAddRemoveCollection nestedInputHandlers; - readonly TextArea textArea; - bool isAttached; - - /// - /// Creates a new TextAreaInputHandler. - /// - public TextAreaInputHandler(TextArea textArea) - { - if (textArea == null) - throw new ArgumentNullException("textArea"); - this.textArea = textArea; - commandBindings = new ObserveAddRemoveCollection(CommandBinding_Added, CommandBinding_Removed); - inputBindings = new ObserveAddRemoveCollection(InputBinding_Added, InputBinding_Removed); - nestedInputHandlers = new ObserveAddRemoveCollection(NestedInputHandler_Added, NestedInputHandler_Removed); - } - - /// - public TextArea TextArea { - get { return textArea; } - } - - /// - /// Gets whether the input handler is currently attached to the text area. - /// - public bool IsAttached { - get { return isAttached; } - } - - #region CommandBindings / InputBindings - /// - /// Gets the command bindings of this input handler. - /// - public ICollection 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); - } - - /// - /// Gets the input bindings of this input handler. - /// - public ICollection 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); - } - - /// - /// Adds a command and input binding. - /// - /// The command ID. - /// The modifiers of the keyboard shortcut. - /// The key of the keyboard shortcut. - /// The event handler to run when the command is executed. - 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 - /// - /// Gets the collection of nested input handlers. NestedInputHandlers are activated and deactivated - /// together with this input handler. - /// - public ICollection 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 - /// - 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(); - } - - /// - 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextSegmentReadOnlySectionProvider.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextSegmentReadOnlySectionProvider.cs deleted file mode 100644 index fb2662471..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Editing/TextSegmentReadOnlySectionProvider.cs +++ /dev/null @@ -1,103 +0,0 @@ -// 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 -{ - /// - /// Implementation for that stores the segments - /// in a . - /// - public class TextSegmentReadOnlySectionProvider : IReadOnlySectionProvider where T : TextSegment - { - readonly TextSegmentCollection segments; - - /// - /// Gets the collection storing the read-only segments. - /// - public TextSegmentCollection Segments { - get { return segments; } - } - - /// - /// Creates a new TextSegmentReadOnlySectionProvider instance for the specified document. - /// - public TextSegmentReadOnlySectionProvider(TextDocument textDocument) - { - segments = new TextSegmentCollection(textDocument); - } - - /// - /// Creates a new TextSegmentReadOnlySectionProvider instance using the specified TextSegmentCollection. - /// - public TextSegmentReadOnlySectionProvider(TextSegmentCollection segments) - { - if (segments == null) - throw new ArgumentNullException("segments"); - this.segments = segments; - } - - /// - /// Gets whether insertion is possible at the specified offset. - /// - public virtual bool CanInsert(int offset) - { - foreach (TextSegment segment in segments.FindSegmentsContaining(offset)) { - if (segment.StartOffset < offset && offset < segment.EndOffset) - return false; - } - return true; - } - - /// - /// Gets the deletable segments inside the given segment. - /// - public virtual IEnumerable 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); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingElementGenerator.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingElementGenerator.cs deleted file mode 100644 index 6b9072083..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingElementGenerator.cs +++ /dev/null @@ -1,210 +0,0 @@ -// 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 -{ - /// - /// A that produces line elements for folded s. - /// - public sealed class FoldingElementGenerator : VisualLineElementGenerator, ITextViewConnect - { - readonly List textViews = new List(); - FoldingManager foldingManager; - - #region FoldingManager property / connecting with TextView - /// - /// Gets/Sets the folding manager from which the foldings should be shown. - /// - 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 - - /// - 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"); - } - } - - /// - 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; - } - } - - /// - 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); - } - } - - /// - /// Default brush for folding element text. Value: Brushes.Gray - /// - public static readonly Brush DefaultTextBrush = Brushes.Gray; - - static Brush textBrush = DefaultTextBrush; - - /// - /// Gets/sets the brush used for folding element text. - /// - public static Brush TextBrush { - get { return textBrush; } - set { textBrush = value; } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingManager.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingManager.cs deleted file mode 100644 index 33767b4fa..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingManager.cs +++ /dev/null @@ -1,397 +0,0 @@ -// 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 -{ - /// - /// Stores a list of foldings for a specific TextView and TextDocument. - /// - public class FoldingManager : IWeakEventListener - { - internal readonly TextDocument document; - - internal readonly List textViews = new List(); - readonly TextSegmentCollection foldings; - bool isFirstUpdate = true; - - #region Constructor - /// - /// Creates a new FoldingManager instance. - /// - public FoldingManager(TextDocument document) - { - if (document == null) - throw new ArgumentNullException("document"); - this.document = document; - this.foldings = new TextSegmentCollection(); - document.VerifyAccess(); - TextDocumentWeakEventManager.Changed.AddListener(document, this); - } - #endregion - - #region 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 - /// - /// Creates a folding for the specified text section. - /// - 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; - } - - /// - /// Removes a folding section from this manager. - /// - public void RemoveFolding(FoldingSection fs) - { - if (fs == null) - throw new ArgumentNullException("fs"); - fs.IsFolded = false; - foldings.Remove(fs); - Redraw(fs); - } - - /// - /// Removes all folding sections. - /// - public void Clear() - { - document.VerifyAccess(); - foreach (FoldingSection s in foldings) - s.IsFolded = false; - foldings.Clear(); - Redraw(); - } - #endregion - - #region Get...Folding - /// - /// 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. - /// - public IEnumerable AllFoldings { - get { return foldings; } - } - - /// - /// Gets the first offset greater or equal to where a folded folding starts. - /// Returns -1 if there are no foldings after . - /// - 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; - } - - /// - /// Gets the first folding with a greater or equal to - /// . - /// Returns null if there are no foldings after . - /// - public FoldingSection GetNextFolding(int startOffset) - { - // TODO: returns the longest folding instead of any folding at the first position after startOffset - return foldings.FindFirstSegmentWithStartAfter(startOffset); - } - - /// - /// Gets all foldings that start exactly at . - /// - public ReadOnlyCollection GetFoldingsAt(int startOffset) - { - List result = new List(); - FoldingSection fs = foldings.FindFirstSegmentWithStartAfter(startOffset); - while (fs != null && fs.StartOffset == startOffset) { - result.Add(fs); - fs = foldings.GetNextSegment(fs); - } - return result.AsReadOnly(); - } - - /// - /// Gets all foldings that contain . - /// - public ReadOnlyCollection GetFoldingsContaining(int offset) - { - return foldings.FindSegmentsContaining(offset); - } - #endregion - - #region UpdateFoldings - /// - /// Updates the foldings in this using the given new foldings. - /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state - /// () for existing foldings. - /// - /// The new set of foldings. These must be sorted by starting offset. - /// The first position of a parse error. Existing foldings starting after - /// this offset will be kept even if they don't appear in . - /// Use -1 for this parameter if there were no parse errors. - public void UpdateFoldings(IEnumerable 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 - /// - /// 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. - /// - /// The that manages the list of foldings inside the text area. - public static FoldingManager Install(TextArea textArea) - { - if (textArea == null) - throw new ArgumentNullException("textArea"); - return new FoldingManagerInstallation(textArea); - } - - /// - /// Uninstalls the folding manager. - /// - /// The specified manager was not created using . - 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingMargin.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingMargin.cs deleted file mode 100644 index a5da8a0e4..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingMargin.cs +++ /dev/null @@ -1,350 +0,0 @@ -// 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 -{ - /// - /// A margin that shows markers for foldings and allows to expand/collapse the foldings. - /// - public class FoldingMargin : AbstractMargin - { - /// - /// Gets/Sets the folding manager from which the foldings should be shown. - /// - public FoldingManager FoldingManager { get; set; } - - internal const double SizeFactor = Constants.PixelPerPoint; - - #region Brushes - /// - /// FoldingMarkerBrush dependency property. - /// - public static readonly DependencyProperty FoldingMarkerBrushProperty = - DependencyProperty.RegisterAttached("FoldingMarkerBrush", typeof(Brush), typeof(FoldingMargin), - new FrameworkPropertyMetadata(Brushes.Gray, FrameworkPropertyMetadataOptions.Inherits, OnUpdateBrushes)); - - /// - /// Gets/sets the Brush used for displaying the lines of folding markers. - /// - public Brush FoldingMarkerBrush { - get { return (Brush)GetValue(FoldingMarkerBrushProperty); } - set { SetValue(FoldingMarkerBrushProperty, value); } - } - - /// - /// FoldingMarkerBackgroundBrush dependency property. - /// - public static readonly DependencyProperty FoldingMarkerBackgroundBrushProperty = - DependencyProperty.RegisterAttached("FoldingMarkerBackgroundBrush", typeof(Brush), typeof(FoldingMargin), - new FrameworkPropertyMetadata(Brushes.White, FrameworkPropertyMetadataOptions.Inherits, OnUpdateBrushes)); - - /// - /// Gets/sets the Brush used for displaying the background of folding markers. - /// - public Brush FoldingMarkerBackgroundBrush { - get { return (Brush)GetValue(FoldingMarkerBackgroundBrushProperty); } - set { SetValue(FoldingMarkerBackgroundBrushProperty, value); } - } - - /// - /// SelectedFoldingMarkerBrush dependency property. - /// - public static readonly DependencyProperty SelectedFoldingMarkerBrushProperty = - DependencyProperty.RegisterAttached("SelectedFoldingMarkerBrush", - typeof(Brush), typeof(FoldingMargin), - new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.Inherits, OnUpdateBrushes)); - - /// - /// Gets/sets the Brush used for displaying the lines of selected folding markers. - /// - public Brush SelectedFoldingMarkerBrush { - get { return (Brush)GetValue(SelectedFoldingMarkerBrushProperty); } - set { SetValue(SelectedFoldingMarkerBrushProperty, value); } - } - - /// - /// SelectedFoldingMarkerBackgroundBrush dependency property. - /// - public static readonly DependencyProperty SelectedFoldingMarkerBackgroundBrushProperty = - DependencyProperty.RegisterAttached("SelectedFoldingMarkerBackgroundBrush", - typeof(Brush), typeof(FoldingMargin), - new FrameworkPropertyMetadata(Brushes.White, FrameworkPropertyMetadataOptions.Inherits, OnUpdateBrushes)); - - /// - /// Gets/sets the Brush used for displaying the background of selected folding markers. - /// - 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 - - /// - 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); - } - - /// - 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); - } - - /// - 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 markers = new List(); - - 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; - } - } - } - } - - /// - protected override int VisualChildrenCount { - get { return markers.Count; } - } - - /// - 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; - } - - /// - 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); - } - - /// - /// Calculates fold lines for all folding sections that start in front of the current view - /// and run into the current view. - /// - void CalculateFoldLinesForFoldingsActiveAtStart(List 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; - } - } - } - } - - /// - /// Calculates fold lines for all folding sections that start inside the current view - /// - void CalculateFoldLinesForMarkers(List 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; - } - } - } - } - - /// - /// 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. - /// - 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 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingMarginMarker.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingMarginMarker.cs deleted file mode 100644 index 93859f08b..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingMarginMarker.cs +++ /dev/null @@ -1,103 +0,0 @@ -// 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(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingSection.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingSection.cs deleted file mode 100644 index c84a962f8..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/FoldingSection.cs +++ /dev/null @@ -1,203 +0,0 @@ -// 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 -{ - /// - /// A section that can be folded. - /// - public sealed class FoldingSection : TextSegment - { - readonly FoldingManager manager; - bool isFolded; - internal CollapsedLineSection[] collapsedSections; - string title; - - /// - /// Gets/sets if the section is folded. - /// - 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); - } - } - } - } - - /// - 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); - } - - /// - /// Gets/Sets the text used to display the collapsed version of the folding section. - /// - public string Title { - get { - return title; - } - set { - if (title != value) { - title = value; - if (this.IsFolded) - manager.Redraw(this); - } - } - } - - /// - /// Gets the content of the collapsed lines as text. - /// - public string TextContent { - get { - return manager.document.GetText(StartOffset, EndOffset - StartOffset); - } - } - - /// - /// Gets the content of the collapsed lines as tooltip text. - /// - [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(); - } - } - - /// - /// Gets/Sets an additional object associated with this folding section. - /// - 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; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/NewFolding.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Folding/NewFolding.cs deleted file mode 100644 index 5e6205a50..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/NewFolding.cs +++ /dev/null @@ -1,87 +0,0 @@ -// 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 -{ - /// - /// Helper class used for . - /// - public class NewFolding : ISegment - { - /// - /// Gets/Sets the start offset. - /// - public int StartOffset { get; set; } - - /// - /// Gets/Sets the end offset. - /// - public int EndOffset { get; set; } - - /// - /// Gets/Sets the name displayed for the folding. - /// - public string Name { get; set; } - - /// - /// Gets/Sets whether the folding is closed by default. - /// - public bool DefaultClosed { get; set; } - - /// - /// Gets/Sets whether the folding is considered to be a definition. - /// This has an effect on the 'Show Definitions only' command. - /// - public bool IsDefinition { get; set; } - - /// - /// Creates a new NewFolding instance. - /// - public NewFolding() - { - } - - /// - /// Creates a new NewFolding instance. - /// - 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; } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/XmlFoldingStrategy.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Folding/XmlFoldingStrategy.cs deleted file mode 100644 index 7f502295f..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Folding/XmlFoldingStrategy.cs +++ /dev/null @@ -1,240 +0,0 @@ -// 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 -{ - /// - /// Holds information about the start of a fold in an xml string. - /// - sealed class XmlFoldStart : NewFolding - { - internal int StartLine; - } - - /// - /// Determines folds for an xml string in the editor. - /// - public class XmlFoldingStrategy - { - /// - /// Flag indicating whether attributes should be displayed on folded - /// elements. - /// - public bool ShowAttributesWhenFolded { get; set; } - - /// - /// Create s for the specified document and updates the folding manager with them. - /// - public void UpdateFoldings(FoldingManager manager, TextDocument document) - { - int firstErrorOffset; - IEnumerable foldings = CreateNewFoldings(document, out firstErrorOffset); - manager.UpdateFoldings(foldings, firstErrorOffset); - } - - /// - /// Create s for the specified document. - /// - public IEnumerable 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(); - } - } - - /// - /// Create s for the specified document. - /// - public IEnumerable CreateNewFoldings(TextDocument document, XmlReader reader, out int firstErrorOffset) - { - Stack stack = new Stack(); - List foldMarkers = new List(); - 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."); - } - } - - /// - /// Creates a comment fold if the comment spans more than one line. - /// - /// The text displayed when the comment is folded is the first - /// line of the comment. - static void CreateCommentFold(TextDocument document, List 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 "); - foldMarkers.Add(new NewFolding(startOffset, endOffset) { Name = foldText } ); - } - } - } - - /// - /// Creates an XmlFoldStart for the start tag of an element. - /// - 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; - } - - /// - /// Create an element fold if the start and end tag are on - /// different lines. - /// - static void CreateElementFold(TextDocument document, List 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); - } - } - - /// - /// Gets the element's attributes as a string on one line that will - /// be displayed when the element is folded. - /// - /// - /// 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. - /// - 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(); - } - - /// - /// 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. - /// - static string XmlEncodeAttributeValue(string attributeValue, char quoteChar) - { - StringBuilder encodedValue = new StringBuilder(attributeValue); - - encodedValue.Replace("&", "&"); - encodedValue.Replace("<", "<"); - encodedValue.Replace(">", ">"); - - if (quoteChar == '"') { - encodedValue.Replace("\"", """); - } else { - encodedValue.Replace("'", "'"); - } - - return encodedValue.ToString(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/DocumentHighlighter.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/DocumentHighlighter.cs deleted file mode 100644 index 406dd1943..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/DocumentHighlighter.cs +++ /dev/null @@ -1,357 +0,0 @@ -// 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; - -namespace ICSharpCode.AvalonEdit.Highlighting -{ - /// - /// This class can syntax-highlight a document. - /// It automatically manages invalidating the highlighting when the document changes. - /// - public class DocumentHighlighter : ILineTracker, IHighlighter - { - /// - /// Stores the span state at the end of each line. - /// storedSpanStacks[0] = state at beginning of document - /// storedSpanStacks[i] = state after line i - /// - readonly CompressingTreeList storedSpanStacks = new CompressingTreeList(object.ReferenceEquals); - readonly CompressingTreeList isValid = new CompressingTreeList((a, b) => a == b); - readonly IDocument document; - readonly IHighlightingDefinition definition; - readonly HighlightingEngine engine; - readonly WeakLineTracker weakLineTracker; - bool isHighlighting; - bool isInHighlightingGroup; - bool isDisposed; - - /// - /// Gets the document that this DocumentHighlighter is highlighting. - /// - public IDocument Document { - get { return document; } - } - - /// - /// Creates a new DocumentHighlighter instance. - /// - 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); - InvalidateSpanStacks(); - } - - #if NREFACTORY - /// - /// Creates a new DocumentHighlighter instance. - /// - 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 - - /// - /// Disposes the document highlighter. - /// - 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() - { - InvalidateSpanStacks(); - } - - void ILineTracker.ChangeComplete(DocumentChangeEventArgs e) - { - } - - ImmutableStack initialSpanStack = SpanStack.Empty; - - /// - /// Gets/sets the the initial span stack of the document. Default value is . - /// - public ImmutableStack InitialSpanStack { - get { return initialSpanStack; } - set { - initialSpanStack = value ?? SpanStack.Empty; - InvalidateHighlighting(); - } - } - - /// - /// 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. - /// - public void InvalidateHighlighting() - { - InvalidateSpanStacks(); - OnHighlightStateChanged(1, document.LineCount); // force a redraw with the new highlighting - } - - /// - /// Invalidates stored highlighting info, but does not raise the HighlightingStateChanged event. - /// - void InvalidateSpanStacks() - { - 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; - - /// - 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; - } - } - - /// - /// Gets the span stack at the end of the specified line. - /// -> GetSpanStack(1) returns the spans at the start of the second line. - /// - /// - /// GetSpanStack(0) is valid and will return . - /// The elements are returned in inside-out order (first element of result enumerable is the color of the innermost span). - /// - public SpanStack GetSpanStack(int lineNumber) - { - ThrowUtil.CheckInRangeInclusive(lineNumber, "lineNumber", 0, document.LineCount); - if (firstInvalidLine <= lineNumber) { - UpdateHighlightingState(lineNumber); - } - return storedSpanStacks[lineNumber]; - } - - /// - public IEnumerable 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."); - } - } - - /// - public void UpdateHighlightingState(int lineNumber) - { - CheckIsHighlighting(); - isHighlighting = true; - try { - HighlightUpTo(lineNumber); - } finally { - isHighlighting = false; - } - } - - /// - /// 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. - /// - 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; - } - - /// - public event HighlightingStateChangedEventHandler HighlightingStateChanged; - - /// - /// Is called when the highlighting state at the end of the specified line has changed. - /// - /// 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. - protected virtual void OnHighlightStateChanged(int fromLineNumber, int toLineNumber) - { - if (HighlightingStateChanged != null) - HighlightingStateChanged(fromLineNumber, toLineNumber); - } - - /// - public HighlightingColor DefaultTextColor { - get { return null; } - } - - /// - public void BeginHighlighting() - { - if (isInHighlightingGroup) - throw new InvalidOperationException("Highlighting group is already open"); - isInHighlightingGroup = true; - } - - /// - public void EndHighlighting() - { - if (!isInHighlightingGroup) - throw new InvalidOperationException("Highlighting group is not open"); - isInHighlightingGroup = false; - } - - /// - public HighlightingColor GetNamedColor(string name) - { - return definition.GetNamedColor(name); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightedInlineBuilder.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightedInlineBuilder.cs deleted file mode 100644 index 97ada1628..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightedInlineBuilder.cs +++ /dev/null @@ -1,205 +0,0 @@ -// 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 -{ - /// - /// Takes a series of highlighting commands and stores them. - /// Later, it can build inline objects (for use with WPF TextBlock) from the commands. - /// - /// - /// 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. - /// - [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 stateChangeOffsets = new List(); - List stateChanges = new List(); - - 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; - } - - /// - /// Creates a new HighlightedInlineBuilder instance. - /// - public HighlightedInlineBuilder(string text) - { - if (text == null) - throw new ArgumentNullException("text"); - this.text = text; - stateChangeOffsets.Add(0); - stateChanges.Add(new HighlightingColor()); - } - - /// - /// Creates a new HighlightedInlineBuilder instance. - /// - 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 offsets, List states) - { - this.text = text; - stateChangeOffsets = offsets; - stateChanges = states; - } - - /// - /// Gets the text. - /// - public string Text { - get { return text; } - } - - /// - /// Applies the properties from the HighlightingColor to the specified text segment. - /// - 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 && color.Underline == 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); - } - } - - /// - /// Sets the foreground brush on the specified text segment. - /// - 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; - } - } - - /// - /// Sets the background brush on the specified text segment. - /// - 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; - } - } - - /// - /// Sets the font weight on the specified text segment. - /// - 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; - } - } - - /// - /// Sets the font style on the specified text segment. - /// - 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; - } - } - - /// - /// Creates WPF Run instances that can be used for TextBlock.Inlines. - /// - public Run[] CreateRuns() - { - return ToRichText().CreateRuns(); - } - - /// - /// Creates a RichText instance. - /// - public RichText ToRichText() - { - return new RichText(text, stateChangeOffsets.ToArray(), stateChanges.Select(FreezableHelper.GetFrozenClone).ToArray()); - } - - /// - /// Clones this HighlightedInlineBuilder. - /// - public HighlightedInlineBuilder Clone() - { - return new HighlightedInlineBuilder(this.text, - stateChangeOffsets.ToList(), - stateChanges.Select(sc => sc.Clone()).ToList()); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightedLine.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightedLine.cs deleted file mode 100644 index 55842a1d8..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightedLine.cs +++ /dev/null @@ -1,335 +0,0 @@ -// 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 -{ - /// - /// Represents a highlighted document line. - /// - public class HighlightedLine - { - /// - /// Creates a new HighlightedLine instance. - /// - 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(); - } - - /// - /// Gets the document associated with this HighlightedLine. - /// - public IDocument Document { get; private set; } - - /// - /// Gets the document line associated with this HighlightedLine. - /// - public IDocumentLine DocumentLine { get; private set; } - - /// - /// 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. - /// - public IList Sections { get; private set; } - - /// - /// Validates that the sections are sorted correctly, and that they are not overlapping. - /// - /// - 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 - /// - /// Merges the additional line into this line. - /// - public void MergeWith(HighlightedLine additionalLine) - { - if (additionalLine == null) - return; - #if DEBUG - ValidateInvariants(); - additionalLine.ValidateInvariants(); - #endif - - int pos = 0; - Stack activeSectionEndOffsets = new Stack(); - 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 insertionStack = new Stack(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 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 - { - 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); - } - } - } - - /// - /// Writes the highlighted line to the RichTextWriter. - /// - internal void WriteTo(RichTextWriter writer) - { - int startOffset = this.DocumentLine.Offset; - WriteTo(writer, startOffset, startOffset + this.DocumentLine.Length); - } - - /// - /// Writes a part of the highlighted line to the RichTextWriter. - /// - 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 elements = new List(); - 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); - } - - /// - /// Produces HTML code for the line, with <span class="colorName"> tags. - /// - public string ToHtml(HtmlOptions options = null) - { - StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); - using (var htmlWriter = new HtmlRichTextWriter(stringWriter, options)) { - WriteTo(htmlWriter); - } - return stringWriter.ToString(); - } - - /// - /// Produces HTML code for a section of the line, with <span class="colorName"> tags. - /// - 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(); - } - - /// - public override string ToString() - { - return "[" + GetType().Name + " " + ToHtml() + "]"; - } - #endregion - - /// - /// Creates a that stores the text and highlighting of this line. - /// - [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; - } - - /// - /// Creates a that stores the highlighting of this line. - /// - 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; - } - - /// - /// Creates a that stores the text and highlighting of this line. - /// - public RichText ToRichText() - { - return new RichText(Document.GetText(DocumentLine), ToRichTextModel()); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightedSection.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightedSection.cs deleted file mode 100644 index f1ffdfd9e..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightedSection.cs +++ /dev/null @@ -1,58 +0,0 @@ -// 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 -{ - /// - /// A text section with syntax highlighting information. - /// - public class HighlightedSection : ISegment - { - /// - /// Gets/sets the document offset of the section. - /// - public int Offset { get; set; } - - /// - /// Gets/sets the length of the section. - /// - public int Length { get; set; } - - int ISegment.EndOffset { - get { return this.Offset + this.Length; } - } - - /// - /// Gets the highlighting color associated with the highlighted section. - /// - public HighlightingColor Color { get; set; } - - /// - public override string ToString() - { - return string.Format("[HighlightedSection ({0}-{1})={2}]", Offset, Offset + Length, Color); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingBrush.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingBrush.cs deleted file mode 100644 index 401f751c2..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingBrush.cs +++ /dev/null @@ -1,165 +0,0 @@ -// 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 -{ - /// - /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. - /// - [Serializable] - public abstract class HighlightingBrush - { - /// - /// Gets the real brush. - /// - /// The construction context. context can be null! - public abstract Brush GetBrush(ITextRunConstructionContext context); - - /// - /// Gets the color of the brush. - /// - /// The construction context. context can be null! - public virtual Color? GetColor(ITextRunConstructionContext context) - { - SolidColorBrush scb = GetBrush(context) as SolidColorBrush; - if (scb != null) - return scb.Color; - else - return null; - } - } - - /// - /// Highlighting brush implementation that takes a frozen brush. - /// - [Serializable] - public sealed class SimpleHighlightingBrush : HighlightingBrush, ISerializable - { - readonly SolidColorBrush brush; - - internal SimpleHighlightingBrush(SolidColorBrush brush) - { - brush.Freeze(); - this.brush = brush; - } - - /// - /// Creates a new HighlightingBrush with the specified color. - /// - public SimpleHighlightingBrush(Color color) : this(new SolidColorBrush(color)) {} - - /// - public override Brush GetBrush(ITextRunConstructionContext context) - { - return brush; - } - - /// - 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)); - } - - /// - public override bool Equals(object obj) - { - SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; - if (other == null) - return false; - return this.brush.Color.Equals(other.brush.Color); - } - - /// - public override int GetHashCode() - { - return brush.Color.GetHashCode(); - } - } - - /// - /// HighlightingBrush implementation that finds a brush using a resource. - /// - [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(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingColor.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingColor.cs deleted file mode 100644 index 6dfb652d0..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingColor.cs +++ /dev/null @@ -1,309 +0,0 @@ -// 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 -{ - /// - /// A highlighting color is a set of font properties and foreground and background color. - /// - [Serializable] - public class HighlightingColor : ISerializable, IFreezable, ICloneable, IEquatable - { - internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor()); - - string name; - FontWeight? fontWeight; - FontStyle? fontStyle; - bool? underline; - HighlightingBrush foreground; - HighlightingBrush background; - bool frozen; - - /// - /// Gets/Sets the name of the color. - /// - public string Name { - get { - return name; - } - set { - if (frozen) - throw new InvalidOperationException(); - name = value; - } - } - - /// - /// Gets/sets the font weight. Null if the highlighting color does not change the font weight. - /// - public FontWeight? FontWeight { - get { - return fontWeight; - } - set { - if (frozen) - throw new InvalidOperationException(); - fontWeight = value; - } - } - - /// - /// Gets/sets the font style. Null if the highlighting color does not change the font style. - /// - public FontStyle? FontStyle { - get { - return fontStyle; - } - set { - if (frozen) - throw new InvalidOperationException(); - fontStyle = value; - } - } - - /// - /// Gets/sets the underline flag. Null if the underline status does not change the font style. - /// - public bool? Underline { - get { - return underline; - } - set { - if (frozen) - throw new InvalidOperationException(); - underline = value; - } - } - - /// - /// Gets/sets the foreground color applied by the highlighting. - /// - public HighlightingBrush Foreground { - get { - return foreground; - } - set { - if (frozen) - throw new InvalidOperationException(); - foreground = value; - } - } - - /// - /// Gets/sets the background color applied by the highlighting. - /// - public HighlightingBrush Background { - get { - return background; - } - set { - if (frozen) - throw new InvalidOperationException(); - background = value; - } - } - - /// - /// Creates a new HighlightingColor instance. - /// - public HighlightingColor() - { - } - - /// - /// Deserializes a HighlightingColor. - /// - 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")); - if (info.GetBoolean("HasUnderline")) - this.Underline = info.GetBoolean("Underline"); - this.Foreground = (HighlightingBrush)info.GetValue("Foreground", typeof(HighlightingBrush)); - this.Background = (HighlightingBrush)info.GetValue("Background", typeof(HighlightingBrush)); - } - - /// - /// Serializes this HighlightingColor instance. - /// - #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("HasUnderline", this.Underline.HasValue); - if (this.Underline.HasValue) - info.AddValue("Underline", this.Underline.Value); - info.AddValue("Foreground", this.Foreground); - info.AddValue("Background", this.Background); - } - - /// - /// Gets CSS code for the color. - /// - [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("; "); - } - if (Underline != null) - { - b.Append("text-decoration: "); - b.Append(Underline.Value ? "underline" : "none"); - b.Append("; "); - } - return b.ToString(); - } - - /// - public override string ToString() - { - return "[" + GetType().Name + " " + (string.IsNullOrEmpty(this.Name) ? ToCss() : this.Name) + "]"; - } - - /// - /// Prevent further changes to this highlighting color. - /// - public virtual void Freeze() - { - frozen = true; - } - - /// - /// Gets whether this HighlightingColor instance is frozen. - /// - public bool IsFrozen { - get { return frozen; } - } - - /// - /// Clones this highlighting color. - /// If this color is frozen, the clone will be unfrozen. - /// - public virtual HighlightingColor Clone() - { - HighlightingColor c = (HighlightingColor)MemberwiseClone(); - c.frozen = false; - return c; - } - - object ICloneable.Clone() - { - return Clone(); - } - - /// - public override sealed bool Equals(object obj) - { - return Equals(obj as HighlightingColor); - } - - /// - public virtual bool Equals(HighlightingColor other) - { - if (other == null) - return false; - return this.name == other.name && this.fontWeight == other.fontWeight - && this.fontStyle == other.fontStyle && this.underline == other.underline - && object.Equals(this.foreground, other.foreground) && object.Equals(this.background, other.background); - } - - /// - 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; - } - - /// - /// 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 null. - /// - 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; - if (color.underline != null) - this.underline = color.underline; - } - - internal bool IsEmptyForMerge { - get { - return fontWeight == null && fontStyle == null && underline == null - && foreground == null && background == null; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingColorizer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingColorizer.cs deleted file mode 100644 index 4eec5242b..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingColorizer.cs +++ /dev/null @@ -1,363 +0,0 @@ -// 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; -using ICSharpCode.AvalonEdit.Document; -using ICSharpCode.AvalonEdit.Rendering; - -namespace ICSharpCode.AvalonEdit.Highlighting -{ - /// - /// A colorizes that interprets a highlighting rule set and colors the document accordingly. - /// - public class HighlightingColorizer : DocumentColorizingTransformer - { - readonly IHighlightingDefinition definition; - TextView textView; - IHighlighter highlighter; - bool isFixedHighlighter; - - /// - /// Creates a new HighlightingColorizer instance. - /// - /// The highlighting definition. - public HighlightingColorizer(IHighlightingDefinition definition) - { - if (definition == null) - throw new ArgumentNullException("definition"); - this.definition = definition; - } - - /// - /// 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. - /// - /// The highlighter to be used. - public HighlightingColorizer(IHighlighter highlighter) - { - if (highlighter == null) - throw new ArgumentNullException("highlighter"); - this.highlighter = highlighter; - this.isFixedHighlighter = true; - } - - /// - /// Creates a new HighlightingColorizer instance. - /// Derived classes using this constructor must override the method. - /// - protected HighlightingColorizer() - { - } - - void textView_DocumentChanged(object sender, EventArgs e) - { - TextView textView = (TextView)sender; - DeregisterServices(textView); - RegisterServices(textView); - } - - /// - /// This method is called when a text view is removed from this HighlightingColorizer, - /// and also when the TextDocument on any associated text view changes. - /// - 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; - } - } - } - - /// - /// 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. - /// - 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; - } - } - } - - /// - /// Creates the IHighlighter instance for the specified text document. - /// - 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."); - } - - /// - 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); - } - - /// - 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; - - /// - 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; - - /// - 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; - } - - /// - /// Gets whether the color is empty (has no effect on a VisualLineTextElement). - /// For example, the C# "Punctuation" is an empty color. - /// - internal static bool IsEmptyColor(HighlightingColor color) - { - if (color == null) - return true; - return color.Background == null && color.Foreground == null - && color.FontStyle == null && color.FontWeight == null - && color.Underline == null; - } - - /// - /// Applies a highlighting color to a visual line element. - /// - 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 - )); - } - if(color.Underline ?? false) - element.TextRunProperties.SetTextDecorations(TextDecorations.Underline); - } - - /// - /// This method is responsible for telling the TextView to redraw lines when the highlighting state has changed. - /// - /// - /// 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! - /// - 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. - */ - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingDefinitionInvalidException.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingDefinitionInvalidException.cs deleted file mode 100644 index 3fb362fba..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingDefinitionInvalidException.cs +++ /dev/null @@ -1,58 +0,0 @@ -// 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 -{ - /// - /// Indicates that the highlighting definition that was tried to load was invalid. - /// - [Serializable()] - public class HighlightingDefinitionInvalidException : Exception - { - /// - /// Creates a new HighlightingDefinitionInvalidException instance. - /// - public HighlightingDefinitionInvalidException() : base() - { - } - - /// - /// Creates a new HighlightingDefinitionInvalidException instance. - /// - public HighlightingDefinitionInvalidException(string message) : base(message) - { - } - - /// - /// Creates a new HighlightingDefinitionInvalidException instance. - /// - public HighlightingDefinitionInvalidException(string message, Exception innerException) : base(message, innerException) - { - } - - /// - /// Creates a new HighlightingDefinitionInvalidException instance. - /// - protected HighlightingDefinitionInvalidException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingDefinitionTypeConverter.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingDefinitionTypeConverter.cs deleted file mode 100644 index faa900d29..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingDefinitionTypeConverter.cs +++ /dev/null @@ -1,69 +0,0 @@ -// 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 -{ - /// - /// Converts between strings and by treating the string as the definition name - /// and calling HighlightingManager.Instance.GetDefinition(name). - /// - public sealed class HighlightingDefinitionTypeConverter : TypeConverter - { - /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - if (sourceType == typeof(string)) - return true; - else - return base.CanConvertFrom(context, sourceType); - } - - /// - 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); - } - - /// - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - if (destinationType == typeof(string)) - return true; - else - return base.CanConvertTo(context, destinationType); - } - - /// - 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingEngine.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingEngine.cs deleted file mode 100644 index e08753130..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingEngine.cs +++ /dev/null @@ -1,325 +0,0 @@ -// 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; - -namespace ICSharpCode.AvalonEdit.Highlighting -{ - /// - /// Regex-based highlighting engine. - /// - public class HighlightingEngine - { - readonly HighlightingRuleSet mainRuleSet; - SpanStack spanStack = SpanStack.Empty; - - /// - /// Creates a new HighlightingEngine instance. - /// - public HighlightingEngine(HighlightingRuleSet mainRuleSet) - { - if (mainRuleSet == null) - throw new ArgumentNullException("mainRuleSet"); - this.mainRuleSet = mainRuleSet; - } - - /// - /// Gets/sets the current span stack. - /// - 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; - - /// - /// the HighlightedLine where highlighting output is being written to. - /// if this variable is null, nothing is highlighted and only the span state is updated - /// - HighlightedLine highlightedLine; - - /// - /// Highlights the specified line in the specified document. - /// - /// Before calling this method, must be set to the proper - /// state for the beginning of this line. After highlighting has completed, - /// will be updated to represent the state after the line. - /// - 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; - } - } - - /// - /// Updates for the specified line in the specified document. - /// - /// Before calling this method, must be set to the proper - /// state for the beginning of this line. After highlighting has completed, - /// will be updated to represent the state after the line. - /// - 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 storedMatchArrays = new Stack(); - 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 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 highlightedSectionStack; - HighlightedSection lastPoppedSection; - - void ResetColorStack() - { - Debug.Assert(position == 0); - lastPoppedSection = null; - if (highlightedLine == null) { - highlightedSectionStack = null; - } else { - highlightedSectionStack = new Stack(); - 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 - /// - /// Returns the first match from the array or endSpanMatch. - /// - 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.Array; - else - return new Match[count]; - } - #endregion - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingManager.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingManager.cs deleted file mode 100644 index c9ea32f07..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingManager.cs +++ /dev/null @@ -1,289 +0,0 @@ -// 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 -{ - /// - /// Manages a list of syntax highlighting definitions. - /// - /// - /// All memers on this class (including instance members) are thread-safe. - /// - public class HighlightingManager : IHighlightingDefinitionReferenceResolver - { - sealed class DelayLoadedHighlightingDefinition : IHighlightingDefinition - { - readonly object lockObj = new object(); - readonly string name; - Func lazyLoadingFunction; - IHighlightingDefinition definition; - Exception storedException; - - public DelayLoadedHighlightingDefinition(string name, Func 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 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 NamedHighlightingColors { - get { - return GetDefinition().NamedHighlightingColors; - } - } - - public override string ToString() - { - return this.Name; - } - - public IDictionary Properties { - get { - return GetDefinition().Properties; - } - } - } - - readonly object lockObj = new object(); - Dictionary highlightingsByName = new Dictionary(); - Dictionary highlightingsByExtension = new Dictionary(StringComparer.OrdinalIgnoreCase); - List allHighlightings = new List(); - - /// - /// Gets a highlighting definition by name. - /// Returns null if the definition is not found. - /// - public IHighlightingDefinition GetDefinition(string name) - { - lock (lockObj) { - IHighlightingDefinition rh; - if (highlightingsByName.TryGetValue(name, out rh)) - return rh; - else - return null; - } - } - - /// - /// Gets a copy of all highlightings. - /// - public ReadOnlyCollection HighlightingDefinitions { - get { - lock (lockObj) { - return Array.AsReadOnly(allHighlightings.ToArray()); - } - } - } - - /// - /// Gets a highlighting definition by extension. - /// Returns null if the definition is not found. - /// - public IHighlightingDefinition GetDefinitionByExtension(string extension) - { - lock (lockObj) { - IHighlightingDefinition rh; - if (highlightingsByExtension.TryGetValue(extension, out rh)) - return rh; - else - return null; - } - } - - /// - /// Registers a highlighting definition. - /// - /// The name to register the definition with. - /// The file extensions to register the definition for. - /// The highlighting definition. - 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; - } - } - } - } - - /// - /// Registers a highlighting definition. - /// - /// The name to register the definition with. - /// The file extensions to register the definition for. - /// A function that loads the highlighting definition. - public void RegisterHighlighting(string name, string[] extensions, Func lazyLoadedHighlighting) - { - if (lazyLoadedHighlighting == null) - throw new ArgumentNullException("lazyLoadedHighlighting"); - RegisterHighlighting(name, extensions, new DelayLoadedHighlightingDefinition(name, lazyLoadedHighlighting)); - } - - /// - /// Gets the default HighlightingManager instance. - /// The default HighlightingManager comes with built-in highlightings. - /// - 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 LoadHighlighting(string resourceName) - { - Func 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; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingRule.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingRule.cs deleted file mode 100644 index 20c03e4c0..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingRule.cs +++ /dev/null @@ -1,46 +0,0 @@ -// 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 -{ - /// - /// A highlighting rule. - /// - [Serializable] - public class HighlightingRule - { - /// - /// Gets/Sets the regular expression for the rule. - /// - public Regex Regex { get; set; } - - /// - /// Gets/Sets the highlighting color. - /// - public HighlightingColor Color { get; set; } - - /// - public override string ToString() - { - return "[" + GetType().Name + " " + Regex + "]"; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingRuleSet.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingRuleSet.cs deleted file mode 100644 index b3d7800bb..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingRuleSet.cs +++ /dev/null @@ -1,61 +0,0 @@ -// 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 -{ - /// - /// A highlighting rule set describes a set of spans that are valid at a given code location. - /// - [Serializable] - public class HighlightingRuleSet - { - /// - /// Creates a new RuleSet instance. - /// - public HighlightingRuleSet() - { - this.Spans = new NullSafeCollection(); - this.Rules = new NullSafeCollection(); - } - - /// - /// Gets/Sets the name of the rule set. - /// - public string Name { get; set; } - - /// - /// Gets the list of spans. - /// - public IList Spans { get; private set; } - - /// - /// Gets the list of rules. - /// - public IList Rules { get; private set; } - - /// - public override string ToString() - { - return "[" + GetType().Name + " " + Name + "]"; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingSpan.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingSpan.cs deleted file mode 100644 index a77d428e0..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingSpan.cs +++ /dev/null @@ -1,79 +0,0 @@ -// 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 -{ - /// - /// A highlighting span is a region with start+end expression that has a different RuleSet inside - /// and colors the region. - /// - [Serializable] - public class HighlightingSpan - { - /// - /// Gets/Sets the start expression. - /// - public Regex StartExpression { get; set; } - - /// - /// Gets/Sets the end expression. - /// - public Regex EndExpression { get; set; } - - /// - /// Gets/Sets the rule set that applies inside this span. - /// - public HighlightingRuleSet RuleSet { get; set; } - - /// - /// Gets the color used for the text matching the start expression. - /// - public HighlightingColor StartColor { get; set; } - - /// - /// Gets the color used for the text between start and end. - /// - public HighlightingColor SpanColor { get; set; } - - /// - /// Gets the color used for the text matching the end expression. - /// - public HighlightingColor EndColor { get; set; } - - /// - /// Gets/Sets whether the span color includes the start. - /// The default is false. - /// - public bool SpanColorIncludesStart { get; set; } - - /// - /// Gets/Sets whether the span color includes the end. - /// The default is false. - /// - public bool SpanColorIncludesEnd { get; set; } - - /// - public override string ToString() - { - return "[" + GetType().Name + " Start=" + StartExpression + ", End=" + EndExpression + "]"; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HtmlClipboard.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HtmlClipboard.cs deleted file mode 100644 index eb0afc0c2..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HtmlClipboard.cs +++ /dev/null @@ -1,112 +0,0 @@ -// 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 -{ - /// - /// Allows copying HTML text to the clipboard. - /// - public static class HtmlClipboard - { - /// - /// Builds a header for the CF_HTML clipboard format. - /// - 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(); - } - - /// - /// 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. - /// - public static void SetHtml(DataObject dataObject, string htmlFragment) - { - if (dataObject == null) - throw new ArgumentNullException("dataObject"); - if (htmlFragment == null) - throw new ArgumentNullException("htmlFragment"); - - string htmlStart = @"" + Environment.NewLine - + "" + Environment.NewLine - + "" + Environment.NewLine - + "" + Environment.NewLine; - string htmlEnd = "" + Environment.NewLine + "" + Environment.NewLine + "" + 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); - } - - /// - /// Creates a HTML fragment from a part of a document. - /// - /// The document to create HTML from. - /// The highlighter used to highlight the document. null is valid and will create HTML without any highlighting. - /// The part of the document to create HTML for. You can pass null to create HTML for the whole document. - /// The options for the HTML creation. - /// HTML code for the document part. - 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("
"); - html.Append(highlightedLine.ToHtml(s.Offset, s.EndOffset, options)); - line = line.NextLine; - } - return html.ToString(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HtmlOptions.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HtmlOptions.cs deleted file mode 100644 index 13c76c241..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HtmlOptions.cs +++ /dev/null @@ -1,85 +0,0 @@ -// 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 -{ - /// - /// Holds options for converting text to HTML. - /// - public class HtmlOptions - { - /// - /// Creates a default HtmlOptions instance. - /// - public HtmlOptions() - { - this.TabSize = 4; - } - - /// - /// Creates a new HtmlOptions instance that copies applicable options from the . - /// - public HtmlOptions(TextEditorOptions options) : this() - { - if (options == null) - throw new ArgumentNullException("options"); - this.TabSize = options.IndentationSize; - } - - /// - /// The amount of spaces a tab gets converted to. - /// - public int TabSize { get; set; } - - /// - /// Writes the HTML attribute for the style to the text writer. - /// - 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('"'); - } - - /// - /// Gets whether the color needs to be written out to HTML. - /// - public virtual bool ColorNeedsSpanForStyling(HighlightingColor color) - { - if (color == null) - throw new ArgumentNullException("color"); - return !string.IsNullOrEmpty(color.ToCss()); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HtmlRichTextWriter.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HtmlRichTextWriter.cs deleted file mode 100644 index b29d452a3..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HtmlRichTextWriter.cs +++ /dev/null @@ -1,268 +0,0 @@ -// 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 -{ - /// - /// RichTextWriter implementation that produces HTML. - /// - class HtmlRichTextWriter : RichTextWriter - { - readonly TextWriter htmlWriter; - readonly HtmlOptions options; - Stack endTagStack = new Stack(); - bool spaceNeedsEscaping = true; - bool hasSpace; - bool needIndentation = true; - int indentationLevel; - - /// - /// Creates a new HtmlRichTextWriter instance. - /// - /// - /// 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! - /// - /// Options that control the HTML output. - public HtmlRichTextWriter(TextWriter htmlWriter, HtmlOptions options = null) - { - if (htmlWriter == null) - throw new ArgumentNullException("htmlWriter"); - this.htmlWriter = htmlWriter; - this.options = options ?? new HtmlOptions(); - } - - /// - public override Encoding Encoding { - get { return htmlWriter.Encoding; } - } - - /// - public override void Flush() - { - FlushSpace(true); // next char potentially might be whitespace - htmlWriter.Flush(); - } - - /// - protected override void Dispose(bool disposing) - { - if (disposing) { - FlushSpace(true); - } - base.Dispose(disposing); - } - - void FlushSpace(bool nextIsWhitespace) - { - if (hasSpace) { - if (spaceNeedsEscaping || nextIsWhitespace) - htmlWriter.Write(" "); - else - htmlWriter.Write(' '); - hasSpace = false; - spaceNeedsEscaping = true; - } - } - - void WriteIndentation() - { - if (needIndentation) { - for (int i = 0; i < indentationLevel; i++) { - WriteChar('\t'); - } - needIndentation = false; - } - } - - /// - 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(" "); - else - hasSpace = true; - break; - case '\t': - for (int i = 0; i < options.TabSize; i++) { - htmlWriter.Write(" "); - } - break; - case '\r': - break; // ignore; we'll write the
with the following \n - case '\n': - htmlWriter.Write("
"); - 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; - } - } - - /// - 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 - } - - /// - public override void Indent() - { - indentationLevel++; - } - - /// - public override void Unindent() - { - if (indentationLevel == 0) - throw new NotSupportedException(); - indentationLevel--; - } - - /// - protected override void BeginUnhandledSpan() - { - endTagStack.Push(null); - } - - /// - public override void EndSpan() - { - htmlWriter.Write(endTagStack.Pop()); - } - - /// - public override void BeginSpan(Color foregroundColor) - { - BeginSpan(new HighlightingColor { Foreground = new SimpleHighlightingBrush(foregroundColor) }); - } - - /// - public override void BeginSpan(FontFamily fontFamily) - { - BeginUnhandledSpan(); // TODO - } - - /// - public override void BeginSpan(FontStyle fontStyle) - { - BeginSpan(new HighlightingColor { FontStyle = fontStyle }); - } - - /// - public override void BeginSpan(FontWeight fontWeight) - { - BeginSpan(new HighlightingColor { FontWeight = fontWeight }); - } - - /// - public override void BeginSpan(HighlightingColor highlightingColor) - { - WriteIndentationAndSpace(); - if (options.ColorNeedsSpanForStyling(highlightingColor)) { - htmlWriter.Write("'); - endTagStack.Push(""); - } else { - endTagStack.Push(null); - } - } - - /// - 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(""); - endTagStack.Push(""); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/IHighlighter.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/IHighlighter.cs deleted file mode 100644 index 66702adf9..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/IHighlighter.cs +++ /dev/null @@ -1,126 +0,0 @@ -// 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 -{ - /// - /// Represents a highlighted document. - /// - /// This interface is used by the to register the highlighter as a TextView service. - public interface IHighlighter : IDisposable - { - /// - /// Gets the underlying text document. - /// - IDocument Document { get; } - - /// - /// 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. - /// - /// - /// 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). - /// - IEnumerable 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). - - /// - /// Highlights the specified document line. - /// - /// The line to highlight. - /// A line object that represents the highlighted sections. - HighlightedLine HighlightLine(int lineNumber); - - /// - /// Enforces a highlighting state update (triggering the HighlightingStateChanged event if necessary) - /// for all lines up to (and inclusive) the specified line number. - /// - void UpdateHighlightingState(int lineNumber); - - /// - /// Notification when the highlighter detects that the highlighting state at the - /// beginning of the specified lines has changed. - /// fromLineNumber and toLineNumber are both inclusive; - /// the common case of a single-line change is represented by fromLineNumber == toLineNumber. - /// - /// 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. - /// - /// - /// 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. - /// - event HighlightingStateChangedEventHandler HighlightingStateChanged; - - /// - /// Opens a group of calls. - /// It is not necessary to call this method before calling , - /// 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). - /// - /// - /// The group is closed by either a or a call. - /// Nested groups are not allowed. - /// - void BeginHighlighting(); - - /// - /// Closes the currently opened group of calls. - /// - /// . - void EndHighlighting(); - - /// - /// Retrieves the HighlightingColor with the specified name. Returns null if no color matching the name is found. - /// - HighlightingColor GetNamedColor(string name); - - /// - /// Gets the default text color. - /// - HighlightingColor DefaultTextColor { get; } - } - - /// - /// Event handler for - /// - public delegate void HighlightingStateChangedEventHandler(int fromLineNumber, int toLineNumber); -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/IHighlightingDefinition.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/IHighlightingDefinition.cs deleted file mode 100644 index 02dc730e4..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/IHighlightingDefinition.cs +++ /dev/null @@ -1,63 +0,0 @@ -// 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 -{ - /// - /// A highlighting definition. - /// - [TypeConverter(typeof(HighlightingDefinitionTypeConverter))] - public interface IHighlightingDefinition - { - /// - /// Gets the name of the highlighting definition. - /// - string Name { get; } - - /// - /// Gets the main rule set. - /// - HighlightingRuleSet MainRuleSet { get; } - - /// - /// Gets a rule set by name. - /// - /// The rule set, or null if it is not found. - HighlightingRuleSet GetNamedRuleSet(string name); - - /// - /// Gets a named highlighting color. - /// - /// The highlighting color, or null if it is not found. - HighlightingColor GetNamedColor(string name); - - /// - /// Gets the list of named highlighting colors. - /// - IEnumerable NamedHighlightingColors { get; } - - /// - /// Gets the list of properties. - /// - IDictionary Properties { get; } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/IHighlightingDefinitionReferenceResolver.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/IHighlightingDefinitionReferenceResolver.cs deleted file mode 100644 index fb1887e3d..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/IHighlightingDefinitionReferenceResolver.cs +++ /dev/null @@ -1,33 +0,0 @@ -// 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 -{ - /// - /// Interface for resolvers that can solve cross-definition references. - /// - public interface IHighlightingDefinitionReferenceResolver - { - /// - /// Gets the highlighting definition by name, or null if it is not found. - /// - IHighlightingDefinition GetDefinition(string name); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/ASPX.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/ASPX.xshd deleted file mode 100644 index bd0c922ac..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/ASPX.xshd +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - <% - %> - - - - - - - diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Boo.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Boo.xshd deleted file mode 100644 index a4e555198..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Boo.xshd +++ /dev/null @@ -1,212 +0,0 @@ - - - - - - - """ - """ - - - \# - - - // - - - /\* - \*/ - - - " - " - - - - - \$\{ - } - - - - - ' - ' - - - - - - @/ - / - - - - /\S+/ - - - - self - super - - - is - isa - and - or - not - - - else - elif - if - match - case - unless - otherwise - for - in - while - - - break - continue - return - yield - goto - - - try - raise - ensure - except - retry - success - - - fixed - unsafe - - - bool - double - single - byte - sbyte - short - ushort - int - uint - long - ulong - date - timespan - decimal - char - object - duck - string - regex - - - void - - - cast - as - - - override - static - virtual - abstract - final - transient - partial - - - public - protected - private - internal - - - namespace - import - from - - - get - set - - - null - value - true - false - ast - - - using - unchecked - checked - lock - getter - required - rawArrayIndexing - normalArrayIndexing - yieldAll - - - assert - array - matrix - print - gets - prompt - enumerate - zip - filter - map - cat - __eval__ - __switch__ - - - constructor - destructor - def - include - event - ref - - - pass - - - enum - class - struct - interface - mixin - callable - do - of - - [\d\w_]+(?=(\s*\()) - \b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)? - - - - - /\* - \*/ - - - /\* - \*/ - - - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/CPP-Mode.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/CPP-Mode.xshd deleted file mode 100644 index f552ad413..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/CPP-Mode.xshd +++ /dev/null @@ -1,195 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - [?,.;()\[\]{}+\-/%*<>^=~!&]+ - - - __abstract - __box - __delegate - __gc - __identifier - __nogc - __pin - __property - __sealed - __try_cast - __typeof - __value - __event - __hook - __raise - __unhook - __interface - ref class - ref struct - value class - value struct - interface class - interface struct - enum class - enum struct - delegate - event - property - abstract - override - sealed - generic - where - finally - for each - gcnew - in - initonly - literal - nullptr - - - this - - - and - and_eq - bitand - bitor - new - not - not_eq - or - or_eq - xor - xor_eq - - - using - namespace - - - friend - - - private - protected - public - const - volatile - static - - - bool - char - unsigned - union - virtual - double - float - short - signed - void - class - enum - struct - - - false - true - - - do - for - while - - - break - continue - goto - return - - - catch - throw - try - - - case - else - if - switch - default - - - asm - auto - compl - mutable - const_cast - delete - dynamic_cast - explicit - export - extern - inline - int - long - operator - register - reinterpret_cast - sizeof - static_cast - template - typedef - typeid - typename - - - \# - - - // - - - /\* - \*/ - - - " - " - - - - - - ' - ' - - - - - [\d\w_]+(?=(\s*\()) - \b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)? - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/CSS-Mode.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/CSS-Mode.xshd deleted file mode 100644 index 198f6e124..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/CSS-Mode.xshd +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - /\* - \*/ - - - \{ - \} - - - \# - \s - - [\d\w] - - - - - /\* - \*/ - - - \: - \;|(?=\}) - - - " - " - - - - - - ' - ' - - - - - - - - - diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/CSharp-Mode.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/CSharp-Mode.xshd deleted file mode 100644 index 08e676896..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/CSharp-Mode.xshd +++ /dev/null @@ -1,292 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TODO - FIXME - - - HACK - UNDONE - - - - - - - \# - - - - (define|undef|if|elif|else|endif|line)\b - - - - // - - - - - - (region|endregion|error|warning|pragma)\b - - - - - - - ///(?!/) - - - - - - - - // - - - - /\* - \*/ - - - - " - " - - - - - - - - ' - ' - - - - - - - - @" - " - - - - - - - - - @[\w\d_]+ - - - - this - base - - - - as - is - new - sizeof - typeof - stackalloc - - - - true - false - - - - else - if - switch - case - default - do - for - foreach - in - while - lock - - - - break - continue - goto - return - - - - yield - partial - global - where - select - group - by - into - from - ascending - descending - orderby - let - join - on - equals - var - dynamic - await - - - - try - throw - catch - finally - - - - checked - unchecked - - - - fixed - unsafe - - - - bool - byte - char - decimal - double - enum - float - int - long - sbyte - short - struct - uint - ushort - ulong - - - - class - interface - delegate - object - string - void - - - - explicit - implicit - operator - - - - params - ref - out - - - - abstract - const - event - extern - override - readonly - sealed - static - virtual - volatile - async - - - - public - protected - private - internal - - - - namespace - using - - - - get - set - add - remove - - - - null - value - - - - - \b - [\d\w_]+ # an identifier - (?=\s*\() # followed by ( - - - - - \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 - - - - [?,.;()\[\]{}+\-/%*<>^+~!|&]+ - - - diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Coco-Mode.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Coco-Mode.xshd deleted file mode 100644 index 9395198b5..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Coco-Mode.xshd +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - - - - - - [{}\(\)\[\]|+\-=\.]+ - - - ANY - CHARACTERS - COMMENTS - COMPILER - CONTEXT - END - FROM - IF - IGNORE - NAMESPACE - NESTED - PRAGMAS - PRODUCTIONS - SYNC - TO - TOKENS - TOKENNAMES - WEAK - using - - - // - - - /\* - \*/ - - - COMPILER - TOKENNAMES - - - " - " - - - ' - ' - - - < - > - - - \(\. - \.\) - - \b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)? - - - - \b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)? - - - - \b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)? - - - \b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)? - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/HTML-Mode.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/HTML-Mode.xshd deleted file mode 100644 index 3be3b5620..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/HTML-Mode.xshd +++ /dev/null @@ -1,388 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - <!-- - --> - - - <script\ lang="JavaScript"> - </script> - - - <script\s.*?text/javascript.*?> - </script> - - - <script\ lang="JScript"> - </script> - - - <script\ lang="VBScript"> - </script> - - - <script> - </script> - - - <script[^\w\d_] - </script> - - - < - > - - - & - ; - - \b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)? - - - - \b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)? - - - - aacute - agrave - acirc - amp - atilde - aring - auml - aelig - ccedil - copy - eacute - egrave - ecirc - euml - iacute - igrave - icirc - iuml - eth - gt - lt - nbsp - ntilde - oacute - ograve - ocirc - otilde - ouml - oslash - quot - reg - szlig - uacute - ugrave - ucirc - uuml - yacute - thorn - trade - yuml - - \b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)? - - - - / - - - = - - - !DOCTYPE - A - ABBR - ACRONYM - ADDRESS - APPLET - AREA - B - BASE - BASEFONT - BGSOUND - BDO - BIG - BLINK - BLOCKQUOTE - BODY - BR - BUTTON - CAPTION - CENTER - CITE - CODE - COL - COLGROUP - COMMENT - DD - DEL - DFN - DIR - DIV - DL - DT - EM - EMBED - FIELDSET - FONT - FORM - FRAME - FRAMESET - H - H1 - H2 - H3 - H4 - H5 - H6 - HEAD - HR - HTA:APPLICATION - HTML - I - IFRAME - IMG - INPUT - INS - ISINDEX - KBD - LABEL - LEGEnd - LI - LINK - LISTING - MAP - MARQUEE - MENU - META - MULTICOL - NEXTID - NOBR - NOFRAMES - NOSCRIPT - OBJECT - OL - OPTGROUP - OPTION - P - PARAM - PLAINTEXT - PRE - Q - S - SAMP - SCRIPT - SELECT - SERVER - SMALL - SOUND - SPACER - Span - STRONG - STYLE - SUB - SUP - TABLE - TBODY - TD - TEXTAREA - TEXTFLOW - TFOOT - TH - THEAD - TITLE - TR - TT - U - VAR - WBR - XMP - - - abbr - accept-charset - accept - accesskey - action - align - alink - alt - applicationname - archive - axis - background - behavior - bgcolor - bgproperties - border - bordercolor - bordercolordark - bordercolorligh - borderstyle - caption - cellpadding - cellspacing - char - charoff - charset - checked - cite - class - classid - clear - code - codetype - color - cols - colspan - compact - content - coords - data - datetime - declare - defer - dir - direction - disabled - dynsrc - enctype - face - for - frame - frameborder - framespacing - gutter - headers - height - href - hreflang - hspace - http-equiv - icon - id - ismap - label - language - leftmargin - link - longdesc - loop - lowsrc - marginheight - marginwidth - maximizebutton - maxlength - media - method - methods - minimizebutton - multiple - name - nohref - noresize - noshade - nowrap - object - onabort - onblur - onchange - onclick - ondblclick - onerror - onfocus - onkeydown - onkeypress - onkeyup - onload - onmousedown - onmousemove - onmouseout - onmouseover - onmouseup - onreset - onselect - onsubmit - onunload - profile - prompt - readonly - rel - rev - rows - rowspan - rules - runat - scheme - scope - scrollamount - scrolldelay - scrolling - selected - shape - showintaskbar - singleinstance - size - span - src - standby - start - style - summary - sysmenu - tabindex - target - text - title - topmargin - type - urn - usemap - valign - value - valuetype - version - vlink - vrml - vspace - width - windowstate - wrap - - - " - " - - - ' - ' - - [\d\w_]+(?=(\s*=)) - \b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)? - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Java-Mode.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Java-Mode.xshd deleted file mode 100644 index dd5053e91..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Java-Mode.xshd +++ /dev/null @@ -1,152 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - [?,.()\[\]{}+\-/%*<>^!|]+ - - - this - super - - - new - instanceof - true - false - - - else - if - switch - case - - - do - for - while - - - break - continue - default - goto - return - - - try - throw - catch - finally - - - boolean - double - int - short - long - float - byte - char - - - class - interface - object - - - void - - - abstract - const - static - final - native - extends - implements - volatile - transient - throws - strictfp - synchronized - - - public - protected - private - - - package - import - - - null - - - // - - - /\* - \*/ - - - " - " - - - - - - ' - ' - - - - - [\d\w_]+(?=(\s*\()) - \b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)? - - - - TODO - - - @author - @version - @param - @return - @exception - @throws - @see - @since - @serial - @serialField - @serialData - @deprecated - - \b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)? - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/JavaScript-Mode.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/JavaScript-Mode.xshd deleted file mode 100644 index f30543c97..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/JavaScript-Mode.xshd +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - - - - - - - - - - - break - continue - delete - else - for - function - if - in - new - return - this - typeof - var - void - while - with - abstract - boolean - byte - case - catch - char - class - const - debugger - default - do - double - enum - export - extends - final - finally - float - goto - implements - import - instanceof - int - interface - long - native - package - private - protected - public - short - static - super - switch - synchronized - throw - throws - transient - try - volatile - - - Array - Boolean - Date - Function - Global - Math - Number - Object - RegExp - String - - - false - null - true - NaN - Infinity - - - eval - parseInt - parseFloat - escape - unescape - isNaN - isFinite - - - // - - - /\* - \*/ - - - - / - / - - - - - - " - " - - - - - - ' - ' - - - - - \b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)? - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/MarkDown-Mode.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/MarkDown-Mode.xshd deleted file mode 100644 index ead5045ab..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/MarkDown-Mode.xshd +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - - - ^\#.* - - - \*\*.*\*\* - - - __.*__ - - - \*(?![ ]).*\* - - - _.*_ - - - `.*` - - - ^\t - ^(?!\t) - - - ^[ ]{4} - ^(?![ ]{4}) - - - ^> - ^(?!>) - - - \!\[.*\]\[.*\] - - - \[.*\]\(.*\) - - - \[.*\]\[.*\] - - - [ ]{2}$ - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/ModeV1.xsd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/ModeV1.xsd deleted file mode 100644 index 82bce451d..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/ModeV1.xsd +++ /dev/null @@ -1,296 +0,0 @@ - - - - - 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. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/ModeV2.xsd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/ModeV2.xsd deleted file mode 100644 index c2e242ac2..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/ModeV2.xsd +++ /dev/null @@ -1,168 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/PHP-Mode.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/PHP-Mode.xshd deleted file mode 100644 index f09ff27d9..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/PHP-Mode.xshd +++ /dev/null @@ -1,158 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \# - - - - // - - - - /\* - \*/ - - - - - \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 - - - - [?,.:;()\[\]{}+\-/%*<>&^!|~@]+ - - - - - \b - [\d\w_]+ # an identifier - (?=\s*\() # followed by ( - - - - ' - ' - - - - - - - - " - " - - - - - - - - - <<<\"?[\d\w_]+\"?$ - ^[\d\w_]+; - - - - - <<<\'[\d\w_]+\'$ - ^[\d\w_]+; - - - - global - my - var - - - - and - or - new - clone - instanceof - xor - true - false - - - - else - else - switch - case - endif - elseif - - - - do - for - foreach - while - endwhile - exit - - - - break - continue - default - goto - return - - - - require - include - require - include - function - - - - int - integer - real - double - float - string - array - object - - - - class - void - - - - public - private - - - diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Patch-Mode.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Patch-Mode.xshd deleted file mode 100644 index c8e1c3cfd..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Patch-Mode.xshd +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - Index:\s - - - == - - - --- - - - \+\+\+ - - - @@ - - - - - - - \+ - - - \s - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/PowerShell.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/PowerShell.xshd deleted file mode 100644 index ee6fec4c8..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/PowerShell.xshd +++ /dev/null @@ -1,146 +0,0 @@ - - - - - - - - - - - - - - - - - - \# - - - - <\# - \#> - - - - " - " - - - - - - - - ' - ' - - - - - - - - @" - "@ - - - - - - - - while - param - end - define - else - from - foreach - var - dynamicparam - filter - dp - until - for - exit - switch - process - begin - elseif - if - in - data - class - using - function - - - - catch - finally - throw - trap - try - - - - break - continue - return - - - - class - - - - -not - -band - -bor - -replace - -ireplace - -creplace - -and - -or - -is - -isnot - -as - -lt - -le - -gt - -ge - -eq - -ne - -contains - -notcontains - -like - -notlike - -match - -notmatch - - - - \$[\d\w_]+ - - - - [\w]+-[\w]+ - - - - - \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 - - - - [?,.;()\[\]{}+\-/%*<>^+~!|&]+ - - - diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Resources.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Resources.cs deleted file mode 100644 index cb74ab885..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Resources.cs +++ /dev/null @@ -1,63 +0,0 @@ -// 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"); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Tex-Mode.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Tex-Mode.xshd deleted file mode 100644 index 91083b0ab..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Tex-Mode.xshd +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - - &~!@%^*()-+=|\#/{}[]:;"'<> , .? - - - % - - - - $$ - $$ - - - \[ - \] - - - - \ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - &~!@%^*()-+=|\#/{}[]:;"'<> , .? - - - - % - - - - \ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/VB-Mode.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/VB-Mode.xshd deleted file mode 100644 index 05e38374f..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/VB-Mode.xshd +++ /dev/null @@ -1,256 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - " - " - - - - - - (?<=(^\s*))\# - - - (?<!(^\s*))\# - \# - - - ''' - - - ' - - - \bREM\b - - - Boolean - Byte - Char - Date - Decimal - Double - Integer - Long - Object - SByte - Short - Single - String - UInteger - ULong - UShort - Variant - - - AddressOf - And - AndAlso - Await - Is - IsNot - Like - Mod - New - Not - Or - OrElse - Xor - - - False - Me - MyBase - MyClass - Nothing - True - - - CBool - CByte - CChar - CDate - CDbl - CDec - CInt - CLng - CObj - CSByte - CShort - CSng - CStr - CType - CUInt - CULng - CUShort - DirectCast - GetType - GetXmlNamespace - IIf - TryCast - TypeOf - - - AddHandler - Alias - As - ByRef - ByVal - Call - Case - Catch - Class - Const - Continue - Declare - Default - Delegate - Dim - Do - Each - Else - ElseIf - End - EndIf - Enum - Erase - Error - Event - Exit - Finally - For - Friend - Function - Get - Global - GoSub - GoTo - Handles - If - Implements - Imports - In - Inherits - Interface - Let - Lib - Loop - Module - MustInherit - MustOverride - Namespace - Narrowing - New - Next - NotInheritable - NotOverridable - Of - On - Operator - Option - Optional - Overloads - Overridable - Overrides - ParamArray - Partial - Private - Property - Protected - Public - RaiseEvent - ReadOnly - ReDim - RemoveHandler - Resume - Return - Select - Set - Shadows - Shared - Static - Step - Stop - Structure - Sub - SyncLock - Then - Throw - To - Try - Using - Wend - When - While - Widening - With - WithEvents - WriteOnly - - - Aggregate - Ansi - Ascending - Async - Auto - Binary - By - Compare - Custom - Descending - Distinct - Equals - Explicit - From - Group - Infer - Into - Iterator - Join - Key - Off - Preserve - Skip - Strict - Take - Text - Unicode - Until - Where - Yield - - - - - Const - Else - ElseIf - End - ExternalChecksum - ExternalSource - If - Region - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/XML-Mode.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/XML-Mode.xshd deleted file mode 100644 index 8f0bdef76..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/XML-Mode.xshd +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - <!-- - --> - - - <!\[CDATA\[ - ]]> - - - <!DOCTYPE - > - - - <\? - \?> - - - < - > - - - - " - "|(?=<) - - - ' - '|(?=<) - - [\d\w_\-\.]+(?=(\s*=)) - = - - - - - - - - & - [\w\d\#]+ - ; - - - - & - [\w\d\#]* - #missing ; - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/XmlDoc.xshd b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/XmlDoc.xshd deleted file mode 100644 index e4303de6a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/XmlDoc.xshd +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - - < - > - - - " - " - - - / - | - = - - - c - code - example - exception - list - para - param - paramref - permission - remarks - returns - see - seealso - summary - value - - type - name - cref - item - term - description - listheader - typeparam - typeparamref - - - - - - - - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichText.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichText.cs deleted file mode 100644 index dae7ea0b0..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichText.cs +++ /dev/null @@ -1,272 +0,0 @@ -// 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 -{ - /// - /// Represents a immutable piece text with highlighting information. - /// - public class RichText - { - /// - /// The empty string without any formatting information. - /// - public static readonly RichText Empty = new RichText(string.Empty); - - readonly string text; - internal readonly int[] stateChangeOffsets; - internal readonly HighlightingColor[] stateChanges; - - /// - /// Creates a RichText instance with the given text and RichTextModel. - /// - /// - /// The text to use in this RichText instance. - /// - /// - /// The model that contains the formatting to use for this RichText instance. - /// model.DocumentLength should correspond to text.Length. - /// This parameter may be null, in which case the RichText instance just holds plain text. - /// - 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; - } - - /// - /// Gets the text. - /// - public string Text { - get { return text; } - } - - /// - /// Gets the text length. - /// - 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; - } - - /// - /// Gets the HighlightingColor for the specified offset. - /// - public HighlightingColor GetHighlightingAt(int offset) - { - return stateChanges[GetIndexForOffset(offset)]; - } - - /// - /// 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. - /// - public IEnumerable 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++; - } - } - - /// - /// Creates a new RichTextModel with the formatting from this RichText. - /// - public RichTextModel ToRichTextModel() - { - return new RichTextModel(stateChangeOffsets, stateChanges.Select(ch => ch.Clone()).ToArray()); - } - - /// - /// Gets the text. - /// - public override string ToString() - { - return text; - } - - /// - /// Creates WPF Run instances that can be used for TextBlock.Inlines. - /// - 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; - } - - /// - /// Produces HTML code for the line, with <span style="..."> tags. - /// - 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(); - } - - /// - /// Produces HTML code for a section of the line, with <span style="..."> tags. - /// - 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(); - } - - /// - /// Creates a substring of this rich text. - /// - 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); - } - - /// - /// Concatenates the specified rich texts. - /// - 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); - } - - /// - /// Concatenates the specified rich texts. - /// - public static RichText operator +(RichText a, RichText b) - { - return RichText.Concat(a, b); - } - - /// - /// Implicit conversion from string to RichText. - /// - public static implicit operator RichText(string text) - { - if (text != null) - return new RichText(text); - else - return null; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichTextColorizer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichTextColorizer.cs deleted file mode 100644 index cdd7b72d0..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichTextColorizer.cs +++ /dev/null @@ -1,54 +0,0 @@ -// 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 -{ - /// - /// A colorizer that applies the highlighting from a to the editor. - /// - public class RichTextColorizer : DocumentColorizingTransformer - { - readonly RichTextModel richTextModel; - - /// - /// Creates a new RichTextColorizer instance. - /// - public RichTextColorizer(RichTextModel richTextModel) - { - if (richTextModel == null) - throw new ArgumentNullException("richTextModel"); - this.richTextModel = richTextModel; - } - - /// - 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)); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichTextModel.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichTextModel.cs deleted file mode 100644 index 10c018e98..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichTextModel.cs +++ /dev/null @@ -1,298 +0,0 @@ -// 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 -{ - /// - /// Stores rich-text formatting. - /// - public sealed class RichTextModel - { - List stateChangeOffsets = new List(); - List stateChanges = new List(); - - 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; - } - - /// - /// Creates a new RichTextModel. - /// - public RichTextModel() - { - stateChangeOffsets.Add(0); - stateChanges.Add(new HighlightingColor()); - } - - /// - /// Creates a RichTextModel from a CONTIGUOUS list of HighlightedSections. - /// - internal RichTextModel(int[] stateChangeOffsets, HighlightingColor[] stateChanges) - { - Debug.Assert(stateChangeOffsets[0] == 0); - this.stateChangeOffsets.AddRange(stateChangeOffsets); - this.stateChanges.AddRange(stateChanges); - } - - #region UpdateOffsets - /// - /// Updates the start and end offsets of all segments stored in this collection. - /// - /// TextChangeEventArgs instance describing the change to the document. - public void UpdateOffsets(TextChangeEventArgs e) - { - if (e == null) - throw new ArgumentNullException("e"); - UpdateOffsets(e.GetNewOffset); - } - - /// - /// Updates the start and end offsets of all segments stored in this collection. - /// - /// OffsetChangeMap instance describing the change to the document. - public void UpdateOffsets(OffsetChangeMap change) - { - if (change == null) - throw new ArgumentNullException("change"); - UpdateOffsets(change.GetNewOffset); - } - - /// - /// Updates the start and end offsets of all segments stored in this collection. - /// - /// OffsetChangeMapEntry instance describing the change to the document. - public void UpdateOffsets(OffsetChangeMapEntry change) - { - UpdateOffsets(change.GetNewOffset); - } - - void UpdateOffsets(Func 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 - - /// - /// Appends another RichTextModel after this one. - /// - 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]); - } - } - - /// - /// Gets a copy of the HighlightingColor for the specified offset. - /// - public HighlightingColor GetHighlightingAt(int offset) - { - return stateChanges[GetIndexForOffsetUseExistingSegment(offset)].Clone(); - } - - /// - /// Applies the HighlightingColor to the specified range of text. - /// If the color specifies null for some properties, existing highlighting is preserved. - /// - 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); - } - } - - /// - /// Sets the HighlightingColor for the specified range of text, - /// completely replacing the existing highlighting in that area. - /// - 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)); - } - - /// - /// Sets the foreground brush on the specified text segment. - /// - 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; - } - } - - /// - /// Sets the background brush on the specified text segment. - /// - 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; - } - } - - /// - /// Sets the font weight on the specified text segment. - /// - 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; - } - } - - /// - /// Sets the font style on the specified text segment. - /// - 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; - } - } - - /// - /// 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. - /// - public IEnumerable 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++; - } - } - - /// - /// Creates WPF Run instances that can be used for TextBlock.Inlines. - /// - /// The text source that holds the text for this RichTextModel. - 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichTextModelWriter.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichTextModelWriter.cs deleted file mode 100644 index 66c455e26..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/RichTextModelWriter.cs +++ /dev/null @@ -1,128 +0,0 @@ -// 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 -{ - /// - /// A RichTextWriter that writes into a document and RichTextModel. - /// - class RichTextModelWriter : PlainRichTextWriter - { - readonly RichTextModel richTextModel; - readonly DocumentTextWriter documentTextWriter; - readonly Stack colorStack = new Stack(); - HighlightingColor currentColor; - int currentColorBegin = -1; - - /// - /// Creates a new RichTextModelWriter that inserts into document, starting at insertionOffset. - /// - 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)); - } - - /// - /// Gets/Sets the current insertion offset. - /// - public int InsertionOffset { - get { return documentTextWriter.InsertionOffset; } - set { documentTextWriter.InsertionOffset = value; } - } - - - /// - protected override void BeginUnhandledSpan() - { - colorStack.Push(currentColor); - } - - void BeginColorSpan() - { - WriteIndentationIfNecessary(); - colorStack.Push(currentColor); - currentColor = currentColor.Clone(); - currentColorBegin = documentTextWriter.InsertionOffset; - } - - /// - public override void EndSpan() - { - currentColor = colorStack.Pop(); - currentColorBegin = documentTextWriter.InsertionOffset; - } - - /// - protected override void AfterWrite() - { - base.AfterWrite(); - richTextModel.SetHighlighting(currentColorBegin, documentTextWriter.InsertionOffset - currentColorBegin, currentColor); - } - - /// - public override void BeginSpan(Color foregroundColor) - { - BeginColorSpan(); - currentColor.Foreground = new SimpleHighlightingBrush(foregroundColor); - currentColor.Freeze(); - } - - /// - public override void BeginSpan(FontFamily fontFamily) - { - BeginUnhandledSpan(); // TODO - } - - /// - public override void BeginSpan(FontStyle fontStyle) - { - BeginColorSpan(); - currentColor.FontStyle = fontStyle; - currentColor.Freeze(); - } - - /// - public override void BeginSpan(FontWeight fontWeight) - { - BeginColorSpan(); - currentColor.FontWeight = fontWeight; - currentColor.Freeze(); - } - - /// - public override void BeginSpan(HighlightingColor highlightingColor) - { - BeginColorSpan(); - currentColor.MergeWith(highlightingColor); - currentColor.Freeze(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/HighlightingLoader.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/HighlightingLoader.cs deleted file mode 100644 index 5c17691a1..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/HighlightingLoader.cs +++ /dev/null @@ -1,114 +0,0 @@ -// 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 -{ - /// - /// Static class with helper methods to load XSHD highlighting files. - /// - public static class HighlightingLoader - { - #region XSHD loading - /// - /// Lodas a syntax definition from the xml reader. - /// - 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 - /// - /// Creates a highlighting definition from the XSHD file. - /// - public static IHighlightingDefinition Load(XshdSyntaxDefinition syntaxDefinition, IHighlightingDefinitionReferenceResolver resolver) - { - if (syntaxDefinition == null) - throw new ArgumentNullException("syntaxDefinition"); - return new XmlHighlightingDefinition(syntaxDefinition, resolver); - } - - /// - /// Creates a highlighting definition from the XSHD file. - /// - public static IHighlightingDefinition Load(XmlReader reader, IHighlightingDefinitionReferenceResolver resolver) - { - return Load(LoadXshd(reader), resolver); - } - #endregion - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/IXshdVisitor.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/IXshdVisitor.cs deleted file mode 100644 index 951134666..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/IXshdVisitor.cs +++ /dev/null @@ -1,46 +0,0 @@ -// 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 -{ - /// - /// A visitor over the XSHD element tree. - /// - public interface IXshdVisitor - { - /// Visit method for XshdRuleSet - object VisitRuleSet(XshdRuleSet ruleSet); - - /// Visit method for XshdColor - object VisitColor(XshdColor color); - - /// Visit method for XshdKeywords - object VisitKeywords(XshdKeywords keywords); - - /// Visit method for XshdSpan - object VisitSpan(XshdSpan span); - - /// Visit method for XshdImport - object VisitImport(XshdImport import); - - /// Visit method for XshdRule - object VisitRule(XshdRule rule); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/SaveXshdVisitor.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/SaveXshdVisitor.cs deleted file mode 100644 index fc89d0d65..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/SaveXshdVisitor.cs +++ /dev/null @@ -1,197 +0,0 @@ -// 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 -{ - /// - /// Xshd visitor implementation that saves an .xshd file as XML. - /// - public sealed class SaveXshdVisitor : IXshdVisitor - { - /// - /// XML namespace for XSHD. - /// - public const string Namespace = V2Loader.Namespace; - - XmlWriter writer; - - /// - /// Creates a new SaveXshdVisitor instance. - /// - public SaveXshdVisitor(XmlWriter writer) - { - if (writer == null) - throw new ArgumentNullException("writer"); - this.writer = writer; - } - - /// - /// Writes the specified syntax definition. - /// - 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 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 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 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/V1Loader.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/V1Loader.cs deleted file mode 100644 index 67b1f2762..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/V1Loader.cs +++ /dev/null @@ -1,340 +0,0 @@ -// 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 -{ - /// - /// Loads .xshd files, version 1.0. - /// - 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 '' in main rule set. - mainRuleSetElement.Elements.Add( - new XshdImport { RuleSetReference = new XshdReference( - 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 GetColorReference(XmlElement element) - { - XshdColor color = GetColorFromElement(element); - if (color != null) - return new XshdReference(color); - else - return new XshdReference(); - } - - 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( - 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(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(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(@"(? - /// Loads .xshd files, version 2.0. - /// Version 2.0 files are recognized by the namespace. - /// - 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 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(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); - } - - /// - /// Sets the element's position to the XmlReader's position. - /// - 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 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(ruleSet.Substring(0, pos), ruleSet.Substring(pos + 1)); - } else { - return new XshdReference(null, ruleSet); - } - } else { - return new XshdReference(); - } - } - - 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 ParseColorReference(XmlReader reader) - { - string color = reader.GetAttribute("color"); - if (color != null) { - int pos = color.LastIndexOf('/'); - if (pos >= 0) { - return new XshdReference(color.Substring(0, pos), color.Substring(pos + 1)); - } else { - return new XshdReference(null, color); - } - } else { - return new XshdReference(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")); - color.Underline = reader.GetBoolAttribute("underline"); - 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XmlHighlightingDefinition.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XmlHighlightingDefinition.cs deleted file mode 100644 index 9743277ba..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XmlHighlightingDefinition.cs +++ /dev/null @@ -1,422 +0,0 @@ -// 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()) - propDict.Add(p.Name, p.Value); - } - - #region RegisterNamedElements - sealed class RegisterNamedElementsVisitor : IXshdVisitor - { - XmlHighlightingDefinition def; - internal readonly Dictionary ruleSets - = new Dictionary(); - - 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 ruleSetDict; - readonly Dictionary reverseRuleSetDict; - readonly IHighlightingDefinitionReferenceResolver resolver; - HashSet processingStartedRuleSets = new HashSet(); - HashSet processedRuleSets = new HashSet(); - bool ignoreCase; - - public TranslateElementVisitor(XmlHighlightingDefinition def, Dictionary ruleSetDict, IHighlightingDefinitionReferenceResolver resolver) - { - Debug.Assert(def != null); - Debug.Assert(ruleSetDict != null); - this.def = def; - this.ruleSetDict = ruleSetDict; - this.resolver = resolver; - reverseRuleSetDict = new Dictionary(); - 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 "); - - 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.Underline = color.Underline; - 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 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 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 ruleSetDict = new Dictionary(); - Dictionary colorDict = new Dictionary(); - [OptionalField] - Dictionary propDict = new Dictionary(); - - 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 NamedHighlightingColors { - get { - return colorDict.Values; - } - } - - public override string ToString() - { - return this.Name; - } - - public IDictionary Properties { - get { - return propDict; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdColor.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdColor.cs deleted file mode 100644 index a6968508b..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdColor.cs +++ /dev/null @@ -1,126 +0,0 @@ -// 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 -{ - /// - /// A color in an Xshd file. - /// - [Serializable] - public class XshdColor : XshdElement, ISerializable - { - /// - /// Gets/sets the name. - /// - public string Name { get; set; } - - /// - /// Gets/sets the foreground brush. - /// - public HighlightingBrush Foreground { get; set; } - - /// - /// Gets/sets the background brush. - /// - public HighlightingBrush Background { get; set; } - - /// - /// Gets/sets the font weight. - /// - public FontWeight? FontWeight { get; set; } - - /// - /// Gets/sets the underline flag - /// - public bool? Underline { get; set; } - - /// - /// Gets/sets the font style. - /// - public FontStyle? FontStyle { get; set; } - - /// - /// Gets/Sets the example text that demonstrates where the color is used. - /// - public string ExampleText { get; set; } - - /// - /// Creates a new XshdColor instance. - /// - public XshdColor() - { - } - - /// - /// Deserializes an XshdColor. - /// - 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"); - if (info.GetBoolean("HasUnderline")) - this.Underline = info.GetBoolean("Underline"); - } - - /// - /// Serializes this XshdColor instance. - /// - #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("HasUnderline", this.Underline.HasValue); - if (this.Underline.HasValue) - info.AddValue("Underline", this.Underline.Value); - 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); - } - - /// - public override object AcceptVisitor(IXshdVisitor visitor) - { - return visitor.VisitColor(this); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdElement.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdElement.cs deleted file mode 100644 index 9ba63545a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdElement.cs +++ /dev/null @@ -1,44 +0,0 @@ -// 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 -{ - /// - /// An element in a XSHD rule set. - /// - [Serializable] - public abstract class XshdElement - { - /// - /// Gets the line number in the .xshd file. - /// - public int LineNumber { get; set; } - - /// - /// Gets the column number in the .xshd file. - /// - public int ColumnNumber { get; set; } - - /// - /// Applies the visitor to this element. - /// - public abstract object AcceptVisitor(IXshdVisitor visitor); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdImport.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdImport.cs deleted file mode 100644 index 262b20391..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdImport.cs +++ /dev/null @@ -1,40 +0,0 @@ -// 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 -{ - /// - /// <Import> element. - /// - [Serializable] - public class XshdImport : XshdElement - { - /// - /// Gets/sets the referenced rule set. - /// - public XshdReference RuleSetReference { get; set; } - - /// - public override object AcceptVisitor(IXshdVisitor visitor) - { - return visitor.VisitImport(this); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdKeywords.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdKeywords.cs deleted file mode 100644 index 19eb01f33..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdKeywords.cs +++ /dev/null @@ -1,51 +0,0 @@ -// 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 -{ - /// - /// A list of keywords. - /// - [Serializable] - public class XshdKeywords : XshdElement - { - /// - /// The color. - /// - public XshdReference ColorReference { get; set; } - - readonly NullSafeCollection words = new NullSafeCollection(); - - /// - /// Gets the list of key words. - /// - public IList Words { - get { return words; } - } - - /// - public override object AcceptVisitor(IXshdVisitor visitor) - { - return visitor.VisitKeywords(this); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdProperty.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdProperty.cs deleted file mode 100644 index 73b379532..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdProperty.cs +++ /dev/null @@ -1,53 +0,0 @@ -// 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 -{ - /// - /// A property in an Xshd file. - /// - [Serializable] - public class XshdProperty : XshdElement - { - /// - /// Gets/sets the name. - /// - public string Name { get; set; } - - /// - /// Gets/sets the value. - /// - public string Value { get; set; } - - /// - /// Creates a new XshdColor instance. - /// - public XshdProperty() - { - } - - /// - public override object AcceptVisitor(IXshdVisitor visitor) - { - return null; -// return visitor.VisitProperty(this); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdReference.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdReference.cs deleted file mode 100644 index 4ea9d6835..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdReference.cs +++ /dev/null @@ -1,142 +0,0 @@ -// 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 -{ - /// - /// A reference to an xshd color, or an inline xshd color. - /// - [Serializable] - public struct XshdReference : IEquatable> where T : XshdElement - { - string referencedDefinition; - string referencedElement; - T inlineElement; - - /// - /// Gets the reference. - /// - public string ReferencedDefinition { - get { return referencedDefinition; } - } - - /// - /// Gets the reference. - /// - public string ReferencedElement { - get { return referencedElement; } - } - - /// - /// Gets the inline element. - /// - public T InlineElement { - get { return inlineElement; } - } - - /// - /// Creates a new XshdReference instance. - /// - public XshdReference(string referencedDefinition, string referencedElement) - { - if (referencedElement == null) - throw new ArgumentNullException("referencedElement"); - this.referencedDefinition = referencedDefinition; - this.referencedElement = referencedElement; - this.inlineElement = null; - } - - /// - /// Creates a new XshdReference instance. - /// - public XshdReference(T inlineElement) - { - if (inlineElement == null) - throw new ArgumentNullException("inlineElement"); - this.referencedDefinition = null; - this.referencedElement = null; - this.inlineElement = inlineElement; - } - - /// - /// Applies the visitor to the inline element, if there is any. - /// - 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" declaration. - - /// - public override bool Equals(object obj) - { - if (obj is XshdReference) - return Equals((XshdReference)obj); // use Equals method below - else - return false; - } - - /// - /// Equality operator. - /// - public bool Equals(XshdReference other) - { - // add comparisions for all members here - return this.referencedDefinition == other.referencedDefinition - && this.referencedElement == other.referencedElement - && this.inlineElement == other.inlineElement; - } - - /// - 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; - } - - /// - /// Equality operator. - /// - public static bool operator ==(XshdReference left, XshdReference right) - { - return left.Equals(right); - } - - /// - /// Inequality operator. - /// - public static bool operator !=(XshdReference left, XshdReference right) - { - return !left.Equals(right); - } - #endregion - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdRule.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdRule.cs deleted file mode 100644 index b339aee9c..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdRule.cs +++ /dev/null @@ -1,50 +0,0 @@ -// 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 -{ - /// - /// <Rule> element. - /// - [Serializable] - public class XshdRule : XshdElement - { - /// - /// Gets/sets the rule regex. - /// - public string Regex { get; set; } - - /// - /// Gets/sets the rule regex type. - /// - public XshdRegexType RegexType { get; set; } - - /// - /// Gets/sets the color reference. - /// - public XshdReference ColorReference { get; set; } - - /// - public override object AcceptVisitor(IXshdVisitor visitor) - { - return visitor.VisitRule(this); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdRuleSet.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdRuleSet.cs deleted file mode 100644 index d1361be5a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdRuleSet.cs +++ /dev/null @@ -1,66 +0,0 @@ -// 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 -{ - /// - /// A rule set in a XSHD file. - /// - [Serializable] - public class XshdRuleSet : XshdElement - { - /// - /// Gets/Sets the name of the rule set. - /// - public string Name { get; set; } - - /// - /// Gets/sets whether the case is ignored in expressions inside this rule set. - /// - public bool? IgnoreCase { get; set; } - - readonly NullSafeCollection elements = new NullSafeCollection(); - - /// - /// Gets the collection of elements. - /// - public IList Elements { - get { return elements; } - } - - /// - /// Applies the visitor to all elements. - /// - public void AcceptElements(IXshdVisitor visitor) - { - foreach (XshdElement element in Elements) { - element.AcceptVisitor(visitor); - } - } - - /// - public override object AcceptVisitor(IXshdVisitor visitor) - { - return visitor.VisitRuleSet(this); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdSpan.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdSpan.cs deleted file mode 100644 index b625f0be5..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdSpan.cs +++ /dev/null @@ -1,97 +0,0 @@ -// 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 -{ - /// - /// Specifies the type of the regex. - /// - public enum XshdRegexType - { - /// - /// Normal regex. Used when the regex was specified as attribute. - /// - Default, - /// - /// Ignore pattern whitespace / allow regex comments. Used when the regex was specified as text element. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", - Justification = "Using the same case as the RegexOption")] - IgnorePatternWhitespace - } - - /// - /// <Span> element. - /// - [Serializable] - public class XshdSpan : XshdElement - { - /// - /// Gets/sets the begin regex. - /// - public string BeginRegex { get; set; } - - /// - /// Gets/sets the begin regex type. - /// - public XshdRegexType BeginRegexType { get; set; } - - /// - /// Gets/sets the end regex. - /// - public string EndRegex { get; set; } - - /// - /// Gets/sets the end regex type. - /// - public XshdRegexType EndRegexType { get; set; } - - /// - /// Gets/sets whether the span is multiline. - /// - public bool Multiline { get; set; } - - /// - /// Gets/sets the rule set reference. - /// - public XshdReference RuleSetReference { get; set; } - - /// - /// Gets/sets the span color. - /// - public XshdReference SpanColorReference { get; set; } - - /// - /// Gets/sets the span begin color. - /// - public XshdReference BeginColorReference { get; set; } - - /// - /// Gets/sets the span end color. - /// - public XshdReference EndColorReference { get; set; } - - /// - public override object AcceptVisitor(IXshdVisitor visitor) - { - return visitor.VisitSpan(this); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdSyntaxDefinition.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdSyntaxDefinition.cs deleted file mode 100644 index d762115ea..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XshdSyntaxDefinition.cs +++ /dev/null @@ -1,65 +0,0 @@ -// 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 -{ - /// - /// A <SyntaxDefinition> element. - /// - [Serializable] - public class XshdSyntaxDefinition - { - /// - /// Creates a new XshdSyntaxDefinition object. - /// - public XshdSyntaxDefinition() - { - this.Elements = new NullSafeCollection(); - this.Extensions = new NullSafeCollection(); - } - - /// - /// Gets/sets the definition name - /// - public string Name { get; set; } - - /// - /// Gets the associated extensions. - /// - public IList Extensions { get; private set; } - - /// - /// Gets the collection of elements. - /// - public IList Elements { get; private set; } - - /// - /// Applies the visitor to all elements. - /// - public void AcceptElements(IXshdVisitor visitor) - { - foreach (XshdElement element in Elements) { - element.AcceptVisitor(visitor); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/ICSharpCode.AvalonEdit.csproj b/AvalonEdit/ICSharpCode.AvalonEdit/ICSharpCode.AvalonEdit.csproj deleted file mode 100644 index 355e81520..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/ICSharpCode.AvalonEdit.csproj +++ /dev/null @@ -1,457 +0,0 @@ - - - - {6C55B776-26D4-4DB3-A6AB-87E783B2F3D1} - Debug - Net40 - Library - ICSharpCode.AvalonEdit - ICSharpCode.AvalonEdit - Properties - False - False - 4 - False - True - ICSharpCode.AvalonEdit.snk - False - File - False - -Microsoft.Design#CA1020;-Microsoft.Design#CA1033;-Microsoft.Performance#CA1805;-Microsoft.Performance#CA1810 - 1607 - - - False - obj\$(Configuration)\ - False - Auto - 4194304 - AnyCPU - 4096 - - - v3.5 - - - v4.0 - DOTNET4 - - - v4.5 - DOTNET4;NREFACTORY - ..\..\NRefactory\ICSharpCode.NRefactory.snk - - - bin\Debug\ - bin\Debug\ICSharpCode.AvalonEdit.xml - true - False - True - obj\ - Full - True - True - - - bin\Release\ - bin\Release\ICSharpCode.AvalonEdit.xml - false - True - False - Full - True - - - DOTNET4;NREFACTORY - - - DOTNET4;NREFACTORY - - - - - {3B2A5653-EC97-4001-BB9B-D90F1AF2C371} - ICSharpCode.NRefactory - - - 4.0 - - - 3.0 - - - 3.0 - - - - 3.5 - - - - 3.5 - - - - 3.0 - - - - - 4.0 - - - - 3.5 - - - 3.0 - - - 3.0 - - - 3.0 - - - - - - - - - Code - - - - - - - - UndoStack.cs - - - - - - - - - - UndoStack.cs - - - DocumentLine.cs - - - - - TextDocument.cs - - - - - - TextAnchor.cs - - - TextAnchor.cs - - - - - - UndoStack.cs - - - - - ILineTracker.cs - - - - - - - - - - - - - Selection.cs - - - - - - - - - - - - - IReadOnlySectionProvider.cs - - - Selection.cs - - - - Selection.cs - - - Selection.cs - - - Selection.cs - - - Selection.cs - - - - - - IReadOnlySectionProvider.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IBackgroundRenderer.cs - - - HeightTree.cs - - - IVisualLineTransformer.cs - - - - - - IVisualLineTransformer.cs - - - - TextView.cs - - - - HeightTree.cs - - - HeightTree.cs - - - - - VisualLineElementGenerator.cs - - - TextView.cs - - - - TextView.cs - - - TextView.cs - - - - - FormattedTextElement.cs - - - - TextView.cs - - - - - TextView.cs - - - - - - - VisualLine.cs - - - - - - VisualLine.cs - - - VisualLineElementGenerator.cs - - - VisualLine.cs - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - TextDocument.cs - - - TextDocument.cs - - - - DocumentLine.cs - - - - - TextEditor.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - SearchPanel.cs - - - DropDownButton.cs - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/ICSharpCode.AvalonEdit.snk b/AvalonEdit/ICSharpCode.AvalonEdit/ICSharpCode.AvalonEdit.snk deleted file mode 100644 index de7b334c86a7003cd077c9f9785c16d184d9f3c4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 596 zcmV-a0;~N80ssI2Bme+XQ$aES1ONa50098;giFZF+&6i!<(CRD*Z^jP6cT|o_14WN zPI7O2g!|j~O3|$ipSqk1Y{pCx(DteAyXUhjZyDJ4G~vN8flWZ)RR5g@JmQ=8uZFa0 zY4GB?5SbfNqOL?XNa2~Fl}G1BW6R;^E{Qf!H2+h!qs}N470c)1-?iipRAzrQ+yu(w z$P{om`NK$yEKyyKtvV%CP(^&m?>W;Xrj>n4;&Dq(<(RrfvxzMNV014usPQy;yvl|} zGkyHZ0F_Rcdj9kqXHBoLFK>On2q ztI7s}*Flepk^B_#^sP6nfWzw1N1g4Bk*)Yo%#J@TUkRT}DY(isQBFK6)zfLE$I>am z3-S>_y*0wZpXlx_EMMNKzsvXfeEJi7O7eE6c)O_9jFvg4a)5vGG0o{YR@6i=-y)?R zl!~D}rU_^6J{*V#jKviP8T~MdnQQT8{^fA6xqGc$&(CnGEY0nFoZ7o_n3rQGiov#) z;vt4MKGa}Uk##Ar_H>H!TMVw359%Xae>%4fvTyoz8jRTBwb05ssCi_dXf-x0^+lPi zyuav**}5AA;gfe4aY4f>0gDor=a7Aduh?M0JbWy6VA;p9=ski%0~2?zs^$wiK8EQ6 ikh0tvmL65;V`KSaE~>96QbW% - /// Smart indentation for C#. - /// - public class CSharpIndentationStrategy : DefaultIndentationStrategy - { - /// - /// Creates a new CSharpIndentationStrategy. - /// - public CSharpIndentationStrategy() - { - } - - /// - /// Creates a new CSharpIndentationStrategy and initializes the settings using the text editor options. - /// - public CSharpIndentationStrategy(TextEditorOptions options) - { - this.IndentationString = options.IndentationString; - } - - string indentationString = "\t"; - - /// - /// Gets/Sets the indentation string. - /// - public string IndentationString { - get { return indentationString; } - set { - if (string.IsNullOrEmpty(value)) - throw new ArgumentException("Indentation string must not be null or empty"); - indentationString = value; - } - } - - /// - /// Performs indentation using the specified document accessor. - /// - /// Object used for accessing the document line-by-line - /// Specifies whether empty lines should be kept - 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); - } - - /// - 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); - } - } - - /// - public override void IndentLines(TextDocument document, int beginLine, int endLine) - { - Indent(new TextDocumentAccessor(document, beginLine, endLine), true); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Indentation/CSharp/DocumentAccessor.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Indentation/CSharp/DocumentAccessor.cs deleted file mode 100644 index 7cafb3517..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Indentation/CSharp/DocumentAccessor.cs +++ /dev/null @@ -1,122 +0,0 @@ -// 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 -{ - /// - /// Interface used for the indentation class to access the document. - /// - public interface IDocumentAccessor - { - /// Gets if the current line is read only (because it is not in the - /// selected text region) - bool IsReadOnly { get; } - /// Gets the number of the current line. - int LineNumber { get; } - /// Gets/Sets the text of the current line. - string Text { get; set; } - /// Advances to the next line. - bool MoveNext(); - } - - #region TextDocumentAccessor - /// - /// Adapter IDocumentAccessor -> TextDocument - /// - public sealed class TextDocumentAccessor : IDocumentAccessor - { - readonly TextDocument doc; - readonly int minLine; - readonly int maxLine; - - /// - /// Creates a new TextDocumentAccessor. - /// - public TextDocumentAccessor(TextDocument document) - { - if (document == null) - throw new ArgumentNullException("document"); - doc = document; - this.minLine = 1; - this.maxLine = doc.LineCount; - } - - /// - /// Creates a new TextDocumentAccessor that indents only a part of the document. - /// - 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; - - /// - public bool IsReadOnly { - get { - return num < minLine; - } - } - - /// - public int LineNumber { - get { - return num; - } - } - - bool lineDirty; - - /// - public string Text { - get { return text; } - set { - if (num < minLine) return; - text = value; - lineDirty = true; - } - } - - /// - 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 -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Indentation/CSharp/IndentationReformatter.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Indentation/CSharp/IndentationReformatter.cs deleted file mode 100644 index 31c0b4dc7..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Indentation/CSharp/IndentationReformatter.cs +++ /dev/null @@ -1,489 +0,0 @@ -// 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"; - /// Leave empty lines empty. - public bool LeaveEmptyLines = true; - } - - sealed class IndentationReformatter - { - /// - /// An indentation block. Tracks the state of the indentation. - /// - struct Block - { - /// - /// The indentation outside of the block. - /// - public string OuterIndent; - - /// - /// The indentation inside the block. - /// - public string InnerIndent; - - /// - /// 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 '{'. - /// - public string LastWord; - - /// - /// The type of bracket that opened this block (, [ or { - /// - public char Bracket; - - /// - /// Gets whether there's currently a line continuation going on inside this block. - /// - public bool Continuation; - - /// - /// 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. - /// - public int OneLineBlock; - - /// - /// The previous value of one-line-block before it was reset. - /// Used to restore the indentation of 'else' to the correct level. - /// - public int PreviousOneLineBlock; - - public void ResetOneLineBlock() - { - PreviousOneLineBlock = OneLineBlock; - OneLineBlock = 0; - } - - /// - /// Gets the line number where this block started. - /// - 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 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 = 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Indentation/DefaultIndentationStrategy.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Indentation/DefaultIndentationStrategy.cs deleted file mode 100644 index 2ac7c2e48..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Indentation/DefaultIndentationStrategy.cs +++ /dev/null @@ -1,55 +0,0 @@ -// 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 -{ - /// - /// Handles indentation by copying the indentation from the previous line. - /// Does not support indenting multiple lines. - /// - public class DefaultIndentationStrategy : IIndentationStrategy - { - /// - 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); - } - } - - /// - /// Does nothing: indenting multiple lines is useless without a smart indentation strategy. - /// - public virtual void IndentLines(TextDocument document, int beginLine, int endLine) - { - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Indentation/IIndentationStrategy.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Indentation/IIndentationStrategy.cs deleted file mode 100644 index 81afddbe0..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Indentation/IIndentationStrategy.cs +++ /dev/null @@ -1,40 +0,0 @@ -// 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 -{ - /// - /// Strategy how the text editor handles indentation when new lines are inserted. - /// - public interface IIndentationStrategy - { - /// - /// Sets the indentation for the specified line. - /// Usually this is constructed from the indentation of the previous line. - /// - void IndentLine(TextDocument document, DocumentLine line); - - /// - /// Reindents a set of lines. - /// - void IndentLines(TextDocument document, int beginLine, int endLine); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Properties/AssemblyInfo.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Properties/AssemblyInfo.cs deleted file mode 100644 index 21160ccbc..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,71 +0,0 @@ -// 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. - -#region Using directives - -using System; -using System.Reflection; -using System.Resources; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Windows; -using System.Windows.Markup; - -#endregion - -// 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: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -[assembly: CLSCompliant(true)] - -[assembly:InternalsVisibleTo("ICSharpCode.AvalonEdit.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100F1844BC8CBDC3779B0E5970A30D800668414128135F5D6CD274E726F7C84FBDBF74AD1AD0D9FBA9C0A6CC64C11D0F6A9EDBBE7B32B6F19D8F734E1C130814D40DF54FF9D063CE29BF7AF86B46A69F0E2B910991B52A2AE443648E199A09547E74663CBE1E72E89365034FF53B6A3CE281415CBE7E2DFB5E40E54667F35DC04CA")] - -[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: System.Runtime.InteropServices.ComVisible(false)] -[assembly: AssemblyCompany("ic#code")] -[assembly: AssemblyProduct("SharpDevelop")] -[assembly: AssemblyCopyright("2000-2014 AlphaSierraPapa for the SharpDevelop Team")] -[assembly: AssemblyVersion("5.0.1")] -[assembly: NeutralResourcesLanguage("en-US")] - -[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")] - -namespace ICSharpCode.NRefactory.Editor {} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Properties/CodeAnalysisDictionary.xml b/AvalonEdit/ICSharpCode.AvalonEdit/Properties/CodeAnalysisDictionary.xml deleted file mode 100644 index 71301b91d..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Properties/CodeAnalysisDictionary.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - Uncollapse - Foldings - Xshd - Utils - Deque - Colorizer - Renderer - Renderers - Deletable - - y - - - - Lineup - - - - Bestest - - - - - - WiX - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/BackgroundGeometryBuilder.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/BackgroundGeometryBuilder.cs deleted file mode 100644 index 73f135cfe..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/BackgroundGeometryBuilder.cs +++ /dev/null @@ -1,358 +0,0 @@ -// 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 -{ - /// - /// Helper for creating a PathGeometry. - /// - public sealed class BackgroundGeometryBuilder - { - double cornerRadius; - - /// - /// Gets/sets the radius of the rounded corners. - /// - public double CornerRadius { - get { return cornerRadius; } - set { cornerRadius = value; } - } - - /// - /// Gets/Sets whether to align the geometry to whole pixels. - /// - public bool AlignToWholePixels { get; set; } - - /// - /// Gets/Sets whether to align the geometry to the middle of pixels. - /// - public bool AlignToMiddleOfPixels { get; set; } - - /// - /// Gets/Sets whether to extend the rectangles to full width at line end. - /// - public bool ExtendToFullWidthAtLineEnd { get; set; } - - /// - /// Creates a new BackgroundGeometryBuilder instance. - /// - public BackgroundGeometryBuilder() - { - } - - /// - /// Adds the specified segment to the geometry. - /// - 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); - } - } - - /// - /// Adds a rectangle to the geometry. - /// - /// - /// This overload will align the coordinates according to - /// or . - /// Use the -overload instead if the coordinates should not be aligned. - /// - 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); - } - } - - /// - /// 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). - /// - public static IEnumerable 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 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; - } - } - - /// - /// Calculates the rectangles for the visual column segment. - /// This returns one rectangle for each line inside the segment. - /// - public static IEnumerable 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 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; - - /// - /// Adds a rectangle to the geometry. - /// - /// - /// This overload assumes that the coordinates are aligned properly - /// (see , ). - /// Use the -overload instead if the coordinates are not yet aligned. - /// - 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; - } - - /// - /// Closes the current figure. - /// - 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; - } - } - - /// - /// Creates the geometry. - /// Returns null when the geometry is empty! - /// - public Geometry CreateGeometry() - { - CloseFigure(); - if (figures.Count != 0) { - PathGeometry g = new PathGeometry(figures); - g.Freeze(); - return g; - } else { - return null; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/CollapsedLineSection.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/CollapsedLineSection.cs deleted file mode 100644 index 808fe7c82..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/CollapsedLineSection.cs +++ /dev/null @@ -1,110 +0,0 @@ -// 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 -{ - /// - /// Represents a collapsed line section. - /// Use the Uncollapse() method to uncollapse the section. - /// - 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 - } - - /// - /// Gets if the document line is collapsed. - /// This property initially is true and turns to false when uncollapsing the section. - /// - public bool IsCollapsed { - get { return start != null; } - } - - /// - /// Gets the start line of the section. - /// When the section is uncollapsed or the text containing it is deleted, - /// this property returns null. - /// - public DocumentLine Start { - get { return start; } - internal set { start = value; } - } - - /// - /// Gets the end line of the section. - /// When the section is uncollapsed or the text containing it is deleted, - /// this property returns null. - /// - public DocumentLine End { - get { return end; } - internal set { end = value; } - } - - /// - /// Uncollapses the section. - /// This causes the Start and End properties to be set to null! - /// Does nothing if the section is already uncollapsed. - /// - public void Uncollapse() - { - if (start == null) - return; - - heightTree.Uncollapse(this); - #if DEBUG - heightTree.CheckProperties(); - #endif - - start = null; - end = null; - } - - /// - /// Gets a string representation of the collapsed section. - /// - [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") + "]"; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ColorizingTransformer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ColorizingTransformer.cs deleted file mode 100644 index d1a0d0c0b..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ColorizingTransformer.cs +++ /dev/null @@ -1,123 +0,0 @@ -// 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 -{ - /// - /// Base class for that helps - /// splitting visual elements so that colors (and other text properties) can be easily assigned - /// to individual words/characters. - /// - public abstract class ColorizingTransformer : IVisualLineTransformer, ITextViewConnect - { - /// - /// Gets the list of elements currently being transformed. - /// - protected IList CurrentElements { get; private set; } - - /// - /// implementation. - /// Sets and calls . - /// - public void Transform(ITextRunConstructionContext context, IList 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; - } - } - - /// - /// Performs the colorization. - /// - protected abstract void Colorize(ITextRunConstructionContext context); - - /// - /// Changes visual element properties. - /// This method accesses , so it must be called only during - /// a call. - /// This method splits s as necessary to ensure that the region - /// can be colored by setting the of whole elements, - /// and then calls the on all elements in the region. - /// - /// Start visual column of the region to change - /// End visual column of the region to change - /// Action that changes an individual . - protected void ChangeVisualElements(int visualStartColumn, int visualEndColumn, Action 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); - } - } - } - } - - /// - /// Called when added to a text view. - /// - protected virtual void OnAddToTextView(TextView textView) - { - } - - /// - /// Called when removed from a text view. - /// - protected virtual void OnRemoveFromTextView(TextView textView) - { - } - - void ITextViewConnect.AddToTextView(TextView textView) - { - OnAddToTextView(textView); - } - - void ITextViewConnect.RemoveFromTextView(TextView textView) - { - OnRemoveFromTextView(textView); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ColumnRulerRenderer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ColumnRulerRenderer.cs deleted file mode 100644 index 2af7f0ba7..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ColumnRulerRenderer.cs +++ /dev/null @@ -1,79 +0,0 @@ -// 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 -{ - /// - /// Renders a ruler at a certain column. - /// - 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/CurrentLineHighlightRenderer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/CurrentLineHighlightRenderer.cs deleted file mode 100644 index 854b9644c..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/CurrentLineHighlightRenderer.cs +++ /dev/null @@ -1,88 +0,0 @@ -// 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); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/DefaultTextRunTypographyProperties.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/DefaultTextRunTypographyProperties.cs deleted file mode 100644 index 38843ab40..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/DefaultTextRunTypographyProperties.cs +++ /dev/null @@ -1,186 +0,0 @@ -// 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 -{ - /// - /// Default implementation for TextRunTypographyProperties. - /// - public class DefaultTextRunTypographyProperties : TextRunTypographyProperties - { - /// - public override FontVariants Variants { - get { return FontVariants.Normal; } - } - - /// - public override bool StylisticSet1 { get { return false; } } - /// - public override bool StylisticSet2 { get { return false; } } - /// - public override bool StylisticSet3 { get { return false; } } - /// - public override bool StylisticSet4 { get { return false; } } - /// - public override bool StylisticSet5 { get { return false; } } - /// - public override bool StylisticSet6 { get { return false; } } - /// - public override bool StylisticSet7 { get { return false; } } - /// - public override bool StylisticSet8 { get { return false; } } - /// - public override bool StylisticSet9 { get { return false; } } - /// - public override bool StylisticSet10 { get { return false; } } - /// - public override bool StylisticSet11 { get { return false; } } - /// - public override bool StylisticSet12 { get { return false; } } - /// - public override bool StylisticSet13 { get { return false; } } - /// - public override bool StylisticSet14 { get { return false; } } - /// - public override bool StylisticSet15 { get { return false; } } - /// - public override bool StylisticSet16 { get { return false; } } - /// - public override bool StylisticSet17 { get { return false; } } - /// - public override bool StylisticSet18 { get { return false; } } - /// - public override bool StylisticSet19 { get { return false; } } - /// - public override bool StylisticSet20 { get { return false; } } - - /// - public override int StylisticAlternates { - get { return 0; } - } - - /// - public override int StandardSwashes { - get { return 0; } - } - - /// - public override bool StandardLigatures { - get { return true; } - } - - /// - public override bool SlashedZero { - get { return false; } - } - - /// - public override FontNumeralStyle NumeralStyle { - get { return FontNumeralStyle.Normal; } - } - - /// - public override FontNumeralAlignment NumeralAlignment { - get { return FontNumeralAlignment.Normal; } - } - - /// - public override bool MathematicalGreek { - get { return false; } - } - - /// - public override bool Kerning { - get { return true; } - } - - /// - public override bool HistoricalLigatures { - get { return false; } - } - - /// - public override bool HistoricalForms { - get { return false; } - } - - /// - public override FontFraction Fraction { - get { return FontFraction.Normal; } - } - - /// - public override FontEastAsianWidths EastAsianWidths { - get { return FontEastAsianWidths.Normal; } - } - - /// - public override FontEastAsianLanguage EastAsianLanguage { - get { return FontEastAsianLanguage.Normal; } - } - - /// - public override bool EastAsianExpertForms { - get { return false; } - } - - /// - public override bool DiscretionaryLigatures { - get { return false; } - } - - /// - public override int ContextualSwashes { - get { return 0; } - } - - /// - public override bool ContextualLigatures { - get { return true; } - } - - /// - public override bool ContextualAlternates { - get { return true; } - } - - /// - public override bool CaseSensitiveForms { - get { return false; } - } - - /// - public override bool CapitalSpacing { - get { return false; } - } - - /// - public override FontCapitals Capitals { - get { return FontCapitals.Normal; } - } - - /// - public override int AnnotationAlternates { - get { return 0; } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/DocumentColorizingTransformer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/DocumentColorizingTransformer.cs deleted file mode 100644 index 384df4cd0..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/DocumentColorizingTransformer.cs +++ /dev/null @@ -1,98 +0,0 @@ -// 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 -{ - /// - /// Base class for 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. - /// - public abstract class DocumentColorizingTransformer : ColorizingTransformer - { - DocumentLine currentDocumentLine; - int firstLineStart; - int currentDocumentLineStartOffset, currentDocumentLineEndOffset; - - /// - /// Gets the current ITextRunConstructionContext. - /// - protected ITextRunConstructionContext CurrentContext { get; private set; } - - /// - 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; - } - - /// - /// Override this method to colorize an individual document line. - /// - protected abstract void ColorizeLine(DocumentLine line); - - /// - /// Changes a part of the current document line. - /// - /// Start offset of the region to change - /// End offset of the region to change - /// Action that changes an individual . - protected void ChangeLinePart(int startOffset, int endOffset, Action 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); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/FormattedTextElement.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/FormattedTextElement.cs deleted file mode 100644 index 95e934fe4..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/FormattedTextElement.cs +++ /dev/null @@ -1,222 +0,0 @@ -// 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 -{ - /// - /// 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. - /// - public class FormattedTextElement : VisualLineElement - { - internal readonly FormattedText formattedText; - internal string text; - internal TextLine textLine; - - /// - /// Creates a new FormattedTextElement that displays the specified text - /// and occupies the specified length in the document. - /// - 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; - } - - /// - /// Creates a new FormattedTextElement that displays the specified text - /// and occupies the specified length in the document. - /// - 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; - } - - /// - /// Creates a new FormattedTextElement that displays the specified text - /// and occupies the specified length in the document. - /// - 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; - } - - /// - /// Gets/sets the line break condition before the element. - /// The default is 'BreakPossible'. - /// - public LineBreakCondition BreakBefore { get; set; } - - /// - /// Gets/sets the line break condition after the element. - /// The default is 'BreakPossible'. - /// - public LineBreakCondition BreakAfter { get; set; } - - /// - 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); - } - - /// - /// Constructs a TextLine from a simple text. - /// - 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); - } - } - - /// - /// This is the TextRun implementation used by the class. - /// - public class FormattedTextRun : TextEmbeddedObject - { - readonly FormattedTextElement element; - TextRunProperties properties; - - /// - /// Creates a new FormattedTextRun. - /// - 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; - } - - /// - /// Gets the element for which the FormattedTextRun was created. - /// - public FormattedTextElement Element { - get { return element; } - } - - /// - public override LineBreakCondition BreakBefore { - get { return element.BreakBefore; } - } - - /// - public override LineBreakCondition BreakAfter { - get { return element.BreakAfter; } - } - - /// - public override bool HasFixedSize { - get { return true; } - } - - /// - public override CharacterBufferReference CharacterBufferReference { - get { return new CharacterBufferReference(); } - } - - /// - public override int Length { - get { return element.VisualLength; } - } - - /// - public override TextRunProperties Properties { - get { return properties; } - } - - /// - 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); - } - } - - /// - 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); - } - } - - /// - 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); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/GlobalTextRunProperties.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/GlobalTextRunProperties.cs deleted file mode 100644 index 4bafd452d..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/GlobalTextRunProperties.cs +++ /dev/null @@ -1,43 +0,0 @@ -// 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; } } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/HeightTree.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/HeightTree.cs deleted file mode 100644 index 1bef5b991..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/HeightTree.cs +++ /dev/null @@ -1,1111 +0,0 @@ -// 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 -{ - /// - /// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data. - /// - 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 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) - { - } - - /// - /// Rebuild the tree, in O(n). - /// - 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 - } - - /// - /// build a tree from a list of nodes - /// - 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 nodesToCheckForMerging; - - void BeginRemoval() - { - Debug.Assert(!inRemoval); - if (nodesToCheckForMerging == null) { - nodesToCheckForMerging = new List(); - } - 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); - } - - /// - /// Collapses the specified text section. - /// Runtime: O(log n) - /// - 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 AllNodes { - get { - if (root != null) { - HeightTreeNode node = root.LeftMost; - while (node != null) { - yield return node; - node = node.Successor; - } - } - } - } - - internal IEnumerable GetAllCollapsedSections() - { - List emptyCSList = new List(); - 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)); - } - - /// - /// Checks that all elements in list1 are contained in list2. - /// - static void CheckAllContainedIn(IEnumerable list1, ICollection list2) - { - if (list1 == null) list1 = new List(); - if (list2 == null) list2 = new List(); - 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/HeightTreeLineNode.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/HeightTreeLineNode.cs deleted file mode 100644 index 1e6b6c3ad..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/HeightTreeLineNode.cs +++ /dev/null @@ -1,64 +0,0 @@ -// 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 collapsedSections; - - internal bool IsDirectlyCollapsed { - get { return collapsedSections != null; } - } - - internal void AddDirectlyCollapsed(CollapsedLineSection section) - { - if (collapsedSections == null) - collapsedSections = new List(); - collapsedSections.Add(section); - } - - internal void RemoveDirectlyCollapsed(CollapsedLineSection section) - { - Debug.Assert(collapsedSections.Contains(section)); - collapsedSections.Remove(section); - if (collapsedSections.Count == 0) - collapsedSections = null; - } - - /// - /// Returns 0 if the line is directly collapsed, otherwise, returns . - /// - internal double TotalHeight { - get { - return IsDirectlyCollapsed ? 0 : height; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/HeightTreeNode.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/HeightTreeNode.cs deleted file mode 100644 index c2e5ed2a5..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/HeightTreeNode.cs +++ /dev/null @@ -1,170 +0,0 @@ -// 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 -{ - /// - /// A node in the text view's height tree. - /// - 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; - } - } - - /// - /// Gets the inorder successor of the node. - /// - 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; - } - } - } - - /// - /// The number of lines in this node and its child nodes. - /// Invariant: - /// totalCount = 1 + left.totalCount + right.totalCount - /// - internal int totalCount; - - /// - /// 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 - /// - internal double totalHeight; - - /// - /// 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). - /// - internal List collapsedSections; - - internal bool IsDirectlyCollapsed { - get { - return collapsedSections != null; - } - } - - internal void AddDirectlyCollapsed(CollapsedLineSection section) - { - if (collapsedSections == null) { - collapsedSections = new List(); - 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 list) - { - if (list == null) - return "{}"; - return "{" + - string.Join(",", - list.ConvertAll(cs=>cs.ID).ToArray()) - + "}"; - } - #endif - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/IBackgroundRenderer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/IBackgroundRenderer.cs deleted file mode 100644 index 0c3101785..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/IBackgroundRenderer.cs +++ /dev/null @@ -1,41 +0,0 @@ -// 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 -{ - /// - /// 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. - /// - public interface IBackgroundRenderer - { - /// - /// Gets the layer on which this background renderer should draw. - /// - KnownLayer Layer { get; } - - /// - /// Causes the background renderer to draw. - /// - void Draw(TextView textView, DrawingContext drawingContext); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ITextRunConstructionContext.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ITextRunConstructionContext.cs deleted file mode 100644 index 79e3ab40d..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ITextRunConstructionContext.cs +++ /dev/null @@ -1,62 +0,0 @@ -// 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 -{ - /// - /// Contains information relevant for text run creation. - /// - public interface ITextRunConstructionContext - { - /// - /// Gets the text document. - /// - TextDocument Document { get; } - - /// - /// Gets the text view for which the construction runs. - /// - TextView TextView { get; } - - /// - /// Gets the visual line that is currently being constructed. - /// - VisualLine VisualLine { get; } - - /// - /// Gets the global text run properties. - /// - TextRunProperties GlobalTextRunProperties { get; } - - /// - /// Gets a piece of text from the document. - /// - /// - /// This method is allowed to return a larger string than requested. - /// It does this by returning a 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. - /// - StringSegment GetText(int offset, int length); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ITextViewConnect.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ITextViewConnect.cs deleted file mode 100644 index 86b7810fa..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/ITextViewConnect.cs +++ /dev/null @@ -1,39 +0,0 @@ -// 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 -{ - /// - /// Allows s, s and - /// s to be notified when they are added or removed from a text view. - /// - public interface ITextViewConnect - { - /// - /// Called when added to a text view. - /// - void AddToTextView(TextView textView); - - /// - /// Called when removed from a text view. - /// - void RemoveFromTextView(TextView textView); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/IVisualLineTransformer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/IVisualLineTransformer.cs deleted file mode 100644 index 42a2a2886..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/IVisualLineTransformer.cs +++ /dev/null @@ -1,34 +0,0 @@ -// 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 -{ - /// - /// Allows transforming visual line elements. - /// - public interface IVisualLineTransformer - { - /// - /// Applies the transformation to the specified list of visual line elements. - /// - void Transform(ITextRunConstructionContext context, IList elements); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/InlineObjectRun.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/InlineObjectRun.cs deleted file mode 100644 index 658ecb9c0..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/InlineObjectRun.cs +++ /dev/null @@ -1,160 +0,0 @@ -// 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 -{ - /// - /// A inline UIElement in the document. - /// - public class InlineObjectElement : VisualLineElement - { - /// - /// Gets the inline element that is displayed. - /// - public UIElement Element { get; private set; } - - /// - /// Creates a new InlineObjectElement. - /// - /// The length of the element in the document. Must be non-negative. - /// The element to display. - public InlineObjectElement(int documentLength, UIElement element) - : base(1, documentLength) - { - if (element == null) - throw new ArgumentNullException("element"); - this.Element = element; - } - - /// - public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) - { - if (context == null) - throw new ArgumentNullException("context"); - - return new InlineObjectRun(1, this.TextRunProperties, this.Element); - } - } - - /// - /// A text run with an embedded UIElement. - /// - public class InlineObjectRun : TextEmbeddedObject - { - UIElement element; - int length; - TextRunProperties properties; - internal Size desiredSize; - - /// - /// Creates a new InlineObjectRun instance. - /// - /// The length of the TextRun. - /// The to use. - /// The to display. - 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; - } - - /// - /// Gets the element displayed by the InlineObjectRun. - /// - public UIElement Element { - get { return element; } - } - - /// - /// Gets the VisualLine that contains this object. This property is only available after the object - /// was added to the text view. - /// - public VisualLine VisualLine { get; internal set; } - - /// - public override LineBreakCondition BreakBefore { - get { return LineBreakCondition.BreakDesired; } - } - - /// - public override LineBreakCondition BreakAfter { - get { return LineBreakCondition.BreakDesired; } - } - - /// - public override bool HasFixedSize { - get { return true; } - } - - /// - public override CharacterBufferReference CharacterBufferReference { - get { return new CharacterBufferReference(); } - } - - /// - public override int Length { - get { return length; } - } - - /// - public override TextRunProperties Properties { - get { return properties; } - } - - /// - 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); - } - - /// - 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; - } - } - - /// - public override void Draw(DrawingContext drawingContext, Point origin, bool rightToLeft, bool sideways) - { - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/Layer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/Layer.cs deleted file mode 100644 index 83d14c49f..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/Layer.cs +++ /dev/null @@ -1,58 +0,0 @@ -// 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 -{ - /// - /// Base class for known layers. - /// - 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/LayerPosition.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/LayerPosition.cs deleted file mode 100644 index 4c003d79d..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/LayerPosition.cs +++ /dev/null @@ -1,106 +0,0 @@ -// 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 -{ - /// - /// An enumeration of well-known layers. - /// - public enum KnownLayer - { - /// - /// 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. - /// - /// This layer is below the Selection layer. - Background, - /// - /// This layer contains the selection rectangle. - /// - /// This layer is between the Background and the Text layers. - Selection, - /// - /// This layer contains the text and inline UI elements. - /// - /// This layer is between the Selection and the Caret layers. - Text, - /// - /// This layer contains the blinking caret. - /// - /// This layer is above the Text layer. - Caret - } - - /// - /// Specifies where a new layer is inserted, in relation to an old layer. - /// - public enum LayerInsertionPosition - { - /// - /// The new layer is inserted below the specified layer. - /// - Below, - /// - /// The new layer replaces the specified layer. The old layer is removed - /// from the collection. - /// - Replace, - /// - /// The new layer is inserted above the specified layer. - /// - Above - } - - sealed class LayerPosition : IComparable - { - 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/LinkElementGenerator.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/LinkElementGenerator.cs deleted file mode 100644 index 6573fadd2..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/LinkElementGenerator.cs +++ /dev/null @@ -1,159 +0,0 @@ -// 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. - - /// - /// Detects hyperlinks and makes them clickable. - /// - /// - /// This element generator can be easily enabled and configured using the - /// . - /// - 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; - - /// - /// Gets/Sets whether the user needs to press Control to click the link. - /// The default value is true. - /// - public bool RequireControlModifierForClick { get; set; } - - /// - /// Creates a new LinkElementGenerator. - /// - public LinkElementGenerator() - { - this.linkRegex = defaultLinkRegex; - this.RequireControlModifierForClick = true; - } - - /// - /// Creates a new LinkElementGenerator using the specified regex. - /// - 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; - } - - /// - public override int GetFirstInterestedOffset(int startOffset) - { - int matchOffset; - GetMatch(startOffset, out matchOffset); - return matchOffset; - } - - /// - 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; - } - } - - /// - /// Constructs a VisualLineElement that replaces the matched text. - /// The default implementation will create a - /// based on the URI provided by . - /// - 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; - } - - /// - /// Fetches the URI from the regex match. Returns null if the URI format is invalid. - /// - 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. - - /// - /// Detects e-mail addresses and makes them clickable. - /// - /// - /// This element generator can be easily enabled and configured using the - /// . - /// - sealed class MailLinkElementGenerator : LinkElementGenerator - { - /// - /// Creates a new MailLinkElementGenerator. - /// - public MailLinkElementGenerator() - : base(defaultMailRegex) - { - } - - protected override Uri GetUriFromMatch(Match match) - { - return new Uri("mailto:" + match.Value); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/MouseHoverLogic.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/MouseHoverLogic.cs deleted file mode 100644 index 32d454ec5..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/MouseHoverLogic.cs +++ /dev/null @@ -1,149 +0,0 @@ -// 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 -{ - /// - /// Encapsulates and adds MouseHover support to UIElements. - /// - public class MouseHoverLogic : IDisposable - { - UIElement target; - - DispatcherTimer mouseHoverTimer; - Point mouseHoverStartPoint; - MouseEventArgs mouseHoverLastEventArgs; - bool mouseHovering; - - /// - /// Creates a new instance and attaches itself to the UIElement. - /// - 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); - } - - /// - /// Occurs when the mouse starts hovering over a certain location. - /// - public event EventHandler MouseHover; - - /// - /// Raises the event. - /// - protected virtual void OnMouseHover(MouseEventArgs e) - { - if (MouseHover != null) { - MouseHover(this, e); - } - } - - /// - /// Occurs when the mouse stops hovering over a certain location. - /// - public event EventHandler MouseHoverStopped; - - /// - /// Raises the event. - /// - protected virtual void OnMouseHoverStopped(MouseEventArgs e) - { - if (MouseHoverStopped != null) { - MouseHoverStopped(this, e); - } - } - - bool disposed; - - /// - /// Removes the MouseHover support from the target UIElement. - /// - public void Dispose() - { - if (!disposed) { - this.target.MouseLeave -= MouseHoverLogicMouseLeave; - this.target.MouseMove -= MouseHoverLogicMouseMove; - this.target.MouseEnter -= MouseHoverLogicMouseEnter; - } - disposed = true; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/SimpleTextSource.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/SimpleTextSource.cs deleted file mode 100644 index 486d4485f..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/SimpleTextSource.cs +++ /dev/null @@ -1,54 +0,0 @@ -// 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 GetPrecedingText(int textSourceCharacterIndexLimit) - { - throw new NotImplementedException(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/SingleCharacterElementGenerator.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/SingleCharacterElementGenerator.cs deleted file mode 100644 index 9a565fd8e..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/SingleCharacterElementGenerator.cs +++ /dev/null @@ -1,283 +0,0 @@ -// 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. - - /// - /// Element generator that displays · for spaces and » for tabs and a box for control characters. - /// - /// - /// This element generator is present in every TextView by default; the enabled features can be configured using the - /// . - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] - sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator - { - /// - /// Gets/Sets whether to show · for spaces. - /// - public bool ShowSpaces { get; set; } - - /// - /// Gets/Sets whether to show » for tabs. - /// - public bool ShowTabs { get; set; } - - /// - /// Gets/Sets whether to show a box with the hex code for control characters. - /// - public bool ShowBoxForControlCharacters { get; set; } - - /// - /// Creates a new SingleCharacterElementGenerator instance. - /// - 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; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextLayer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextLayer.cs deleted file mode 100644 index a7843986f..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextLayer.cs +++ /dev/null @@ -1,85 +0,0 @@ -// 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 -{ - /// - /// 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. - /// - /// - /// 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. - /// - sealed class TextLayer : Layer - { - /// - /// the index of the text layer in the layers collection - /// - internal int index; - - public TextLayer(TextView textView) : base(textView, KnownLayer.Text) - { - } - - List visuals = new List(); - - internal void SetVisualLines(ICollection 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextView.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextView.cs deleted file mode 100644 index 550577b58..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextView.cs +++ /dev/null @@ -1,2108 +0,0 @@ -// 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 -{ - /// - /// A virtualizing panel producing+showing s for a . - /// - /// 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. - /// - [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; - - /// - /// Creates a new TextView instance. - /// - public TextView() - { - services.AddService(typeof(TextView), this); - textLayer = new TextLayer(this); - elementGenerators = new ObserveAddRemoveCollection(ElementGenerator_Added, ElementGenerator_Removed); - lineTransformers = new ObserveAddRemoveCollection(LineTransformer_Added, LineTransformer_Removed); - backgroundRenderers = new ObserveAddRemoveCollection(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 - /// - /// Document property. - /// - public static readonly DependencyProperty DocumentProperty = - DependencyProperty.Register("Document", typeof(TextDocument), typeof(TextView), - new FrameworkPropertyMetadata(OnDocumentChanged)); - - TextDocument document; - HeightTree heightTree; - - /// - /// Gets/Sets the document displayed by the text editor. - /// - 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); - } - } - - /// - /// Occurs when the document property has changed. - /// - 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); - } - - /// - /// Recreates the text formatter that is used internally - /// by calling . - /// - void RecreateTextFormatter() - { - if (formatter != null) { - formatter.Dispose(); - formatter = TextFormatterFactory.Create(this); - Redraw(); - } - } - - void RecreateCachedElements() - { - if (cachedElements != null) { - cachedElements.Dispose(); - cachedElements = new TextViewCachedElements(); - } - } - - /// - 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 - /// - /// Options property. - /// - public static readonly DependencyProperty OptionsProperty = - DependencyProperty.Register("Options", typeof(TextEditorOptions), typeof(TextView), - new FrameworkPropertyMetadata(OnOptionsChanged)); - - /// - /// Gets/Sets the options used by the text editor. - /// - public TextEditorOptions Options { - get { return (TextEditorOptions)GetValue(OptionsProperty); } - set { SetValue(OptionsProperty, value); } - } - - /// - /// Occurs when a text editor option has changed. - /// - public event PropertyChangedEventHandler OptionChanged; - - /// - /// Raises the event. - /// - 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 elementGenerators; - - /// - /// Gets a collection where element generators can be registered. - /// - public IList ElementGenerators { - get { return elementGenerators; } - } - - void ElementGenerator_Added(VisualLineElementGenerator generator) - { - ConnectToTextView(generator); - Redraw(); - } - - void ElementGenerator_Removed(VisualLineElementGenerator generator) - { - DisconnectFromTextView(generator); - Redraw(); - } - - readonly ObserveAddRemoveCollection lineTransformers; - - /// - /// Gets a collection where line transformers can be registered. - /// - public IList 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(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; - - /// - /// Gets the list of layers displayed in the text view. - /// - 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); - } - - /// - /// Inserts a new layer at a position specified relative to an existing layer. - /// - /// The new layer to insert. - /// The existing layer - /// Specifies whether the layer is inserted above,below, or replaces the referenced layer - 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); - } - - /// - protected override int VisualChildrenCount { - get { return layers.Count + inlineObjects.Count; } - } - - /// - 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]; - } - - /// - protected override System.Collections.IEnumerator LogicalChildren { - get { - return inlineObjects.Select(io => io.Element).Concat(layers.Cast()).GetEnumerator(); - } - } - #endregion - - #region Inline object handling - List inlineObjects = new List(); - - /// - /// Adds a new inline object. - /// - 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 visualLinesWithOutstandingInlineObjects = new List(); - - 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); - } - } - - /// - /// Remove the inline objects that were marked for removal. - /// - 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 - /// - /// NonPrintableCharacterBrush dependency property. - /// - public static readonly DependencyProperty NonPrintableCharacterBrushProperty = - DependencyProperty.Register("NonPrintableCharacterBrush", typeof(Brush), typeof(TextView), - new FrameworkPropertyMetadata(Brushes.LightGray)); - - /// - /// Gets/sets the Brush used for displaying non-printable characters. - /// - public Brush NonPrintableCharacterBrush { - get { return (Brush)GetValue(NonPrintableCharacterBrushProperty); } - set { SetValue(NonPrintableCharacterBrushProperty, value); } - } - - /// - /// LinkTextForegroundBrush dependency property. - /// - public static readonly DependencyProperty LinkTextForegroundBrushProperty = - DependencyProperty.Register("LinkTextForegroundBrush", typeof(Brush), typeof(TextView), - new FrameworkPropertyMetadata(Brushes.Blue)); - - /// - /// Gets/sets the Brush used for displaying link texts. - /// - public Brush LinkTextForegroundBrush { - get { return (Brush)GetValue(LinkTextForegroundBrushProperty); } - set { SetValue(LinkTextForegroundBrushProperty, value); } - } - - /// - /// LinkTextBackgroundBrush dependency property. - /// - public static readonly DependencyProperty LinkTextBackgroundBrushProperty = - DependencyProperty.Register("LinkTextBackgroundBrush", typeof(Brush), typeof(TextView), - new FrameworkPropertyMetadata(Brushes.Transparent)); - - /// - /// Gets/sets the Brush used for the background of link texts. - /// - public Brush LinkTextBackgroundBrush { - get { return (Brush)GetValue(LinkTextBackgroundBrushProperty); } - set { SetValue(LinkTextBackgroundBrushProperty, value); } - } - #endregion - - /// - /// LinkTextUnderlinedBrush dependency property. - /// - public static readonly DependencyProperty LinkTextUnderlineProperty = - DependencyProperty.Register("LinkTextUnderline", typeof(bool), typeof(TextView), - new FrameworkPropertyMetadata(true)); - - /// - /// Gets/sets whether to underline link texts. - /// - /// - /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. - /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. - /// - public bool LinkTextUnderline - { - get { return (bool)GetValue(LinkTextUnderlineProperty); } - set { SetValue(LinkTextUnderlineProperty, value); } - } - - #region Redraw methods / VisualLine invalidation - /// - /// Causes the text editor to regenerate all visual lines. - /// - public void Redraw() - { - Redraw(DispatcherPriority.Normal); - } - - /// - /// Causes the text editor to regenerate all visual lines. - /// - public void Redraw(DispatcherPriority redrawPriority) - { - VerifyAccess(); - ClearVisualLines(); - InvalidateMeasure(redrawPriority); - } - - /// - /// Causes the text editor to regenerate the specified visual line. - /// - public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority = DispatcherPriority.Normal) - { - VerifyAccess(); - if (allVisualLines.Remove(visualLine)) { - DisposeVisualLine(visualLine); - InvalidateMeasure(redrawPriority); - } - } - - /// - /// Causes the text editor to redraw all lines overlapping with the specified segment. - /// - 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); - } - } - - /// - /// Causes a known layer to redraw. - /// This method does not invalidate visual lines; - /// use the method to do that. - /// - [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); - } - - /// - /// Causes a known layer to redraw. - /// This method does not invalidate visual lines; - /// use the method to do that. - /// - [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); - } - - /// - /// Causes the text editor to redraw all lines overlapping with the specified segment. - /// Does nothing if segment is null. - /// - public void Redraw(ISegment segment, DispatcherPriority redrawPriority = DispatcherPriority.Normal) - { - if (segment != null) { - Redraw(segment.Offset, segment.Length, redrawPriority); - } - } - - /// - /// Invalidates all visual lines. - /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure - /// that the visual lines will be recreated. - /// - 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 - /// - /// Gets the visual line that contains the document line with the specified number. - /// Returns null if the document line is outside the visible range. - /// - 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; - } - - /// - /// 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. - /// - 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 allVisualLines = new List(); - ReadOnlyCollection visibleVisualLines; - double clippedPixelsOnTop; - List newVisualLines; - - /// - /// Gets the currently visible visual lines. - /// - /// - /// Gets thrown if there are invalid visual lines when this property is accessed. - /// You can use the property to check for this case, - /// or use the method to force creating the visual lines - /// when they are invalid. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] - public ReadOnlyCollection VisualLines { - get { - if (visibleVisualLines == null) - throw new VisualLinesInvalidException(); - return visibleVisualLines; - } - } - - /// - /// Gets whether the visual lines are valid. - /// Will return false after a call to Redraw(). - /// Accessing the visual lines property will cause a - /// if this property is false. - /// - public bool VisualLinesValid { - get { return visibleVisualLines != null; } - } - - /// - /// 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. - /// - public event EventHandler VisualLineConstructionStarting; - - /// - /// Occurs when the TextView was measured and changed its visual lines. - /// - public event EventHandler VisualLinesChanged; - - /// - /// 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. - /// - /// The visual line build process is already running. - /// It is not allowed to call this method during the construction of a visual line. - 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 - /// - /// 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. - /// - const double AdditionalHorizontalScrollAmount = 3; - - Size lastAvailableSize; - bool inMeasure; - - /// - 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(); - 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)) { - // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after - // scrolling to the very bottom. - double minVisibleDocumentHeight = Math.Max(DefaultLineHeight, Editing.Caret.MinimumDistanceToViewBorder); - // scrollViewportBottom: bottom of scroll view port, but clamped so that at least minVisibleDocumentHeight of the document stays visible. - double scrollViewportBottom = Math.Min(heightTreeHeight - minVisibleDocumentHeight, scrollOffset.Y) + scrollViewport.Height; - // increase the extend height to allow scrolling below the document - heightTreeHeight = Math.Max(heightTreeHeight, scrollViewportBottom); - } - } - - 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)); - } - - /// - /// Build all VisualLines in the visible range. - /// - /// Width the longest line - 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(); - - 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(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(); - 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 - /// - /// Arrange implementation. - /// - 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 backgroundRenderers; - - /// - /// Gets the list of background renderers. - /// - public IList BackgroundRenderers { - get { return backgroundRenderers; } - } - - void BackgroundRenderer_Added(IBackgroundRenderer renderer) - { - ConnectToTextView(renderer); - InvalidateLayer(renderer.Layer); - } - - void BackgroundRenderer_Removed(IBackgroundRenderer renderer) - { - DisconnectFromTextView(renderer); - InvalidateLayer(renderer.Layer); - } - - /// - 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 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 - /// - /// Size of the document, in pixels. - /// - Size scrollExtent; - - /// - /// Offset of the scroll position. - /// - Vector scrollOffset; - - /// - /// Size of the viewport. - /// - 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; } - } - - /// - /// Gets the horizontal scroll offset. - /// - public double HorizontalOffset { - get { return scrollOffset.X; } - } - - /// - /// Gets the vertical scroll offset. - /// - public double VerticalOffset { - get { return scrollOffset.Y; } - } - - /// - /// Gets the scroll offset; - /// - public Vector ScrollOffset { - get { return scrollOffset; } - } - - /// - /// Occurs when the scroll offset has changed. - /// - 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. - - /// - /// Gets the width of a 'wide space' (the space width used for calculating the tab size). - /// - /// - /// 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. - /// - public double WideSpaceWidth { - get { - CalculateDefaultTextMetrics(); - return wideSpaceWidth; - } - } - - /// - /// 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. - /// - public double DefaultLineHeight { - get { - CalculateDefaultTextMetrics(); - return defaultLineHeight; - } - } - - /// - /// Gets the default baseline position. This is the difference between - /// and for a line containing regular text. - /// Lines that include formatted text or custom UI elements may have a different baseline. - /// - 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; - } - - /// - /// Scrolls the text view so that the specified rectangle gets visible. - /// - 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 - /// - 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; - - /// - /// Updates the mouse cursor by calling , but with background priority. - /// - 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(); - } - - /// - protected override void OnQueryCursor(QueryCursorEventArgs e) - { - VisualLineElement element = GetVisualLineElementFromPosition(e.GetPosition(this) + scrollOffset); - if (element != null) { - element.OnQueryCursor(e); - } - } - - /// - 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); - } - } - } - - /// - 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 - /// - /// 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). - /// - 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; - } - - /// - /// Gets the visual top position (relative to start of document) from a document line number. - /// - 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 - /// - /// Gets the visual position from a text view position. - /// - /// The text view position. - /// The mode how to retrieve the Y position. - /// The position in WPF device-independent pixels relative - /// to the top left corner of the document. - 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); - } - - /// - /// 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. - /// - /// The position in WPF device-independent pixels relative - /// to the top left corner of the document. - /// The logical position, or null if the position is outside the document. - 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); - } - - /// - /// 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. - /// - /// The position in WPF device-independent pixels relative - /// to the top left corner of the document. - /// The logical position, or null if the position is outside the document. - 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(); - - /// - /// Gets a service container used to associate services with the text view. - /// - /// - /// This container does not provide document services - - /// use TextView.GetService() instead of TextView.Services.GetService() to ensure - /// that document services can be found as well. - /// - public ServiceContainer Services { - get { return services; } - } - - /// - /// Retrieves a service from the text view. - /// If the service is not found in the container, - /// this method will also look for it in the current document's service provider. - /// - 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 - /// - /// The PreviewMouseHover event. - /// - public static readonly RoutedEvent PreviewMouseHoverEvent = - EventManager.RegisterRoutedEvent("PreviewMouseHover", RoutingStrategy.Tunnel, - typeof(MouseEventHandler), typeof(TextView)); - /// - /// The MouseHover event. - /// - public static readonly RoutedEvent MouseHoverEvent = - EventManager.RegisterRoutedEvent("MouseHover", RoutingStrategy.Bubble, - typeof(MouseEventHandler), typeof(TextView)); - - /// - /// The PreviewMouseHoverStopped event. - /// - public static readonly RoutedEvent PreviewMouseHoverStoppedEvent = - EventManager.RegisterRoutedEvent("PreviewMouseHoverStopped", RoutingStrategy.Tunnel, - typeof(MouseEventHandler), typeof(TextView)); - /// - /// The MouseHoverStopped event. - /// - public static readonly RoutedEvent MouseHoverStoppedEvent = - EventManager.RegisterRoutedEvent("MouseHoverStopped", RoutingStrategy.Bubble, - typeof(MouseEventHandler), typeof(TextView)); - - - /// - /// Occurs when the mouse has hovered over a fixed location for some time. - /// - public event MouseEventHandler PreviewMouseHover { - add { AddHandler(PreviewMouseHoverEvent, value); } - remove { RemoveHandler(PreviewMouseHoverEvent, value); } - } - - /// - /// Occurs when the mouse has hovered over a fixed location for some time. - /// - public event MouseEventHandler MouseHover { - add { AddHandler(MouseHoverEvent, value); } - remove { RemoveHandler(MouseHoverEvent, value); } - } - - /// - /// Occurs when the mouse had previously hovered but now started moving again. - /// - public event MouseEventHandler PreviewMouseHoverStopped { - add { AddHandler(PreviewMouseHoverStoppedEvent, value); } - remove { RemoveHandler(PreviewMouseHoverStoppedEvent, value); } - } - - /// - /// Occurs when the mouse had previously hovered but now started moving again. - /// - 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 - - /// - /// Collapses lines for the purpose of scrolling. s marked as collapsed will be hidden - /// and not used to start the generation of a . - /// - /// - /// This method is meant for s that cause s to span - /// multiple s. Do not call it without providing a corresponding - /// . - /// If you want to create collapsible text sections, see . - /// - /// 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 on the - /// returned from this method. - /// - public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) - { - VerifyAccess(); - if (heightTree == null) - throw ThrowUtil.NoDocumentAssigned(); - return heightTree.CollapseText(start, end); - } - - /// - /// Gets the height of the document. - /// - public double DocumentHeight { - get { - // return 0 if there is no document = no heightTree - return heightTree != null ? heightTree.TotalHeight : 0; - } - } - - /// - /// Gets the document line at the specified visual position. - /// - public DocumentLine GetDocumentLineByVisualTop(double visualTop) - { - VerifyAccess(); - if (heightTree == null) - throw ThrowUtil.NoDocumentAssigned(); - return heightTree.GetLineByVisualPosition(visualTop); - } - - /// - 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 - || e.Property == TextView.LinkTextUnderlineProperty) - { - // 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; - } - } - - /// - /// The pen used to draw the column ruler. - /// - /// - 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; - } - - /// - /// Gets/Sets the pen used to draw the column ruler. - /// - /// - public Pen ColumnRulerPen { - get { return (Pen)GetValue(ColumnRulerPenProperty); } - set { SetValue(ColumnRulerPenProperty, value); } - } - - /// - /// The property. - /// - public static readonly DependencyProperty CurrentLineBackgroundProperty = - DependencyProperty.Register("CurrentLineBackground", typeof(Brush), typeof(TextView)); - - /// - /// Gets/Sets the background brush used by current line highlighter. - /// - public Brush CurrentLineBackground { - get { return (Brush)GetValue(CurrentLineBackgroundProperty); } - set { SetValue(CurrentLineBackgroundProperty, value); } - } - - /// - /// The property. - /// - public static readonly DependencyProperty CurrentLineBorderProperty = - DependencyProperty.Register("CurrentLineBorder", typeof(Pen), typeof(TextView)); - - /// - /// Gets/Sets the background brush used for the current line. - /// - public Pen CurrentLineBorder { - get { return (Pen)GetValue(CurrentLineBorderProperty); } - set { SetValue(CurrentLineBorderProperty, value); } - } - - /// - /// Gets/Sets highlighted line number. - /// - public int HighlightedLine { - get { return this.currentLineHighlighRenderer.Line; } - set { this.currentLineHighlighRenderer.Line = value; } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextViewCachedElements.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextViewCachedElements.cs deleted file mode 100644 index 24ff9d46c..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextViewCachedElements.cs +++ /dev/null @@ -1,58 +0,0 @@ -// 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 nonPrintableCharacterTexts; - - public TextLine GetTextForNonPrintableCharacter(string text, ITextRunConstructionContext context) - { - if (nonPrintableCharacterTexts == null) - nonPrintableCharacterTexts = new Dictionary(); - 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(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextViewWeakEventManager.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextViewWeakEventManager.cs deleted file mode 100644 index 65f2fafd0..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/TextViewWeakEventManager.cs +++ /dev/null @@ -1,86 +0,0 @@ -// 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 -{ - /// - /// Contains weak event managers for the TextView events. - /// - public static class TextViewWeakEventManager - { - /// - /// Weak event manager for the event. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public sealed class DocumentChanged : WeakEventManagerBase - { - /// - protected override void StartListening(TextView source) - { - source.DocumentChanged += DeliverEvent; - } - - /// - protected override void StopListening(TextView source) - { - source.DocumentChanged -= DeliverEvent; - } - } - - /// - /// Weak event manager for the event. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public sealed class VisualLinesChanged : WeakEventManagerBase - { - /// - protected override void StartListening(TextView source) - { - source.VisualLinesChanged += DeliverEvent; - } - - /// - protected override void StopListening(TextView source) - { - source.VisualLinesChanged -= DeliverEvent; - } - } - - /// - /// Weak event manager for the event. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public sealed class ScrollOffsetChanged : WeakEventManagerBase - { - /// - protected override void StartListening(TextView source) - { - source.ScrollOffsetChanged += DeliverEvent; - } - - /// - protected override void StopListening(TextView source) - { - source.ScrollOffsetChanged -= DeliverEvent; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLine.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLine.cs deleted file mode 100644 index 150ca2a7b..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLine.cs +++ /dev/null @@ -1,772 +0,0 @@ -// 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 -{ - /// - /// 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. - /// - public sealed class VisualLine - { - enum LifetimePhase : byte - { - Generating, - Transforming, - Live, - Disposed - } - - TextView textView; - List elements; - internal bool hasInlineObjects; - LifetimePhase phase; - - /// - /// Gets the document to which this VisualLine belongs. - /// - public TextDocument Document { get; private set; } - - /// - /// Gets the first document line displayed by this visual line. - /// - public DocumentLine FirstDocumentLine { get; private set; } - - /// - /// Gets the last document line displayed by this visual line. - /// - public DocumentLine LastDocumentLine { get; private set; } - - /// - /// Gets a read-only collection of line elements. - /// - public ReadOnlyCollection Elements { get; private set; } - - ReadOnlyCollection textLines; - - /// - /// Gets a read-only collection of text lines. - /// - public ReadOnlyCollection TextLines { - get { - if (phase < LifetimePhase.Live) - throw new InvalidOperationException(); - return textLines; - } - } - - /// - /// Gets the start offset of the VisualLine inside the document. - /// This is equivalent to FirstDocumentLine.Offset. - /// - public int StartOffset { - get { - return FirstDocumentLine.Offset; - } - } - - /// - /// Length in visual line coordinates. - /// - public int VisualLength { get; private set; } - - /// - /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. - /// - public int VisualLengthWithEndOfLineMarker { - get { - int length = VisualLength; - if (textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; - return length; - } - } - - /// - /// Gets the height of the visual line in device-independent pixels. - /// - public double Height { get; private set; } - - /// - /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. - /// - 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(); - 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; - } - - /// - /// Replaces the single element at with the specified elements. - /// The replacement operation must preserve the document length, but may change the visual length. - /// - /// - /// This method may only be called by line transformers. - /// - public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) - { - ReplaceElement(elementIndex, 1, newElements); - } - - /// - /// Replaces elements starting at with the specified elements. - /// The replacement operation must preserve the document length, but may change the visual length. - /// - /// - /// This method may only be called by line transformers. - /// - 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 textLines) - { - this.textLines = textLines.AsReadOnly(); - Height = 0; - foreach (TextLine line in textLines) - Height += line.Height; - } - - /// - /// Gets the visual column from a document offset relative to the first line start. - /// - 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; - } - - /// - /// Gets the document offset (relative to the first line start) from a visual column. - /// - 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; - } - - /// - /// Gets the text line containing the specified visual column. - /// - public TextLine GetTextLine(int visualColumn) - { - return GetTextLine(visualColumn, false); - } - - /// - /// Gets the text line containing the specified visual column. - /// - 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?)"); - } - - /// - /// Gets the visual top from the specified text line. - /// - /// Distance in device-independent pixels - /// from the top of the document to the top of the specified text line. - 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"); - } - - /// - /// Gets the start visual column from the specified text line. - /// - 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; - } - - /// - /// Gets a TextLine by the visual position. - /// - 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]; - } - - /// - /// Gets the visual position from the specified visualColumn. - /// - /// Position in device-independent pixels - /// relative to the top left of the document. - 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); - } - - /// - /// 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. - /// - 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; - } - - /// - /// 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. - /// - public int GetVisualColumn(Point point) - { - return GetVisualColumn(point, textView.Options.EnableVirtualSpace); - } - - /// - /// 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. - /// - 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; - } - - /// - /// 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. - /// - 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; - } - - /// - /// Validates the visual column and returns the correct one. - /// - public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) - { - return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); - } - - /// - /// Validates the visual column and returns the correct one. - /// - 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; - } - - /// - /// 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. - /// - public int GetVisualColumnFloor(Point point) - { - return GetVisualColumnFloor(point, textView.Options.EnableVirtualSpace); - } - - /// - /// 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. - /// - 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; - } - - /// - /// Gets the text view position from the specified visual column. - /// - public TextViewPosition GetTextViewPosition(int visualColumn) - { - int documentOffset = GetRelativeOffset(visualColumn) + this.FirstDocumentLine.Offset; - return new TextViewPosition(this.Document.GetLocation(documentOffset), visualColumn); - } - - /// - /// 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. - /// - /// The position in WPF device-independent pixels relative - /// to the top left corner of the document. - /// Controls whether positions in virtual space may be returned. - 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; - } - - /// - /// 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. - /// - /// The position in WPF device-independent pixels relative - /// to the top left corner of the document. - /// Controls whether positions in virtual space may be returned. - 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; - } - - /// - /// Gets whether the visual line was disposed. - /// - 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(); - } - } - - /// - /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. - /// - 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineConstructionStartEventArgs.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineConstructionStartEventArgs.cs deleted file mode 100644 index 2278379eb..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineConstructionStartEventArgs.cs +++ /dev/null @@ -1,44 +0,0 @@ -// 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 -{ - /// - /// EventArgs for the event. - /// - public class VisualLineConstructionStartEventArgs : EventArgs - { - /// - /// Gets/Sets the first line that is visible in the TextView. - /// - public DocumentLine FirstLineInView { get; private set; } - - /// - /// Creates a new VisualLineConstructionStartEventArgs instance. - /// - public VisualLineConstructionStartEventArgs(DocumentLine firstLineInView) - { - if (firstLineInView == null) - throw new ArgumentNullException("firstLineInView"); - this.FirstLineInView = firstLineInView; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineElement.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineElement.cs deleted file mode 100644 index ddf341d5a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineElement.cs +++ /dev/null @@ -1,264 +0,0 @@ -// 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 -{ - /// - /// Represents a visual element in the document. - /// - public abstract class VisualLineElement - { - /// - /// Creates a new VisualLineElement. - /// - /// The length of the element in VisualLine coordinates. Must be positive. - /// The length of the element in the document. Must be non-negative. - 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; - } - - /// - /// Gets the length of this element in visual columns. - /// - public int VisualLength { get; private set; } - - /// - /// Gets the length of this element in the text document. - /// - public int DocumentLength { get; private set; } - - /// - /// Gets the visual column where this element starts. - /// - [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; } - - /// - /// Gets the text offset where this element starts, relative to the start text offset of the visual line. - /// - public int RelativeTextOffset { get; internal set; } - - /// - /// Gets the text run properties. - /// A unique instance is used for each - /// ; colorizing code may assume that modifying the - /// will affect only this - /// . - /// - public VisualLineElementTextRunProperties TextRunProperties { get; private set; } - - /// - /// Gets/sets the brush used for the background of this . - /// - public Brush BackgroundBrush { get; set; } - - internal void SetTextRunProperties(VisualLineElementTextRunProperties p) - { - this.TextRunProperties = p; - } - - /// - /// Creates the TextRun for this line element. - /// - /// - /// The visual column from which the run should be constructed. - /// Normally the same value as the property is used to construct the full run; - /// but when word-wrapping is active, partial runs might be created. - /// - /// - /// Context object that contains information relevant for text run creation. - /// - public abstract TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context); - - /// - /// Retrieves the text span immediately before the visual column. - /// - /// This method is used for word-wrapping in bidirectional text. - public virtual TextSpan GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) - { - return null; - } - - /// - /// Gets if this VisualLineElement can be split. - /// - public virtual bool CanSplit { - get { return false; } - } - - /// - /// Splits the element. - /// - /// Position inside this element at which it should be broken - /// The collection of line elements - /// The index at which this element is in the elements list. - public virtual void Split(int splitVisualColumn, IList elements, int elementIndex) - { - throw new NotSupportedException(); - } - - /// - /// Helper method for splitting this line element into two, correctly updating the - /// , , - /// and properties. - /// - /// The element before the split position. - /// The element after the split position. - /// The split position as visual column. - /// The split position as text offset. - 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(); - } - - /// - /// Gets the visual column of a text location inside this element. - /// The text offset is given relative to the visual line start. - /// - public virtual int GetVisualColumn(int relativeTextOffset) - { - if (relativeTextOffset >= this.RelativeTextOffset + DocumentLength) - return VisualColumn + VisualLength; - else - return VisualColumn; - } - - /// - /// Gets the text offset of a visual column inside this element. - /// - /// A text offset relative to the visual line start. - public virtual int GetRelativeOffset(int visualColumn) - { - if (visualColumn >= this.VisualColumn + VisualLength) - return RelativeTextOffset + DocumentLength; - else - return RelativeTextOffset; - } - - /// - /// Gets the next caret position inside this element. - /// - /// The visual column from which the search should be started. - /// The search direction (forwards or backwards). - /// Whether to stop only at word borders. - /// The visual column of the next caret position, or -1 if there is no next caret position. - /// - /// 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. - /// - 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; - } - - /// - /// Gets whether the specified offset in this element is considered whitespace. - /// - public virtual bool IsWhitespace(int visualColumn) - { - return false; - } - - /// - /// Gets whether the 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 - /// . - /// - public virtual bool HandlesLineBorders { - get { return false; } - } - - /// - /// Queries the cursor over the visual line element. - /// - protected internal virtual void OnQueryCursor(QueryCursorEventArgs e) - { - } - - /// - /// Allows the visual line element to handle a mouse event. - /// - protected internal virtual void OnMouseDown(MouseButtonEventArgs e) - { - } - - /// - /// Allows the visual line element to handle a mouse event. - /// - protected internal virtual void OnMouseUp(MouseButtonEventArgs e) - { - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineElementGenerator.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineElementGenerator.cs deleted file mode 100644 index e8f40ff15..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineElementGenerator.cs +++ /dev/null @@ -1,78 +0,0 @@ -// 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 -{ - /// - /// Abstract base class for generators that produce new visual line elements. - /// - public abstract class VisualLineElementGenerator - { - /// - /// Gets the text run construction context. - /// - protected ITextRunConstructionContext CurrentContext { get; private set; } - - /// - /// Initializes the generator for the - /// - public virtual void StartGeneration(ITextRunConstructionContext context) - { - if (context == null) - throw new ArgumentNullException("context"); - this.CurrentContext = context; - } - - /// - /// De-initializes the generator. - /// - public virtual void FinishGeneration() - { - this.CurrentContext = null; - } - - /// - /// Should only be used by VisualLine.ConstructVisualElements. - /// - internal int cachedInterest; - - /// - /// Gets the first offset >= startOffset where the generator wants to construct an element. - /// Return -1 to signal no interest. - /// - public abstract int GetFirstInterestedOffset(int startOffset); - - /// - /// Constructs an element at the specified offset. - /// May return null if no element should be constructed. - /// - /// - /// Avoid signalling interest and then building no element by returning null - doing so - /// causes the generated elements to be unnecessarily split - /// at the position where you signalled interest. - /// - public abstract VisualLineElement ConstructElement(int offset); - } - - internal interface IBuiltinElementGenerator - { - void FetchOptions(TextEditorOptions options); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineElementTextRunProperties.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineElementTextRunProperties.cs deleted file mode 100644 index 47a1d8d52..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineElementTextRunProperties.cs +++ /dev/null @@ -1,256 +0,0 @@ -// 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 -{ - /// - /// implementation that allows changing the properties. - /// A instance usually is assigned to a single - /// . - /// - 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; - - /// - /// Creates a new VisualLineElementTextRunProperties instance that copies its values - /// from the specified . - /// For the and collections, deep copies - /// are created if those collections are not frozen. - /// - 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; - } - - /// - /// Creates a copy of this instance. - /// - public virtual VisualLineElementTextRunProperties Clone() - { - return new VisualLineElementTextRunProperties(this); - } - - object ICloneable.Clone() - { - return Clone(); - } - - /// - public override Brush BackgroundBrush { - get { return backgroundBrush; } - } - - /// - /// Sets the . - /// - public void SetBackgroundBrush(Brush value) - { - ExtensionMethods.CheckIsFrozen(value); - backgroundBrush = value; - } - - /// - public override BaselineAlignment BaselineAlignment { - get { return baselineAlignment; } - } - - /// - /// Sets the . - /// - public void SetBaselineAlignment(BaselineAlignment value) - { - baselineAlignment = value; - } - - /// - public override CultureInfo CultureInfo { - get { return cultureInfo; } - } - - /// - /// Sets the . - /// - public void SetCultureInfo(CultureInfo value) - { - if (value == null) - throw new ArgumentNullException("value"); - cultureInfo = value; - } - - /// - public override double FontHintingEmSize { - get { return fontHintingEmSize; } - } - - /// - /// Sets the . - /// - public void SetFontHintingEmSize(double value) - { - fontHintingEmSize = value; - } - - /// - public override double FontRenderingEmSize { - get { return fontRenderingEmSize; } - } - - /// - /// Sets the . - /// - public void SetFontRenderingEmSize(double value) - { - fontRenderingEmSize = value; - } - - /// - public override Brush ForegroundBrush { - get { return foregroundBrush; } - } - - /// - /// Sets the . - /// - public void SetForegroundBrush(Brush value) - { - ExtensionMethods.CheckIsFrozen(value); - foregroundBrush = value; - } - - /// - public override Typeface Typeface { - get { return typeface; } - } - - /// - /// Sets the . - /// - public void SetTypeface(Typeface value) - { - if (value == null) - throw new ArgumentNullException("value"); - typeface = value; - } - - /// - /// Gets the text decorations. The value may be null, a frozen - /// or an unfrozen . - /// If the value is an unfrozen , you may assume that the - /// collection instance is only used for this instance and it is safe - /// to add s. - /// - public override TextDecorationCollection TextDecorations { - get { return textDecorations; } - } - - /// - /// Sets the . - /// - public void SetTextDecorations(TextDecorationCollection value) - { - ExtensionMethods.CheckIsFrozen(value); - textDecorations = value; - } - - /// - /// Gets the text effects. The value may be null, a frozen - /// or an unfrozen . - /// If the value is an unfrozen , you may assume that the - /// collection instance is only used for this instance and it is safe - /// to add s. - /// - public override TextEffectCollection TextEffects { - get { return textEffects; } - } - - /// - /// Sets the . - /// - public void SetTextEffects(TextEffectCollection value) - { - ExtensionMethods.CheckIsFrozen(value); - textEffects = value; - } - - /// - /// Gets the typography properties for the text run. - /// - public override TextRunTypographyProperties TypographyProperties { - get { return typographyProperties; } - } - - /// - /// Sets the . - /// - public void SetTypographyProperties(TextRunTypographyProperties value) - { - typographyProperties = value; - } - - /// - /// Gets the number substitution settings for the text run. - /// - public override NumberSubstitution NumberSubstitution { - get { return numberSubstitution; } - } - - /// - /// Sets the . - /// - public void SetNumberSubstitution(NumberSubstitution value) - { - numberSubstitution = value; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineLinkText.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineLinkText.cs deleted file mode 100644 index bf895ce9a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineLinkText.cs +++ /dev/null @@ -1,130 +0,0 @@ -// 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 -{ - /// - /// VisualLineElement that represents a piece of text and is a clickable link. - /// - public class VisualLineLinkText : VisualLineText - { - /// - /// Gets/Sets the URL that is navigated to when the link is clicked. - /// - public Uri NavigateUri { get; set; } - - /// - /// Gets/Sets the window name where the URL will be opened. - /// - public string TargetName { get; set; } - - /// - /// Gets/Sets whether the user needs to press Control to click the link. - /// The default value is true. - /// - public bool RequireControlModifierForClick { get; set; } - - /// - /// Creates a visual line text element with the specified length. - /// It uses the and its - /// to find the actual text string. - /// - public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length) - { - this.RequireControlModifierForClick = true; - } - - /// - public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) - { - this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush); - this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush); - if (context.TextView.LinkTextUnderline) - this.TextRunProperties.SetTextDecorations(TextDecorations.Underline); - return base.CreateTextRun(startVisualColumn, context); - } - - /// - /// Gets whether the link is currently clickable. - /// - /// Returns true when control is pressed; or when - /// is disabled. - protected bool LinkIsClickable() - { - if (NavigateUri == null) - return false; - if (RequireControlModifierForClick) - return (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control; - else - return true; - } - - /// - protected internal override void OnQueryCursor(QueryCursorEventArgs e) - { - if (LinkIsClickable()) { - e.Handled = true; - e.Cursor = Cursors.Hand; - } - } - - /// - [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; - } - } - - /// - protected override VisualLineText CreateInstance(int length) - { - return new VisualLineLinkText(ParentVisualLine, length) { - NavigateUri = this.NavigateUri, - TargetName = this.TargetName, - RequireControlModifierForClick = this.RequireControlModifierForClick - }; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineText.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineText.cs deleted file mode 100644 index 9d9cf48e3..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineText.cs +++ /dev/null @@ -1,137 +0,0 @@ -// 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 -{ - /// - /// VisualLineElement that represents a piece of text. - /// - public class VisualLineText : VisualLineElement - { - VisualLine parentVisualLine; - - /// - /// Gets the parent visual line. - /// - public VisualLine ParentVisualLine { - get { return parentVisualLine; } - } - - /// - /// Creates a visual line text element with the specified length. - /// It uses the and its - /// to find the actual text string. - /// - public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) - { - if (parentVisualLine == null) - throw new ArgumentNullException("parentVisualLine"); - this.parentVisualLine = parentVisualLine; - } - - /// - /// Override this method to control the type of new VisualLineText instances when - /// the visual line is split due to syntax highlighting. - /// - protected virtual VisualLineText CreateInstance(int length) - { - return new VisualLineText(parentVisualLine, length); - } - - /// - 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); - } - - /// - public override bool IsWhitespace(int visualColumn) - { - int offset = visualColumn - this.VisualColumn + parentVisualLine.FirstDocumentLine.Offset + this.RelativeTextOffset; - return char.IsWhiteSpace(parentVisualLine.Document.GetCharAt(offset)); - } - - /// - public override TextSpan 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(range.Length, new CultureSpecificCharacterBufferRange(this.TextRunProperties.CultureInfo, range)); - } - - /// - public override bool CanSplit { - get { return true; } - } - - /// - public override void Split(int splitVisualColumn, IList 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); - } - - /// - public override int GetRelativeOffset(int visualColumn) - { - return this.RelativeTextOffset + visualColumn - this.VisualColumn; - } - - /// - public override int GetVisualColumn(int relativeTextOffset) - { - return this.VisualColumn + relativeTextOffset - this.RelativeTextOffset; - } - - /// - 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineTextParagraphProperties.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineTextParagraphProperties.cs deleted file mode 100644 index 89242a668..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineTextParagraphProperties.cs +++ /dev/null @@ -1,46 +0,0 @@ -// 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; } } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineTextSource.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineTextSource.cs deleted file mode 100644 index d8cd12ea9..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLineTextSource.cs +++ /dev/null @@ -1,138 +0,0 @@ -// 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 -{ - /// - /// WPF TextSource implementation that creates TextRuns for a VisualLine. - /// - 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 GetPrecedingText(int textSourceCharacterIndexLimit) - { - try { - foreach (VisualLineElement element in VisualLine.Elements) { - if (textSourceCharacterIndexLimit > element.VisualColumn - && textSourceCharacterIndexLimit <= element.VisualColumn + element.VisualLength) - { - TextSpan 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(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)); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLinesInvalidException.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLinesInvalidException.cs deleted file mode 100644 index 1e7bcdac2..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualLinesInvalidException.cs +++ /dev/null @@ -1,59 +0,0 @@ -// 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 -{ - /// - /// A VisualLinesInvalidException indicates that you accessed the property - /// of the while the visual lines were invalid. - /// - [Serializable] - public class VisualLinesInvalidException : Exception - { - /// - /// Creates a new VisualLinesInvalidException instance. - /// - public VisualLinesInvalidException() : base() - { - } - - /// - /// Creates a new VisualLinesInvalidException instance. - /// - public VisualLinesInvalidException(string message) : base(message) - { - } - - /// - /// Creates a new VisualLinesInvalidException instance. - /// - public VisualLinesInvalidException(string message, Exception innerException) : base(message, innerException) - { - } - - /// - /// Creates a new VisualLinesInvalidException instance. - /// - protected VisualLinesInvalidException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualYPosition.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualYPosition.cs deleted file mode 100644 index 292d94dda..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Rendering/VisualYPosition.cs +++ /dev/null @@ -1,61 +0,0 @@ -// 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 -{ - /// - /// An enum that specifies the possible Y positions that can be returned by VisualLine.GetVisualPosition. - /// - public enum VisualYPosition - { - /// - /// Returns the top of the TextLine. - /// - LineTop, - /// - /// 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. - /// - TextTop, - /// - /// Returns the bottom of the TextLine. - /// - LineBottom, - /// - /// The middle between LineTop and LineBottom. - /// - LineMiddle, - /// - /// 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. - /// - TextBottom, - /// - /// The middle between TextTop and TextBottom. - /// - TextMiddle, - /// - /// Returns the baseline of the text. - /// - Baseline - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Search/DropDownButton.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Search/DropDownButton.cs deleted file mode 100644 index 31cb5f996..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Search/DropDownButton.cs +++ /dev/null @@ -1,89 +0,0 @@ -// 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 -{ - /// - /// A button that opens a drop-down menu when clicked. - /// - public class DropDownButton : ButtonBase - { - /// - /// Identifies the  dependency property. - /// - public static readonly DependencyProperty DropDownContentProperty - = DependencyProperty.Register("DropDownContent", typeof(Popup), - typeof(DropDownButton), new FrameworkPropertyMetadata(null)); - - /// - /// The key that identifies the  dependency property. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] - protected static readonly DependencyPropertyKey IsDropDownContentOpenPropertyKey - = DependencyProperty.RegisterReadOnly("IsDropDownContentOpen", typeof(bool), - typeof(DropDownButton), new FrameworkPropertyMetadata(false)); - - /// - /// Identifies the  dependency property. - /// - public static readonly DependencyProperty IsDropDownContentOpenProperty = IsDropDownContentOpenPropertyKey.DependencyProperty; - - static DropDownButton() - { - DefaultStyleKeyProperty.OverrideMetadata(typeof(DropDownButton), new FrameworkPropertyMetadata(typeof(DropDownButton))); - } - - /// - /// Gets/Sets the popup that is used as drop-down content. - /// - public Popup DropDownContent { - get { return (Popup)GetValue(DropDownContentProperty); } - set { SetValue(DropDownContentProperty, value); } - } - - /// - /// Gets whether the drop-down is opened. - /// - public bool IsDropDownContentOpen { - get { return (bool)GetValue(IsDropDownContentOpenProperty); } - protected set { SetValue(IsDropDownContentOpenPropertyKey, value); } - } - - /// - 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Search/DropDownButton.xaml b/AvalonEdit/ICSharpCode.AvalonEdit/Search/DropDownButton.xaml deleted file mode 100644 index 597f2fba4..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Search/DropDownButton.xaml +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Search/ISearchStrategy.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Search/ISearchStrategy.cs deleted file mode 100644 index 9121a454a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Search/ISearchStrategy.cs +++ /dev/null @@ -1,103 +0,0 @@ -// 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 -{ - /// - /// Basic interface for search algorithms. - /// - public interface ISearchStrategy : IEquatable - { - /// - /// Finds all matches in the given ITextSource and the given range. - /// - /// - /// 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). - /// - IEnumerable FindAll(ITextSource document, int offset, int length); - - /// - /// Finds the next match in the given ITextSource and the given range. - /// - /// This method must be implemented thread-safe. - ISearchResult FindNext(ITextSource document, int offset, int length); - } - - /// - /// Represents a search result. - /// - public interface ISearchResult : ISegment - { - /// - /// Replaces parts of the replacement string with parts from the match. (e.g. $1) - /// - string ReplaceWith(string replacement); - } - - /// - /// Defines supported search modes. - /// - public enum SearchMode - { - /// - /// Standard search - /// - Normal, - /// - /// RegEx search - /// - RegEx, - /// - /// Wildcard search - /// - Wildcard - } - - /// - public class SearchPatternException : Exception, ISerializable - { - /// - public SearchPatternException() - { - } - - /// - public SearchPatternException(string message) : base(message) - { - } - - /// - public SearchPatternException(string message, Exception innerException) : base(message, innerException) - { - } - - // This constructor is needed for serialization. - /// - protected SearchPatternException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Search/Localization.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Search/Localization.cs deleted file mode 100644 index b0044d93d..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Search/Localization.cs +++ /dev/null @@ -1,79 +0,0 @@ -// 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 -{ - /// - /// Holds default texts for buttons and labels in the SearchPanel. Override properties to add other languages. - /// - public class Localization - { - /// - /// Default: 'Match case' - /// - public virtual string MatchCaseText { - get { return "Match case"; } - } - - /// - /// Default: 'Match whole words' - /// - public virtual string MatchWholeWordsText { - get { return "Match whole words"; } - } - - - /// - /// Default: 'Use regular expressions' - /// - public virtual string UseRegexText { - get { return "Use regular expressions"; } - } - - /// - /// Default: 'Find next (F3)' - /// - public virtual string FindNextText { - get { return "Find next (F3)"; } - } - - /// - /// Default: 'Find previous (Shift+F3)' - /// - public virtual string FindPreviousText { - get { return "Find previous (Shift+F3)"; } - } - - /// - /// Default: 'Error: ' - /// - public virtual string ErrorText { - get { return "Error: "; } - } - - /// - /// Default: 'No matches found!' - /// - public virtual string NoMatchesFoundText { - get { return "No matches found!"; } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Search/RegexSearchStrategy.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Search/RegexSearchStrategy.cs deleted file mode 100644 index 47bde5af0..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Search/RegexSearchStrategy.cs +++ /dev/null @@ -1,85 +0,0 @@ -// 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 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchCommands.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchCommands.cs deleted file mode 100644 index 6e16f38f5..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchCommands.cs +++ /dev/null @@ -1,155 +0,0 @@ -// 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 -{ - /// - /// Search commands for AvalonEdit. - /// - public static class SearchCommands - { - /// - /// Finds the next occurrence in the file. - /// - public static readonly RoutedCommand FindNext = new RoutedCommand( - "FindNext", typeof(SearchPanel), - new InputGestureCollection { new KeyGesture(Key.F3) } - ); - - /// - /// Finds the previous occurrence in the file. - /// - public static readonly RoutedCommand FindPrevious = new RoutedCommand( - "FindPrevious", typeof(SearchPanel), - new InputGestureCollection { new KeyGesture(Key.F3, ModifierKeys.Shift) } - ); - - /// - /// Closes the SearchPanel. - /// - public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand( - "CloseSearchPanel", typeof(SearchPanel), - new InputGestureCollection { new KeyGesture(Key.Escape) } - ); - } - - /// - /// TextAreaInputHandler that registers all search-related commands. - /// - public class SearchInputHandler : TextAreaInputHandler - { - /// - /// Creates a new SearchInputHandler and registers the search-related commands. - /// - [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; - } - - internal void RegisterGlobalCommands(CommandBindingCollection commandBindings) - { - commandBindings.Add(new CommandBinding(ApplicationCommands.Find, ExecuteFind)); - commandBindings.Add(new CommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); - commandBindings.Add(new CommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); - } - - void RegisterCommands(ICollection 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; - } - } - - /// - /// Fired when SearchOptions are modified inside the SearchPanel. - /// - public event EventHandler SearchOptionsChanged { - add { panel.SearchOptionsChanged += value; } - remove { panel.SearchOptionsChanged -= value; } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchPanel.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchPanel.cs deleted file mode 100644 index cc2a7119a..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchPanel.cs +++ /dev/null @@ -1,528 +0,0 @@ -// 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 -{ - /// - /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. - /// - public class SearchPanel : Control - { - TextArea textArea; - SearchInputHandler handler; - TextDocument currentDocument; - SearchResultBackgroundRenderer renderer; - TextBox searchTextBox; - SearchPanelAdorner adorner; - - #region DependencyProperties - /// - /// Dependency property for . - /// - public static readonly DependencyProperty UseRegexProperty = - DependencyProperty.Register("UseRegex", typeof(bool), typeof(SearchPanel), - new FrameworkPropertyMetadata(false, SearchPatternChangedCallback)); - - /// - /// Gets/sets whether the search pattern should be interpreted as regular expression. - /// - public bool UseRegex { - get { return (bool)GetValue(UseRegexProperty); } - set { SetValue(UseRegexProperty, value); } - } - - /// - /// Dependency property for . - /// - public static readonly DependencyProperty MatchCaseProperty = - DependencyProperty.Register("MatchCase", typeof(bool), typeof(SearchPanel), - new FrameworkPropertyMetadata(false, SearchPatternChangedCallback)); - - /// - /// Gets/sets whether the search pattern should be interpreted case-sensitive. - /// - public bool MatchCase { - get { return (bool)GetValue(MatchCaseProperty); } - set { SetValue(MatchCaseProperty, value); } - } - - /// - /// Dependency property for . - /// - public static readonly DependencyProperty WholeWordsProperty = - DependencyProperty.Register("WholeWords", typeof(bool), typeof(SearchPanel), - new FrameworkPropertyMetadata(false, SearchPatternChangedCallback)); - - /// - /// Gets/sets whether the search pattern should only match whole words. - /// - public bool WholeWords { - get { return (bool)GetValue(WholeWordsProperty); } - set { SetValue(WholeWordsProperty, value); } - } - - /// - /// Dependency property for . - /// - public static readonly DependencyProperty SearchPatternProperty = - DependencyProperty.Register("SearchPattern", typeof(string), typeof(SearchPanel), - new FrameworkPropertyMetadata("", SearchPatternChangedCallback)); - - /// - /// Gets/sets the search pattern. - /// - public string SearchPattern { - get { return (string)GetValue(SearchPatternProperty); } - set { SetValue(SearchPatternProperty, value); } - } - - /// - /// Dependency property for . - /// - public static readonly DependencyProperty MarkerBrushProperty = - DependencyProperty.Register("MarkerBrush", typeof(Brush), typeof(SearchPanel), - new FrameworkPropertyMetadata(Brushes.LightGreen, MarkerBrushChangedCallback)); - - /// - /// Gets/sets the Brush used for marking search results in the TextView. - /// - public Brush MarkerBrush { - get { return (Brush)GetValue(MarkerBrushProperty); } - set { SetValue(MarkerBrushProperty, value); } - } - - /// - /// Dependency property for . - /// - public static readonly DependencyProperty LocalizationProperty = - DependencyProperty.Register("Localization", typeof(Localization), typeof(SearchPanel), - new FrameworkPropertyMetadata(new Localization())); - - /// - /// Gets/sets the localization for the SearchPanel. - /// - 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); - } - - /// - /// Creates a new SearchPanel. - /// - SearchPanel() - { - } - - /// - /// Attaches this SearchPanel to a TextArea instance. - /// - [Obsolete("Use the Install method instead")] - public void Attach(TextArea textArea) - { - if (textArea == null) - throw new ArgumentNullException("textArea"); - AttachInternal(textArea); - } - - /// - /// Creates a SearchPanel and installs it to the TextEditor's TextArea. - /// - /// This is a convenience wrapper. - public static SearchPanel Install(TextEditor editor) - { - if (editor == null) - throw new ArgumentNullException("editor"); - return Install(editor.TextArea); - } - - /// - /// Creates a SearchPanel and installs it to the TextArea. - /// - public static SearchPanel Install(TextArea textArea) - { - if (textArea == null) - throw new ArgumentNullException("textArea"); - SearchPanel panel = new SearchPanel(); - panel.AttachInternal(textArea); - panel.handler = new SearchInputHandler(textArea, panel); - textArea.DefaultInputHandler.NestedInputHandlers.Add(panel.handler); - return panel; - } - - public void RegisterCommands(CommandBindingCollection commandBindings) - { - handler.RegisterGlobalCommands(commandBindings); - } - - /// - /// Removes the SearchPanel from the TextArea. - /// - 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); - } - - /// - 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); - } - } - - /// - /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. - /// - public void Reactivate() - { - if (searchTextBox == null) - return; - searchTextBox.Focus(); - searchTextBox.SelectAll(); - } - - /// - /// Moves to the next occurrence in the file. - /// - public void FindNext() - { - SearchResult result = renderer.CurrentResults.FindFirstSegmentWithStartAfter(textArea.Caret.Offset + 1); - if (result == null) - result = renderer.CurrentResults.FirstSegment; - if (result != null) { - SelectResult(result); - } - } - - /// - /// Moves to the previous occurrence in the file. - /// - 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 = true, Focusable = 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; - 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; - } - } - - /// - /// Gets whether the Panel is already closed. - /// - public bool IsClosed { get; private set; } - - /// - /// Closes the SearchPanel. - /// - 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(); - } - - /// - /// Closes the SearchPanel and removes it. - /// - [Obsolete("Use the Uninstall method instead!")] - public void CloseAndRemove() - { - Close(); - textArea.DocumentChanged -= textArea_DocumentChanged; - if (currentDocument != null) - currentDocument.TextChanged -= textArea_Document_TextChanged; - } - - /// - /// Opens the an existing search panel. - /// - 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); - } - - /// - /// Fired when SearchOptions are changed inside the SearchPanel. - /// - public event EventHandler SearchOptionsChanged; - - /// - /// Raises the event. - /// - protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) - { - if (SearchOptionsChanged != null) { - SearchOptionsChanged(this, e); - } - } - } - - /// - /// EventArgs for event. - /// - public class SearchOptionsChangedEventArgs : EventArgs - { - /// - /// Gets the search pattern. - /// - public string SearchPattern { get; private set; } - - /// - /// Gets whether the search pattern should be interpreted case-sensitive. - /// - public bool MatchCase { get; private set; } - - /// - /// Gets whether the search pattern should be interpreted as regular expression. - /// - public bool UseRegex { get; private set; } - - /// - /// Gets whether the search pattern should only match whole words. - /// - public bool WholeWords { get; private set; } - - /// - /// Creates a new SearchOptionsChangedEventArgs instance. - /// - 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchPanel.xaml b/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchPanel.xaml deleted file mode 100644 index 3e7e19f8e..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchPanel.xaml +++ /dev/null @@ -1,47 +0,0 @@ - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchResultBackgroundRenderer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchResultBackgroundRenderer.cs deleted file mode 100644 index 41669269e..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchResultBackgroundRenderer.cs +++ /dev/null @@ -1,93 +0,0 @@ -// 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 currentResults = new TextSegmentCollection(); - - public TextSegmentCollection 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); - } - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchStrategyFactory.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchStrategyFactory.cs deleted file mode 100644 index 4c45a1477..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Search/SearchStrategyFactory.cs +++ /dev/null @@ -1,83 +0,0 @@ -// 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 -{ - /// - /// Provides factory methods for ISearchStrategies. - /// - public static class SearchStrategyFactory - { - /// - /// Creates a default ISearchStrategy with the given parameters. - /// - 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(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Search/next.png b/AvalonEdit/ICSharpCode.AvalonEdit/Search/next.png deleted file mode 100644 index 250330790b12cd2a59ab899dc8c3820c9b414a24..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1304 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstPBjy3;{kN zu0U}!uM`G`|EfMSHG`Jxg)TCUS!t8J#V%!|y~i2bvL`-;dp*i7`q$qJs=w}7@z|;I ziF?gcpZbTvElH2?)AOI#yL zg7ec#$`gxH83GbB^GfvmTtgJfjP*?QEX=JNfT74x>*?Ycq7fY1|5m6;LBMsoNx+Rw zF`tyR?*G>;EDW6U?n86&w|52(f4JY=d3IXyjjNBK-xqOF^60Ug5N>FVdQ&MBb@0BpOI+W-In diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Search/prev.png b/AvalonEdit/ICSharpCode.AvalonEdit/Search/prev.png deleted file mode 100644 index f0454a237cbb52216d9bd8d6afe6065e936e9b91..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1300 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstPBjy3;{kN zu0U}!uM`G`|EfMSHG`Jxg)TCUS!t8J#V%!|y~i2bvL`-;dp*i7`q$qJs=w}7@z|;I ziF?gcpZbTvElH2?)AOI#yL zg7ec#$`gxH83GbB^GfvmTtgJfjP*?QEX=JNfT74x>FMGaq7fW>;VoaY0uO6|BV*&L z%SQIcu6(ce3hS74(D(nBC7H9r7J8I^{q>D|$H~UqGFy(mtZ#~TNmg@~WPbag;q|M( z$A3Sr5zOH1c%QoP*0)B7D?$u&UeB4mUvQDhf{?`_*}pkFB_`{rIZpaxFzHcAptyhw a=Xv3}paY9oxgOjG7dM`+elF{r5}E)BQIUH9 diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/IActiveElement.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/IActiveElement.cs deleted file mode 100644 index 1c566d7c5..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/IActiveElement.cs +++ /dev/null @@ -1,50 +0,0 @@ -// 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 -{ - /// - /// Represents an active element that allows the snippet to stay interactive after insertion. - /// - public interface IActiveElement - { - /// - /// Called when the all snippet elements have been inserted. - /// - void OnInsertionCompleted(); - - /// - /// Called when the interactive mode is deactivated. - /// - void Deactivate(SnippetEventArgs e); - - /// - /// Gets whether this element is editable (the user will be able to select it with Tab). - /// - bool IsEditable { get; } - - /// - /// Gets the segment associated with this element. May be null. - /// - ISegment Segment { get; } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/InsertionContext.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/InsertionContext.cs deleted file mode 100644 index 17438c6af..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/InsertionContext.cs +++ /dev/null @@ -1,302 +0,0 @@ -// 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 -{ - /// - /// Represents the context of a snippet insertion. - /// - public class InsertionContext : IWeakEventListener - { - enum Status - { - Insertion, - RaisingInsertionCompleted, - Interactive, - RaisingDeactivated, - Deactivated - } - - Status currentStatus = Status.Insertion; - - /// - /// Creates a new InsertionContext instance. - /// - 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); - } - - /// - /// Gets the text area. - /// - public TextArea TextArea { get; private set; } - - /// - /// Gets the text document. - /// - public ICSharpCode.AvalonEdit.Document.TextDocument Document { get; private set; } - - /// - /// Gets the text that was selected before the insertion of the snippet. - /// - public string SelectedText { get; private set; } - - /// - /// Gets the indentation at the insertion position. - /// - public string Indentation { get; private set; } - - /// - /// Gets the indentation string for a single indentation level. - /// - public string Tab { get; private set; } - - /// - /// Gets the line terminator at the insertion position. - /// - public string LineTerminator { get; private set; } - - /// - /// Gets/Sets the insertion position. - /// - public int InsertionPosition { get; set; } - - readonly int startPosition; - ICSharpCode.AvalonEdit.Document.AnchorSegment wholeSnippetAnchor; - bool deactivateIfSnippetEmpty; - - /// - /// Gets the start position of the snippet insertion. - /// - public int StartPosition { - get { - if (wholeSnippetAnchor != null) - return wholeSnippetAnchor.Offset; - else - return startPosition; - } - } - - /// - /// Inserts text at the insertion position and advances the insertion position. - /// This method will add the current indentation to every line in and will - /// replace newlines with the expected newline for the document. - /// - 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 elementMap = new Dictionary(); - List registeredElements = new List(); - - /// - /// Registers an active element. Elements should be registered during insertion and will be called back - /// when insertion has completed. - /// - /// The snippet element that created the active element. - /// The active element. - 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); - } - - /// - /// Returns the active element belonging to the specified snippet element, or null if no such active element is found. - /// - 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; - } - - /// - /// Gets the list of active elements. - /// - public IEnumerable ActiveElements { - get { return registeredElements; } - } - - /// - /// Calls the method on all registered active elements - /// and raises the event. - /// - /// The EventArgs to use - [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; - - /// - /// Occurs when the all snippet elements have been inserted. - /// - public event EventHandler InsertionCompleted; - - /// - /// Calls the method on all registered active elements. - /// - /// The EventArgs to use - 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; - } - - /// - /// Occurs when the interactive mode is deactivated. - /// - public event EventHandler Deactivated; - - bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e) - { - return ReceiveWeakEvent(managerType, sender, e); - } - - /// - 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; - } - - /// - /// Adds existing segments as snippet elements. - /// - 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))); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/Snippet.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/Snippet.cs deleted file mode 100644 index ebc2771bf..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/Snippet.cs +++ /dev/null @@ -1,59 +0,0 @@ -// 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 -{ - /// - /// A code snippet that can be inserted into the text editor. - /// - [Serializable] - public class Snippet : SnippetContainerElement - { - /// - /// Inserts the snippet into the text area. - /// - 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); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetAnchorElement.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetAnchorElement.cs deleted file mode 100644 index 924edc96b..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetAnchorElement.cs +++ /dev/null @@ -1,113 +0,0 @@ -// 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 -{ - /// - /// Creates a named anchor that can be accessed by other SnippetElements. - /// - public sealed class SnippetAnchorElement : SnippetElement - { - /// - /// Gets or sets the name of the anchor. - /// - public string Name { get; private set; } - - /// - /// Creates a SnippetAnchorElement with the supplied name. - /// - public SnippetAnchorElement(string name) - { - this.Name = name; - } - - /// - 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)); - } - } - - /// - /// AnchorElement created by SnippetAnchorElement. - /// - public sealed class AnchorElement : IActiveElement - { - /// - public bool IsEditable { - get { return false; } - } - - AnchorSegment segment; - InsertionContext context; - - /// - public ISegment Segment { - get { return segment; } - } - - /// - /// Creates a new AnchorElement. - /// - public AnchorElement(AnchorSegment segment, string name, InsertionContext context) - { - this.segment = segment; - this.context = context; - this.Name = name; - } - - /// - /// Gets or sets the text at the anchor. - /// - 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); - } - } - } - - /// - /// Gets or sets the name of the anchor. - /// - public string Name { get; private set; } - - /// - public void OnInsertionCompleted() - { - } - - /// - public void Deactivate(SnippetEventArgs e) - { - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetBoundElement.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetBoundElement.cs deleted file mode 100644 index 746ec8043..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetBoundElement.cs +++ /dev/null @@ -1,138 +0,0 @@ -// 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 -{ - /// - /// An element that binds to a and displays the same text. - /// - [Serializable] - public class SnippetBoundElement : SnippetElement - { - SnippetReplaceableTextElement targetElement; - - /// - /// Gets/Sets the target element. - /// - public SnippetReplaceableTextElement TargetElement { - get { return targetElement; } - set { targetElement = value; } - } - - /// - /// Converts the text before copying it. - /// - public virtual string ConvertText(string input) - { - return input; - } - - /// - 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)); - } - } - - /// - 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; } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetCaretElement.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetCaretElement.cs deleted file mode 100644 index 0fd8ac05d..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetCaretElement.cs +++ /dev/null @@ -1,73 +0,0 @@ -// 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 -{ - /// - /// Sets the caret position after interactive mode has finished. - /// - [Serializable] - public class SnippetCaretElement : SnippetElement - { - [OptionalField] - bool setCaretOnlyIfTextIsSelected; - - /// - /// Creates a new SnippetCaretElement. - /// - public SnippetCaretElement() - { - } - - /// - /// Creates a new SnippetCaretElement. - /// - /// - /// 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. - /// - public SnippetCaretElement(bool setCaretOnlyIfTextIsSelected) - { - this.setCaretOnlyIfTextIsSelected = setCaretOnlyIfTextIsSelected; - } - - /// - 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; - } - }; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetContainerElement.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetContainerElement.cs deleted file mode 100644 index ee16630c4..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetContainerElement.cs +++ /dev/null @@ -1,62 +0,0 @@ -// 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 -{ - /// - /// A snippet element that has sub-elements. - /// - [Serializable] - public class SnippetContainerElement : SnippetElement - { - NullSafeCollection elements = new NullSafeCollection(); - - /// - /// Gets the list of child elements. - /// - public IList Elements { - get { return elements; } - } - - /// - public override void Insert(InsertionContext context) - { - foreach (SnippetElement e in this.Elements) { - e.Insert(context); - } - } - - /// - 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetElement.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetElement.cs deleted file mode 100644 index 4b03ea559..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetElement.cs +++ /dev/null @@ -1,43 +0,0 @@ -// 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 -{ - /// - /// An element inside a snippet. - /// - [Serializable] - public abstract class SnippetElement - { - /// - /// Performs insertion of the snippet. - /// - public abstract void Insert(InsertionContext context); - - /// - /// Converts the snippet to text, with replaceable fields in italic. - /// - public virtual Inline ToTextRun() - { - return null; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetEventArgs.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetEventArgs.cs deleted file mode 100644 index 9facd8940..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetEventArgs.cs +++ /dev/null @@ -1,72 +0,0 @@ -// 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 -{ - /// - /// Provides information about the event that occured during use of snippets. - /// - public class SnippetEventArgs : EventArgs - { - /// - /// Gets the reason for deactivation. - /// - public DeactivateReason Reason { get; private set; } - - /// - /// Creates a new SnippetEventArgs object, with a DeactivateReason. - /// - public SnippetEventArgs(DeactivateReason reason) - { - this.Reason = reason; - } - } - - /// - /// Describes the reason for deactivation of a . - /// - public enum DeactivateReason - { - /// - /// Unknown reason. - /// - Unknown, - /// - /// Snippet was deleted. - /// - Deleted, - /// - /// There are no active elements in the snippet. - /// - NoActiveElements, - /// - /// The SnippetInputHandler was detached. - /// - InputHandlerDetached, - /// - /// Return was pressed by the user. - /// - ReturnPressed, - /// - /// Escape was pressed by the user. - /// - EscapePressed - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetInputHandler.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetInputHandler.cs deleted file mode 100644 index 55c1a74c7..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetInputHandler.cs +++ /dev/null @@ -1,93 +0,0 @@ -// 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 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(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetReplaceableTextElement.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetReplaceableTextElement.cs deleted file mode 100644 index e07b2843b..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetReplaceableTextElement.cs +++ /dev/null @@ -1,227 +0,0 @@ -// 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 -{ - /// - /// Text element that is supposed to be replaced by the user. - /// Will register an . - /// - [Serializable] - public class SnippetReplaceableTextElement : SnippetTextElement - { - /// - 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)); - } - - /// - public override Inline ToTextRun() - { - return new Italic(base.ToTextRun()); - } - } - - /// - /// Interface for active element registered by . - /// - public interface IReplaceableActiveElement : IActiveElement - { - /// - /// Gets the current text inside the element. - /// - string Text { get; } - - /// - /// Occurs when the text inside the element changes. - /// - 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()) { - if (boundElement.targetElement == element) { - geoBuilder.AddSegment(textView, boundElement.Segment); - geoBuilder.CloseFigure(); - } - } - drawingContext.DrawGeometry(null, activeBorderPen, geoBuilder.CreateGeometry()); - } - } - } - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetSelectionElement.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetSelectionElement.cs deleted file mode 100644 index 569758017..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetSelectionElement.cs +++ /dev/null @@ -1,58 +0,0 @@ -// 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 -{ - /// - /// Inserts the previously selected text at the selection marker. - /// - [Serializable] - public class SnippetSelectionElement : SnippetElement - { - /// - /// Gets/Sets the new indentation of the selected text. - /// - public int Indentation { get; set; } - - /// - 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetTextElement.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetTextElement.cs deleted file mode 100644 index 5ee82a9ca..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Snippets/SnippetTextElement.cs +++ /dev/null @@ -1,53 +0,0 @@ -// 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 -{ - /// - /// Represents a text element in a snippet. - /// - [Serializable] - public class SnippetTextElement : SnippetElement - { - string text; - - /// - /// The text to be inserted. - /// - public string Text { - get { return text; } - set { text = value; } - } - - /// - public override void Insert(InsertionContext context) - { - if (text != null) - context.InsertText(text); - } - - /// - public override Inline ToTextRun() - { - return new Run(text ?? string.Empty); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/TextEditor.cs b/AvalonEdit/ICSharpCode.AvalonEdit/TextEditor.cs deleted file mode 100644 index 91e183d46..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/TextEditor.cs +++ /dev/null @@ -1,1182 +0,0 @@ -// 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 -{ - /// - /// The text editor control. - /// Contains a scrollable TextArea. - /// - [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)); - } - - /// - /// Creates a new TextEditor instance. - /// - public TextEditor() : this(new TextArea()) - { - } - - /// - /// Creates a new TextEditor instance. - /// - 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 - - /// - protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() - { - return new TextEditorAutomationPeer(this); - } - - /// Forward focus to TextArea. - /// - protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e) - { - base.OnGotKeyboardFocus(e); - if (e.NewFocus == this) { - Keyboard.Focus(this.TextArea); - e.Handled = true; - } - } - - #region Document property - /// - /// Document property. - /// - public static readonly DependencyProperty DocumentProperty - = TextView.DocumentProperty.AddOwner( - typeof(TextEditor), new FrameworkPropertyMetadata(OnDocumentChanged)); - - /// - /// Gets/Sets the document displayed by the text editor. - /// This is a dependency property. - /// - public TextDocument Document { - get { return (TextDocument)GetValue(DocumentProperty); } - set { SetValue(DocumentProperty, value); } - } - - /// - /// Occurs when the document property has changed. - /// - public event EventHandler DocumentChanged; - - /// - /// Raises the event. - /// - 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 - /// - /// Options property. - /// - public static readonly DependencyProperty OptionsProperty - = TextView.OptionsProperty.AddOwner(typeof(TextEditor), new FrameworkPropertyMetadata(OnOptionsChanged)); - - /// - /// Gets/Sets the options currently used by the text editor. - /// - public TextEditorOptions Options { - get { return (TextEditorOptions)GetValue(OptionsProperty); } - set { SetValue(OptionsProperty, value); } - } - - /// - /// Occurs when a text editor option has changed. - /// - public event PropertyChangedEventHandler OptionChanged; - - /// - /// Raises the event. - /// - 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)); - } - - /// - 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 - /// - /// Gets/Sets the text of the current document. - /// - [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; - } - - /// - /// Occurs when the Text property changes. - /// - public event EventHandler TextChanged; - - /// - /// Raises the event. - /// - protected virtual void OnTextChanged(EventArgs e) - { - if (TextChanged != null) { - TextChanged(this, e); - } - } - #endregion - - #region TextArea / ScrollViewer properties - readonly TextArea textArea; - ScrollViewer scrollViewer; - - /// - /// Is called after the template was applied. - /// - public override void OnApplyTemplate() - { - base.OnApplyTemplate(); - scrollViewer = (ScrollViewer)Template.FindName("PART_ScrollViewer", this); - } - - /// - /// Gets the text area. - /// - public TextArea TextArea { - get { - return textArea; - } - } - - /// - /// 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. - /// - 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 - /// - /// The property. - /// - public static readonly DependencyProperty SyntaxHighlightingProperty = - DependencyProperty.Register("SyntaxHighlighting", typeof(IHighlightingDefinition), typeof(TextEditor), - new FrameworkPropertyMetadata(OnSyntaxHighlightingChanged)); - - - /// - /// Gets/sets the syntax highlighting definition used to colorize the text. - /// - 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); - } - } - - /// - /// Creates the highlighting colorizer for the specified highlighting definition. - /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. - /// - /// - protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) - { - if (highlightingDefinition == null) - throw new ArgumentNullException("highlightingDefinition"); - return new HighlightingColorizer(highlightingDefinition); - } - #endregion - - #region WordWrap - /// - /// Word wrap dependency property. - /// - public static readonly DependencyProperty WordWrapProperty = - DependencyProperty.Register("WordWrap", typeof(bool), typeof(TextEditor), - new FrameworkPropertyMetadata(Boxes.False)); - - /// - /// Specifies whether the text editor uses word wrapping. - /// - /// - /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the - /// HorizontalScrollBarVisibility setting. - /// - public bool WordWrap { - get { return (bool)GetValue(WordWrapProperty); } - set { SetValue(WordWrapProperty, Boxes.Box(value)); } - } - #endregion - - #region IsReadOnly - /// - /// IsReadOnly dependency property. - /// - public static readonly DependencyProperty IsReadOnlyProperty = - DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(TextEditor), - new FrameworkPropertyMetadata(Boxes.False, OnIsReadOnlyChanged)); - - /// - /// Specifies whether the user can change the text editor content. - /// Setting this property will replace the - /// TextArea.ReadOnlySectionProvider. - /// - 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 - /// - /// Dependency property for - /// - public static readonly DependencyProperty IsModifiedProperty = - DependencyProperty.Register("IsModified", typeof(bool), typeof(TextEditor), - new FrameworkPropertyMetadata(Boxes.False, OnIsModifiedChanged)); - - /// - /// Gets/Sets the 'modified' flag. - /// - 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 - /// - /// ShowLineNumbers dependency property. - /// - public static readonly DependencyProperty ShowLineNumbersProperty = - DependencyProperty.Register("ShowLineNumbers", typeof(bool), typeof(TextEditor), - new FrameworkPropertyMetadata(Boxes.False, OnShowLineNumbersChanged)); - - /// - /// Specifies whether line numbers are shown on the left to the text view. - /// - 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 - /// - /// LineNumbersForeground dependency property. - /// - public static readonly DependencyProperty LineNumbersForegroundProperty = - DependencyProperty.Register("LineNumbersForeground", typeof(Brush), typeof(TextEditor), - new FrameworkPropertyMetadata(Brushes.Gray, OnLineNumbersForegroundChanged)); - - /// - /// Gets/sets the Brush used for displaying the foreground color of line numbers. - /// - 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 - /// - /// Appends text to the end of the document. - /// - public void AppendText(string textData) - { - var document = GetDocument(); - document.Insert(document.TextLength, textData); - } - - /// - /// Begins a group of document changes. - /// - public void BeginChange() - { - GetDocument().BeginUpdate(); - } - - /// - /// Copies the current selection to the clipboard. - /// - public void Copy() - { - Execute(ApplicationCommands.Copy); - } - - /// - /// Removes the current selection and copies it to the clipboard. - /// - public void Cut() - { - Execute(ApplicationCommands.Cut); - } - - /// - /// Begins a group of document changes and returns an object that ends the group of document - /// changes when it is disposed. - /// - public IDisposable DeclareChangeBlock() - { - return GetDocument().RunUpdate(); - } - - /// - /// Ends the current group of document changes. - /// - public void EndChange() - { - GetDocument().EndUpdate(); - } - - /// - /// Scrolls one line down. - /// - public void LineDown() - { - if (scrollViewer != null) - scrollViewer.LineDown(); - } - - /// - /// Scrolls to the left. - /// - public void LineLeft() - { - if (scrollViewer != null) - scrollViewer.LineLeft(); - } - - /// - /// Scrolls to the right. - /// - public void LineRight() - { - if (scrollViewer != null) - scrollViewer.LineRight(); - } - - /// - /// Scrolls one line up. - /// - public void LineUp() - { - if (scrollViewer != null) - scrollViewer.LineUp(); - } - - /// - /// Scrolls one page down. - /// - public void PageDown() - { - if (scrollViewer != null) - scrollViewer.PageDown(); - } - - /// - /// Scrolls one page up. - /// - public void PageUp() - { - if (scrollViewer != null) - scrollViewer.PageUp(); - } - - /// - /// Scrolls one page left. - /// - public void PageLeft() - { - if (scrollViewer != null) - scrollViewer.PageLeft(); - } - - /// - /// Scrolls one page right. - /// - public void PageRight() - { - if (scrollViewer != null) - scrollViewer.PageRight(); - } - - /// - /// Pastes the clipboard content. - /// - public void Paste() - { - Execute(ApplicationCommands.Paste); - } - - /// - /// Redoes the most recent undone command. - /// - /// True is the redo operation was successful, false is the redo stack is empty. - public bool Redo() - { - if (CanExecute(ApplicationCommands.Redo)) { - Execute(ApplicationCommands.Redo); - return true; - } - return false; - } - - /// - /// Scrolls to the end of the document. - /// - public void ScrollToEnd() - { - ApplyTemplate(); // ensure scrollViewer is created - if (scrollViewer != null) - scrollViewer.ScrollToEnd(); - } - - /// - /// Scrolls to the start of the document. - /// - public void ScrollToHome() - { - ApplyTemplate(); // ensure scrollViewer is created - if (scrollViewer != null) - scrollViewer.ScrollToHome(); - } - - /// - /// Scrolls to the specified position in the document. - /// - public void ScrollToHorizontalOffset(double offset) - { - ApplyTemplate(); // ensure scrollViewer is created - if (scrollViewer != null) - scrollViewer.ScrollToHorizontalOffset(offset); - } - - /// - /// Scrolls to the specified position in the document. - /// - public void ScrollToVerticalOffset(double offset) - { - ApplyTemplate(); // ensure scrollViewer is created - if (scrollViewer != null) - scrollViewer.ScrollToVerticalOffset(offset); - } - - /// - /// Selects the entire text. - /// - public void SelectAll() - { - Execute(ApplicationCommands.SelectAll); - } - - /// - /// Undoes the most recent command. - /// - /// True is the undo operation was successful, false is the undo stack is empty. - public bool Undo() - { - if (CanExecute(ApplicationCommands.Undo)) { - Execute(ApplicationCommands.Undo); - return true; - } - return false; - } - - /// - /// Gets if the most recent undone command can be redone. - /// - public bool CanRedo { - get { return CanExecute(ApplicationCommands.Redo); } - } - - /// - /// Gets if the most recent command can be undone. - /// - public bool CanUndo { - get { return CanExecute(ApplicationCommands.Undo); } - } - - /// - /// Gets the vertical size of the document. - /// - public double ExtentHeight { - get { - return scrollViewer != null ? scrollViewer.ExtentHeight : 0; - } - } - - /// - /// Gets the horizontal size of the current document region. - /// - public double ExtentWidth { - get { - return scrollViewer != null ? scrollViewer.ExtentWidth : 0; - } - } - - /// - /// Gets the horizontal size of the viewport. - /// - public double ViewportHeight { - get { - return scrollViewer != null ? scrollViewer.ViewportHeight : 0; - } - } - - /// - /// Gets the horizontal size of the viewport. - /// - public double ViewportWidth { - get { - return scrollViewer != null ? scrollViewer.ViewportWidth : 0; - } - } - - /// - /// Gets the vertical scroll position. - /// - public double VerticalOffset { - get { - return scrollViewer != null ? scrollViewer.VerticalOffset : 0; - } - } - - /// - /// Gets the horizontal scroll position. - /// - public double HorizontalOffset { - get { - return scrollViewer != null ? scrollViewer.HorizontalOffset : 0; - } - } - #endregion - - #region TextBox methods - /// - /// Gets/Sets the selected text. - /// - [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); - } - } - } - - /// - /// Gets/sets the caret position. - /// - [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; - } - } - - /// - /// Gets/sets the start position of the selection. - /// - [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); - } - } - - /// - /// Gets/sets the length of the selection. - /// - [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); - } - } - - /// - /// Selects the specified text section. - /// - 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; - } - - /// - /// Gets the number of lines in the document. - /// - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public int LineCount { - get { - TextDocument document = this.Document; - if (document != null) - return document.LineCount; - else - return 1; - } - } - - /// - /// Clears the text. - /// - public void Clear() - { - this.Text = string.Empty; - } - #endregion - - #region Loading from stream - /// - /// Loads the text from the stream, auto-detecting the encoding. - /// - /// - /// This method sets to false. - /// - 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); - } - - /// - /// Loads the text from the stream, auto-detecting the encoding. - /// - 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); - } - } - - /// - /// Encoding dependency property. - /// - public static readonly DependencyProperty EncodingProperty = - DependencyProperty.Register("Encoding", typeof(Encoding), typeof(TextEditor)); - - /// - /// Gets/sets the encoding used when the file is saved. - /// - /// - /// The method autodetects the encoding of the file and sets this property accordingly. - /// The method uses the encoding specified in this property. - /// - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public Encoding Encoding { - get { return (Encoding)GetValue(EncodingProperty); } - set { SetValue(EncodingProperty, value); } - } - - /// - /// Saves the text to the stream. - /// - /// - /// This method sets to false. - /// - 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); - } - - /// - /// Saves the text to the file. - /// - 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 - /// - /// The PreviewMouseHover event. - /// - public static readonly RoutedEvent PreviewMouseHoverEvent = - TextView.PreviewMouseHoverEvent.AddOwner(typeof(TextEditor)); - - /// - /// The MouseHover event. - /// - public static readonly RoutedEvent MouseHoverEvent = - TextView.MouseHoverEvent.AddOwner(typeof(TextEditor)); - - - /// - /// The PreviewMouseHoverStopped event. - /// - public static readonly RoutedEvent PreviewMouseHoverStoppedEvent = - TextView.PreviewMouseHoverStoppedEvent.AddOwner(typeof(TextEditor)); - - /// - /// The MouseHoverStopped event. - /// - public static readonly RoutedEvent MouseHoverStoppedEvent = - TextView.MouseHoverStoppedEvent.AddOwner(typeof(TextEditor)); - - - /// - /// Occurs when the mouse has hovered over a fixed location for some time. - /// - public event MouseEventHandler PreviewMouseHover { - add { AddHandler(PreviewMouseHoverEvent, value); } - remove { RemoveHandler(PreviewMouseHoverEvent, value); } - } - - /// - /// Occurs when the mouse has hovered over a fixed location for some time. - /// - public event MouseEventHandler MouseHover { - add { AddHandler(MouseHoverEvent, value); } - remove { RemoveHandler(MouseHoverEvent, value); } - } - - /// - /// Occurs when the mouse had previously hovered but now started moving again. - /// - public event MouseEventHandler PreviewMouseHoverStopped { - add { AddHandler(PreviewMouseHoverStoppedEvent, value); } - remove { RemoveHandler(PreviewMouseHoverStoppedEvent, value); } - } - - /// - /// Occurs when the mouse had previously hovered but now started moving again. - /// - public event MouseEventHandler MouseHoverStopped { - add { AddHandler(MouseHoverStoppedEvent, value); } - remove { RemoveHandler(MouseHoverStoppedEvent, value); } - } - #endregion - - #region ScrollBarVisibility - /// - /// Dependency property for - /// - public static readonly DependencyProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner(typeof(TextEditor), new FrameworkPropertyMetadata(ScrollBarVisibility.Visible)); - - /// - /// Gets/Sets the horizontal scroll bar visibility. - /// - public ScrollBarVisibility HorizontalScrollBarVisibility { - get { return (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); } - set { SetValue(HorizontalScrollBarVisibilityProperty, value); } - } - - /// - /// Dependency property for - /// - public static readonly DependencyProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner(typeof(TextEditor), new FrameworkPropertyMetadata(ScrollBarVisibility.Visible)); - - /// - /// Gets/Sets the vertical scroll bar visibility. - /// - public ScrollBarVisibility VerticalScrollBarVisibility { - get { return (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); } - set { SetValue(VerticalScrollBarVisibilityProperty, value); } - } - #endregion - - object IServiceProvider.GetService(Type serviceType) - { - return textArea.GetService(serviceType); - } - - /// - /// Gets the text view position from a point inside the editor. - /// - /// The position, relative to top left - /// corner of TextEditor control - /// The text view position, or null if the point is outside the document. - public TextViewPosition? GetPositionFromPoint(Point point) - { - if (this.Document == null) - return null; - TextView textView = this.TextArea.TextView; - return textView.GetPosition(TranslatePoint(point, textView) + textView.ScrollOffset); - } - - /// - /// Scrolls to the specified line. - /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). - /// - public void ScrollToLine(int line) - { - ScrollTo(line, -1); - } - - /// - /// Scrolls to the specified line/column. - /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). - /// - 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); - } - } - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/TextEditor.xaml b/AvalonEdit/ICSharpCode.AvalonEdit/TextEditor.xaml deleted file mode 100644 index da738e09b..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/TextEditor.xaml +++ /dev/null @@ -1,78 +0,0 @@ - - - - - \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorAutomationPeer.cs b/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorAutomationPeer.cs deleted file mode 100644 index e0c081271..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorAutomationPeer.cs +++ /dev/null @@ -1,80 +0,0 @@ -// 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 -{ - /// - /// Exposes to automation. - /// - public class TextEditorAutomationPeer : FrameworkElementAutomationPeer, IValueProvider - { - /// - /// Creates a new TextEditorAutomationPeer instance. - /// - 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; } - } - - /// - 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)); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorComponent.cs b/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorComponent.cs deleted file mode 100644 index 8c65d6cc9..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorComponent.cs +++ /dev/null @@ -1,55 +0,0 @@ -// 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 -{ - /// - /// Represents a text editor control (, - /// or ). - /// - public interface ITextEditorComponent : IServiceProvider - { - /// - /// Gets the document being edited. - /// - TextDocument Document { get; } - - /// - /// Occurs when the Document property changes (when the text editor is connected to another - /// document - not when the document content changes). - /// - event EventHandler DocumentChanged; - - /// - /// Gets the options of the text editor. - /// - TextEditorOptions Options { get; } - - /// - /// Occurs when the Options property changes, or when an option inside the current option list - /// changes. - /// - event PropertyChangedEventHandler OptionChanged; - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorOptions.cs b/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorOptions.cs deleted file mode 100644 index 5b0fa5538..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorOptions.cs +++ /dev/null @@ -1,497 +0,0 @@ -// 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 -{ - /// - /// A container for the text editor options. - /// - [Serializable] - public class TextEditorOptions : INotifyPropertyChanged - { - #region ctor - /// - /// Initializes an empty instance of TextEditorOptions. - /// - public TextEditorOptions() - { - } - - /// - /// Initializes a new instance of TextEditorOptions by copying all values - /// from to the new instance. - /// - 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 - /// - [field: NonSerialized] - public event PropertyChangedEventHandler PropertyChanged; - - /// - /// Raises the PropertyChanged event. - /// - /// The name of the changed property. - protected void OnPropertyChanged(string propertyName) - { - OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); - } - - /// - /// Raises the PropertyChanged event. - /// - protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) - { - if (PropertyChanged != null) { - PropertyChanged(this, e); - } - } - #endregion - - #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters - bool showSpaces; - - /// - /// Gets/Sets whether to show · for spaces. - /// - /// The default value is false. - [DefaultValue(false)] - public virtual bool ShowSpaces { - get { return showSpaces; } - set { - if (showSpaces != value) { - showSpaces = value; - OnPropertyChanged("ShowSpaces"); - } - } - } - - bool showTabs; - - /// - /// Gets/Sets whether to show » for tabs. - /// - /// The default value is false. - [DefaultValue(false)] - public virtual bool ShowTabs { - get { return showTabs; } - set { - if (showTabs != value) { - showTabs = value; - OnPropertyChanged("ShowTabs"); - } - } - } - - bool showEndOfLine; - - /// - /// Gets/Sets whether to show ¶ at the end of lines. - /// - /// The default value is false. - [DefaultValue(false)] - public virtual bool ShowEndOfLine { - get { return showEndOfLine; } - set { - if (showEndOfLine != value) { - showEndOfLine = value; - OnPropertyChanged("ShowEndOfLine"); - } - } - } - - bool showBoxForControlCharacters = true; - - /// - /// Gets/Sets whether to show a box with the hex code for control characters. - /// - /// The default value is true. - [DefaultValue(true)] - public virtual bool ShowBoxForControlCharacters { - get { return showBoxForControlCharacters; } - set { - if (showBoxForControlCharacters != value) { - showBoxForControlCharacters = value; - OnPropertyChanged("ShowBoxForControlCharacters"); - } - } - } - #endregion - - #region EnableHyperlinks - bool enableHyperlinks = true; - - /// - /// Gets/Sets whether to enable clickable hyperlinks in the editor. - /// - /// The default value is true. - [DefaultValue(true)] - public virtual bool EnableHyperlinks { - get { return enableHyperlinks; } - set { - if (enableHyperlinks != value) { - enableHyperlinks = value; - OnPropertyChanged("EnableHyperlinks"); - } - } - } - - bool enableEmailHyperlinks = true; - - /// - /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. - /// - /// The default value is true. - [DefaultValue(true)] - public virtual bool EnableEmailHyperlinks { - get { return enableEmailHyperlinks; } - set { - if (enableEmailHyperlinks != value) { - enableEmailHyperlinks = value; - OnPropertyChanged("EnableEMailHyperlinks"); - } - } - } - - bool requireControlModifierForHyperlinkClick = true; - - /// - /// Gets/Sets whether the user needs to press Control to click hyperlinks. - /// The default value is true. - /// - /// The default value is true. - [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; - - /// - /// Gets/Sets the width of one indentation unit. - /// - /// The default value is 4. - [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; - - /// - /// Gets/Sets whether to use spaces for indentation instead of tabs. - /// - /// The default value is false. - [DefaultValue(false)] - public virtual bool ConvertTabsToSpaces { - get { return convertTabsToSpaces; } - set { - if (convertTabsToSpaces != value) { - convertTabsToSpaces = value; - OnPropertyChanged("ConvertTabsToSpaces"); - OnPropertyChanged("IndentationString"); - } - } - } - - /// - /// Gets the text used for indentation. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] - [Browsable(false)] - public string IndentationString { - get { return GetIndentationString(1); } - } - - /// - /// Gets text required to indent from the specified to the next indentation level. - /// - 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; - - /// - /// Gets/Sets whether copying without a selection copies the whole current line. - /// - [DefaultValue(true)] - public virtual bool CutCopyWholeLine { - get { return cutCopyWholeLine; } - set { - if (cutCopyWholeLine != value) { - cutCopyWholeLine = value; - OnPropertyChanged("CutCopyWholeLine"); - } - } - } - - bool allowScrollBelowDocument; - - /// - /// 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. - /// - [DefaultValue(false)] - public virtual bool AllowScrollBelowDocument { - get { return allowScrollBelowDocument; } - set { - if (allowScrollBelowDocument != value) { - allowScrollBelowDocument = value; - OnPropertyChanged("AllowScrollBelowDocument"); - } - } - } - - double wordWrapIndentation = 0; - - /// - /// Gets/Sets the indentation used for all lines except the first when word-wrapping. - /// The default value is 0. - /// - [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; - - /// - /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. - /// The default value is true. - /// - /// When combined with , the inherited indentation is added to the word wrap indentation. - [DefaultValue(true)] - public virtual bool InheritWordWrapIndentation { - get { return inheritWordWrapIndentation; } - set { - if (value != inheritWordWrapIndentation) { - inheritWordWrapIndentation = value; - OnPropertyChanged("InheritWordWrapIndentation"); - } - } - } - - bool enableRectangularSelection = true; - - /// - /// Enables rectangular selection (press ALT and select a rectangle) - /// - [DefaultValue(true)] - public bool EnableRectangularSelection { - get { return enableRectangularSelection; } - set { - if (enableRectangularSelection != value) { - enableRectangularSelection = value; - OnPropertyChanged("EnableRectangularSelection"); - } - } - } - - bool enableTextDragDrop = true; - - /// - /// Enable dragging text within the text area. - /// - [DefaultValue(true)] - public bool EnableTextDragDrop { - get { return enableTextDragDrop; } - set { - if (enableTextDragDrop != value) { - enableTextDragDrop = value; - OnPropertyChanged("EnableTextDragDrop"); - } - } - } - - bool enableVirtualSpace; - - /// - /// 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. - /// - [DefaultValue(false)] - public virtual bool EnableVirtualSpace { - get { return enableVirtualSpace; } - set { - if (enableVirtualSpace != value) { - enableVirtualSpace = value; - OnPropertyChanged("EnableVirtualSpace"); - } - } - } - - bool enableImeSupport = true; - - /// - /// Gets/Sets whether the support for Input Method Editors (IME) - /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. - /// - [DefaultValue(true)] - public virtual bool EnableImeSupport { - get { return enableImeSupport; } - set { - if (enableImeSupport != value) { - enableImeSupport = value; - OnPropertyChanged("EnableImeSupport"); - } - } - } - - bool showColumnRuler = false; - - /// - /// Gets/Sets whether the column ruler should be shown. - /// - [DefaultValue(false)] - public virtual bool ShowColumnRuler { - get { return showColumnRuler; } - set { - if (showColumnRuler != value) { - showColumnRuler = value; - OnPropertyChanged("ShowColumnRuler"); - } - } - } - - int columnRulerPosition = 80; - - /// - /// Gets/Sets where the column ruler should be shown. - /// - [DefaultValue(80)] - public virtual int ColumnRulerPosition { - get { return columnRulerPosition; } - set { - if (columnRulerPosition != value) { - columnRulerPosition = value; - OnPropertyChanged("ColumnRulerPosition"); - } - } - } - - bool highlightCurrentLine = false; - - /// - /// Gets/Sets if current line should be shown. - /// - [DefaultValue(false)] - public virtual bool HighlightCurrentLine { - get { return highlightCurrentLine; } - set { - if (highlightCurrentLine != value) { - highlightCurrentLine = value; - OnPropertyChanged("HighlightCurrentLine"); - } - } - } - - bool hideCursorWhileTyping = true; - - /// - /// Gets/Sets if mouse cursor should be hidden while user is typing. - /// - [DefaultValue(true)] - public bool HideCursorWhileTyping { - get { return hideCursorWhileTyping; } - set { - if (hideCursorWhileTyping != value) { - hideCursorWhileTyping = value; - OnPropertyChanged("HideCursorWhileTyping"); - } - } - } - - bool allowToggleOverstrikeMode = false; - - /// - /// Gets/Sets if the user is allowed to enable/disable overstrike mode. - /// - [DefaultValue(false)] - public bool AllowToggleOverstrikeMode { - get { return allowToggleOverstrikeMode; } - set { - if (allowToggleOverstrikeMode != value) { - allowToggleOverstrikeMode = value; - OnPropertyChanged("AllowToggleOverstrikeMode"); - } - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorWeakEventManager.cs b/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorWeakEventManager.cs deleted file mode 100644 index 60c039a24..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorWeakEventManager.cs +++ /dev/null @@ -1,67 +0,0 @@ -// 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 -{ - /// - /// Contains weak event managers for . - /// - public static class TextEditorWeakEventManager - { - /// - /// Weak event manager for the event. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public sealed class DocumentChanged : WeakEventManagerBase - { - /// - protected override void StartListening(ITextEditorComponent source) - { - source.DocumentChanged += DeliverEvent; - } - - /// - protected override void StopListening(ITextEditorComponent source) - { - source.DocumentChanged -= DeliverEvent; - } - } - - /// - /// Weak event manager for the event. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public sealed class OptionChanged : WeakEventManagerBase - { - /// - protected override void StartListening(ITextEditorComponent source) - { - source.OptionChanged += DeliverEvent; - } - - /// - protected override void StopListening(ITextEditorComponent source) - { - source.OptionChanged -= DeliverEvent; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/TextViewPosition.cs b/AvalonEdit/ICSharpCode.AvalonEdit/TextViewPosition.cs deleted file mode 100644 index 3fcbfbf5f..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/TextViewPosition.cs +++ /dev/null @@ -1,199 +0,0 @@ -// 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 -{ - /// - /// Represents a text location with a visual column. - /// - public struct TextViewPosition : IEquatable, IComparable - { - int line, column, visualColumn; - bool isAtEndOfLine; - - /// - /// Gets/Sets Location. - /// - public TextLocation Location { - get { - return new TextLocation(line, column); - } - set { - line = value.Line; - column = value.Column; - } - } - - /// - /// Gets/Sets the line number. - /// - public int Line { - get { return line; } - set { line = value; } - } - - /// - /// Gets/Sets the (text) column number. - /// - public int Column { - get { return column; } - set { column = value; } - } - - /// - /// Gets/Sets the visual column number. - /// Can be -1 (meaning unknown visual column). - /// - public int VisualColumn { - get { return visualColumn; } - set { visualColumn = value; } - } - - /// - /// 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 true indicates that the position refers to the end of the previous TextLine; - /// the value false 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. - /// - public bool IsAtEndOfLine { - get { return isAtEndOfLine; } - set { isAtEndOfLine = value; } - } - - /// - /// Creates a new TextViewPosition instance. - /// - public TextViewPosition(int line, int column, int visualColumn) - { - this.line = line; - this.column = column; - this.visualColumn = visualColumn; - this.isAtEndOfLine = false; - } - - /// - /// Creates a new TextViewPosition instance. - /// - public TextViewPosition(int line, int column) - : this(line, column, -1) - { - } - - /// - /// Creates a new TextViewPosition instance. - /// - public TextViewPosition(TextLocation location, int visualColumn) - { - this.line = location.Line; - this.column = location.Column; - this.visualColumn = visualColumn; - this.isAtEndOfLine = false; - } - - /// - /// Creates a new TextViewPosition instance. - /// - public TextViewPosition(TextLocation location) - : this(location, -1) - { - } - - /// - 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" declaration. - - /// - public override bool Equals(object obj) - { - if (obj is TextViewPosition) - return Equals((TextViewPosition)obj); // use Equals method below - else - return false; - } - - /// - public override int GetHashCode() - { - int hashCode = isAtEndOfLine ? 115817 : 0; - unchecked { - hashCode += 1000000007 * Line.GetHashCode(); - hashCode += 1000000009 * Column.GetHashCode(); - hashCode += 1000000021 * VisualColumn.GetHashCode(); - } - return hashCode; - } - - /// - /// Equality test. - /// - public bool Equals(TextViewPosition other) - { - return this.Line == other.Line && this.Column == other.Column && this.VisualColumn == other.VisualColumn && this.IsAtEndOfLine == other.IsAtEndOfLine; - } - - /// - /// Equality test. - /// - public static bool operator ==(TextViewPosition left, TextViewPosition right) - { - return left.Equals(right); - } - - /// - /// Inequality test. - /// - public static bool operator !=(TextViewPosition left, TextViewPosition right) - { - return !(left.Equals(right)); // use operator == and negate result - } - #endregion - - /// - 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Boxes.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Boxes.cs deleted file mode 100644 index a74410ea9..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Boxes.cs +++ /dev/null @@ -1,36 +0,0 @@ -// 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 -{ - /// - /// Reuse the same instances for boxed booleans. - /// - 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/CallbackOnDispose.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/CallbackOnDispose.cs deleted file mode 100644 index ffcc717c1..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/CallbackOnDispose.cs +++ /dev/null @@ -1,101 +0,0 @@ -// 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 -{ - /// - /// Invokes an action when it is disposed. - /// - /// - /// This class ensures the callback is invoked at most once, - /// even when Dispose is called on multiple threads. - /// - 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(); - } - } - } - - /// - /// 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. - /// - 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 objectList; - - internal BusyLock(List 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 _activeObjects; - - public static BusyLock Enter(object obj) - { - List activeObjects = _activeObjects; - if (activeObjects == null) - activeObjects = _activeObjects = new List(); - for (int i = 0; i < activeObjects.Count; i++) { - if (activeObjects[i] == obj) - return BusyLock.Failed; - } - activeObjects.Add(obj); - return new BusyLock(activeObjects); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/CharRope.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/CharRope.cs deleted file mode 100644 index e787e7030..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/CharRope.cs +++ /dev/null @@ -1,226 +0,0 @@ -// 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 -{ - /// - /// Poor man's template specialization: extension methods for Rope<char>. - /// - public static class CharRope - { - /// - /// Creates a new rope from the specified text. - /// - public static Rope Create(string text) - { - if (text == null) - throw new ArgumentNullException("text"); - return new Rope(InitFromString(text)); - } - - /// - /// Retrieves the text for a portion of the rope. - /// Runs in O(lg N + M), where M=. - /// - /// offset or length is outside the valid range. - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - public static string ToString(this Rope 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); - } - - /// - /// 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=. - /// - /// offset or length is outside the valid range. - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - public static void WriteTo(this Rope 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); - } - - /// - /// Appends text to this rope. - /// Runs in O(lg N + M). - /// - /// newElements is null. - public static void AddText(this Rope rope, string text) - { - InsertText(rope, rope.Length, text); - } - - /// - /// Inserts text into this rope. - /// Runs in O(lg N + M). - /// - /// newElements is null. - /// index or length is outside the valid range. - public static void InsertText(this Rope 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 InitFromString(string text) - { - if (text.Length == 0) { - return RopeNode.emptyRopeNode; - } - RopeNode node = RopeNode.CreateNodes(text.Length); - FillNode(node, text, 0); - return node; - } - - static void FillNode(RopeNode 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 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); - } - } - } - - /// - /// Gets the index of the first occurrence of any element in the specified array. - /// - /// The target rope. - /// Array of characters being searched. - /// Start index of the search. - /// Length of the area to search. - /// The first index where any character was found; or -1 if no occurrence was found. - public static int IndexOfAny(this Rope 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; - } - - /// - /// Gets the index of the first occurrence of the search text. - /// - public static int IndexOf(this Rope 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; - } - - /// - /// Gets the index of the last occurrence of the search text. - /// - public static int LastIndexOf(this Rope 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/CompressingTreeList.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/CompressingTreeList.cs deleted file mode 100644 index eee2afaf6..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/CompressingTreeList.cs +++ /dev/null @@ -1,927 +0,0 @@ -// 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 -{ - /// - /// 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. - /// - /// - /// 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). - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", - Justification = "It's an IList implementation")] - public sealed class CompressingTreeList : IList - { - // 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; - } - } - - /// - /// Gets the inorder predecessor of the node. - /// - 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; - } - } - } - - /// - /// Gets the inorder successor of the node. - /// - 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 comparisonFunc; - Node root; - - /// - /// Creates a new CompressingTreeList instance. - /// - /// The equality comparer used for comparing consequtive values. - /// A single node may be used to store the multiple values that are considered equal. - public CompressingTreeList(IEqualityComparer equalityComparer) - { - if (equalityComparer == null) - throw new ArgumentNullException("equalityComparer"); - this.comparisonFunc = equalityComparer.Equals; - } - - /// - /// Creates a new CompressingTreeList instance. - /// - /// A function that checks two values for equality. If this - /// function returns true, a single node may be used to store the two values. - public CompressingTreeList(Func comparisonFunc) - { - if (comparisonFunc == null) - throw new ArgumentNullException("comparisonFunc"); - this.comparisonFunc = comparisonFunc; - } - #endregion - - #region InsertRange - /// - /// Inserts times at position - /// . - /// - 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 - /// - /// Removes items starting at position - /// . - /// - 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 - /// - /// Sets indices starting at to - /// - /// - 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 implementation - /// - /// Gets or sets an item by index. - /// - 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); - } - } - - /// - /// Gets the number of items in the list. - /// - public int Count { - get { - if (root != null) - return root.totalCount; - else - return 0; - } - } - - bool ICollection.IsReadOnly { - get { - return false; - } - } - - /// - /// Gets the index of the specified . - /// - 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; - } - - /// - /// Gets the the first index so that all values from the result index to - /// are equal. - /// - 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; - } - - /// - /// Gets the first index after so that the value at the result index is not - /// equal to the value at . - /// That is, this method returns the exclusive end index of the run of equal values. - /// - 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; - } - - /// - /// Gets the number of elements after that have the same value as each other. - /// - [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; - } - - /// - /// Applies the conversion function to all elements in this CompressingTreeList. - /// - public void Transform(Func 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(); - } - - /// - /// Applies the conversion function to the elements in the specified range. - /// - public void TransformRange(int index, int length, Func 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; - } - } - - /// - /// Inserts the specified at - /// - public void Insert(int index, T item) - { - InsertRange(index, 1, item); - } - - /// - /// Removes one item at - /// - public void RemoveAt(int index) - { - RemoveRange(index, 1); - } - - /// - /// Adds the specified to the end of the list. - /// - public void Add(T item) - { - InsertRange(this.Count, 1, item); - } - - /// - /// Removes all items from this list. - /// - public void Clear() - { - root = null; - } - - /// - /// Gets whether this list contains the specified item. - /// - public bool Contains(T item) - { - return IndexOf(item) >= 0; - } - - /// - /// Copies all items in this list to the specified array. - /// - 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; - } - } - - /// - /// Removes the specified item from this list. - /// - public bool Remove(T item) - { - int index = IndexOf(item); - if (index >= 0) { - RemoveAt(index); - return true; - } else { - return false; - } - } - #endregion - - #region IEnumerable - /// - /// Gets an enumerator for this list. - /// - public IEnumerator 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 ""; - 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Constants.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Constants.cs deleted file mode 100644 index 0249d957c..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Constants.cs +++ /dev/null @@ -1,30 +0,0 @@ -// 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 - { - /// - /// Multiply with this constant to convert from points to device-independent pixels. - /// - public const double PixelPerPoint = 4 / 3.0; - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/DelayedEvents.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/DelayedEvents.cs deleted file mode 100644 index 52aa2d47d..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/DelayedEvents.cs +++ /dev/null @@ -1,63 +0,0 @@ -// 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 -{ - /// - /// Maintains a list of delayed events to raise. - /// - 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 eventCalls = new Queue(); - - 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(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Deque.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Deque.cs deleted file mode 100644 index d67a6b17b..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Deque.cs +++ /dev/null @@ -1,189 +0,0 @@ -// 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 -{ - /// - /// Double-ended queue. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] - [Serializable] - public sealed class Deque : ICollection - { - T[] arr = Empty.Array; - int size, head, tail; - - /// - public int Count { - get { return size; } - } - - /// - public void Clear() - { - arr = Empty.Array; - size = 0; - head = 0; - tail = 0; - } - - /// - /// Gets/Sets an element inside the deque. - /// - 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; - } - } - - /// - /// Adds an element to the end of the deque. - /// - [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++; - } - - /// - /// Pops an element from the end of the deque. - /// - 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; - } - - /// - /// Adds an element to the front of the deque. - /// - 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++; - } - - /// - /// Pops an element from the end of the deque. - /// - 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; - } - - /// - public IEnumerator 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.IsReadOnly { - get { return false; } - } - - void ICollection.Add(T item) - { - PushBack(item); - } - - /// - public bool Contains(T item) - { - EqualityComparer comparer = EqualityComparer.Default; - foreach (T element in this) - if (comparer.Equals(item, element)) - return true; - return false; - } - - /// - 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.Remove(T item) - { - throw new NotSupportedException(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/DocumentPrinter.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/DocumentPrinter.cs deleted file mode 100644 index 49d3abc79..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/DocumentPrinter.cs +++ /dev/null @@ -1,122 +0,0 @@ -// 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 -{ - /// - /// Helps printing documents. - /// - public static class DocumentPrinter - { - #if NREFACTORY - /// - /// Converts a readonly TextDocument to a Block and applies the provided highlighting definition. - /// - 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 - - /// - /// Converts an IDocument to a Block and applies the provided highlighter. - /// - 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 - /// - /// Converts a readonly TextDocument to a RichText and applies the provided highlighting definition. - /// - 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 - - /// - /// Converts an IDocument to a RichText and applies the provided highlighter. - /// - public static RichText ConvertTextDocumentToRichText(IDocument document, IHighlighter highlighter) - { - if (document == null) - throw new ArgumentNullException("document"); - var texts = new List(); - 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()); - } - - /// - /// Creates a flow document from the editor's contents. - /// - 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; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Empty.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Empty.cs deleted file mode 100644 index e9d1935dd..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Empty.cs +++ /dev/null @@ -1,32 +0,0 @@ -// 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 -{ - /// - /// Provides immutable empty list instances. - /// - static class Empty - { - public static readonly T[] Array = new T[0]; - //public static readonly ReadOnlyCollection ReadOnlyCollection = new ReadOnlyCollection(Array); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/ExtensionMethods.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/ExtensionMethods.cs deleted file mode 100644 index 147d4e176..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/ExtensionMethods.cs +++ /dev/null @@ -1,237 +0,0 @@ -// 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 - /// - /// Epsilon used for IsClose() 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 - /// - public const double Epsilon = 0.01; - - /// - /// Returns true if the doubles are close (difference smaller than 0.01). - /// - public static bool IsClose(this double d1, double d2) - { - if (d1 == d2) // required for infinities - return true; - return Math.Abs(d1 - d2) < Epsilon; - } - - /// - /// Returns true if the doubles are close (difference smaller than 0.01). - /// - public static bool IsClose(this Size d1, Size d2) - { - return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); - } - - /// - /// Returns true if the doubles are close (difference smaller than 0.01). - /// - public static bool IsClose(this Vector d1, Vector d2) - { - return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); - } - - /// - /// Forces the value to stay between mininum and maximum. - /// - /// minimum, if value is less than minimum. - /// Maximum, if value is greater than maximum. - /// Otherwise, value. - public static double CoerceValue(this double value, double minimum, double maximum) - { - return Math.Max(Math.Min(value, maximum), minimum); - } - - /// - /// Forces the value to stay between mininum and maximum. - /// - /// minimum, if value is less than minimum. - /// Maximum, if value is greater than maximum. - /// Otherwise, value. - public static int CoerceValue(this int value, int minimum, int maximum) - { - return Math.Max(Math.Min(value, maximum), minimum); - } - #endregion - - #region CreateTypeface - /// - /// Creates typeface from the framework element. - /// - 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(this ICollection collection, IEnumerable elements) - { - foreach (T e in elements) - collection.Add(e); - } - - /// - /// Creates an IEnumerable with a single value. - /// - public static IEnumerable Sequence(T value) - { - yield return value; - } - #endregion - - #region XML reading - /// - /// Gets the value of the attribute, or null if the attribute does not exist. - /// - public static string GetAttributeOrNull(this XmlElement element, string attributeName) - { - XmlAttribute attr = element.GetAttributeNode(attributeName); - return attr != null ? attr.Value : null; - } - - /// - /// Gets the value of the attribute as boolean, or null if the attribute does not exist. - /// - public static bool? GetBoolAttribute(this XmlElement element, string attributeName) - { - XmlAttribute attr = element.GetAttributeNode(attributeName); - return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; - } - - /// - /// Gets the value of the attribute as boolean, or null if the attribute does not exist. - /// - 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 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); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/FileReader.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/FileReader.cs deleted file mode 100644 index a716b1a80..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/FileReader.cs +++ /dev/null @@ -1,240 +0,0 @@ -// 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 -{ - /// - /// Class that can open text files with auto-detection of the encoding. - /// - public static class FileReader - { - /// - /// Gets if the given encoding is a Unicode encoding (UTF). - /// - /// - /// 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. - /// - 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; - } - } - - /// - /// Reads the content of the given stream. - /// - /// The stream to read. - /// The stream must support seeking and must be positioned at its beginning. - /// The encoding to use if the encoding cannot be auto-detected. - /// The file content as string. - public static string ReadFileContent(Stream stream, Encoding defaultEncoding) - { - using (StreamReader reader = OpenStream(stream, defaultEncoding)) { - return reader.ReadToEnd(); - } - } - - /// - /// Reads the content of the file. - /// - /// The file name. - /// The encoding to use if the encoding cannot be auto-detected. - /// The file content as string. - public static string ReadFileContent(string fileName, Encoding defaultEncoding) - { - using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { - return ReadFileContent(fs, defaultEncoding); - } - } - - /// - /// Opens the specified file for reading. - /// - /// The file to open. - /// The encoding to use if the encoding cannot be auto-detected. - /// Returns a StreamReader that reads from the stream. Use - /// to get the encoding that was used. - 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; - } - } - - /// - /// Opens the specified stream for reading. - /// - /// The stream to open. - /// The encoding to use if the encoding cannot be auto-detected. - /// Returns a StreamReader that reads from the stream. Use - /// to get the encoding that was used. - 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); - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/IFreezable.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/IFreezable.cs deleted file mode 100644 index 1529e2942..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/IFreezable.cs +++ /dev/null @@ -1,123 +0,0 @@ -// 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 - { - /// - /// Gets if this instance is frozen. Frozen instances are immutable and thus thread-safe. - /// - bool IsFrozen { get; } - - /// - /// Freezes this instance. - /// - 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 FreezeListAndElements(IList list) - { - if (list != null) { - foreach (T item in list) - Freeze(item); - } - return FreezeList(list); - } - - public static IList FreezeList(IList list) - { - if (list == null || list.Count == 0) - return Empty.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(list.ToArray()); - } - } - - public static void Freeze(object item) - { - IFreezable f = item as IFreezable; - if (f != null) - f.Freeze(); - } - - public static T FreezeAndReturn(T item) where T : IFreezable - { - item.Freeze(); - return item; - } - - /// - /// 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. - /// - public static T GetFrozenClone(T item) where T : IFreezable, ICloneable - { - if (!item.IsFrozen) { - item = (T)item.Clone(); - item.Freeze(); - } - return item; - } - } - - [Serializable] - abstract class AbstractFreezable : IFreezable - { - bool isFrozen; - - /// - /// Gets if this instance is frozen. Frozen instances are immutable and thus thread-safe. - /// - public bool IsFrozen { - get { return isFrozen; } - } - - /// - /// Freezes this instance. - /// - public void Freeze() - { - if (!isFrozen) { - FreezeInternal(); - isFrozen = true; - } - } - - protected virtual void FreezeInternal() - { - } - } -} \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/ImmutableStack.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/ImmutableStack.cs deleted file mode 100644 index 17e717d28..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/ImmutableStack.cs +++ /dev/null @@ -1,132 +0,0 @@ -// 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 -{ - /// - /// An immutable stack. - /// - /// Using 'foreach' on the stack will return the items from top to bottom (in the order they would be popped). - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] - [Serializable] - public sealed class ImmutableStack : IEnumerable - { - /// - /// Gets the empty stack instance. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "ImmutableStack is immutable")] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] - public static readonly ImmutableStack Empty = new ImmutableStack(); - - readonly T value; - readonly ImmutableStack next; - - private ImmutableStack() - { - } - - private ImmutableStack(T value, ImmutableStack next) - { - this.value = value; - this.next = next; - } - - /// - /// Pushes an item on the stack. This does not modify the stack itself, but returns a new - /// one with the value pushed. - /// - public ImmutableStack Push(T item) - { - return new ImmutableStack(item, this); - } - - /// - /// Gets the item on the top of the stack. - /// - /// The stack is empty. - public T Peek() - { - if (IsEmpty) - throw new InvalidOperationException("Operation not valid on empty stack."); - return value; - } - - /// - /// Gets the item on the top of the stack. - /// Returns default(T) if the stack is empty. - /// - public T PeekOrDefault() - { - return value; - } - - /// - /// Gets the stack with the top item removed. - /// - /// The stack is empty. - public ImmutableStack Pop() - { - if (IsEmpty) - throw new InvalidOperationException("Operation not valid on empty stack."); - return next; - } - - /// - /// Gets if this stack is empty. - /// - public bool IsEmpty { - get { return next == null; } - } - - /// - /// Gets an enumerator that iterates through the stack top-to-bottom. - /// - public IEnumerator GetEnumerator() - { - ImmutableStack t = this; - while (!t.IsEmpty) { - yield return t.value; - t = t.next; - } - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return this.GetEnumerator(); - } - - /// - public override string ToString() - { - StringBuilder b = new StringBuilder("[Stack"); - foreach (T val in this) { - b.Append(' '); - b.Append(val); - } - b.Append(']'); - return b.ToString(); - } - } -} \ No newline at end of file diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/NullSafeCollection.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/NullSafeCollection.cs deleted file mode 100644 index dbfaadd9f..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/NullSafeCollection.cs +++ /dev/null @@ -1,46 +0,0 @@ -// 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 -{ - /// - /// A collection that cannot contain null values. - /// - [Serializable] - public class NullSafeCollection : Collection where T : class - { - /// - protected override void InsertItem(int index, T item) - { - if (item == null) - throw new ArgumentNullException("item"); - base.InsertItem(index, item); - } - - /// - protected override void SetItem(int index, T item) - { - if (item == null) - throw new ArgumentNullException("item"); - base.SetItem(index, item); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/ObserveAddRemoveCollection.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/ObserveAddRemoveCollection.cs deleted file mode 100644 index 7fa331294..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/ObserveAddRemoveCollection.cs +++ /dev/null @@ -1,89 +0,0 @@ -// 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 -{ - /// - /// 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. - /// - sealed class ObserveAddRemoveCollection : Collection - { - readonly Action onAdd, onRemove; - - /// - /// Creates a new ObserveAddRemoveCollection using the specified callbacks. - /// - public ObserveAddRemoveCollection(Action onAdd, Action onRemove) - { - if (onAdd == null) - throw new ArgumentNullException("onAdd"); - if (onRemove == null) - throw new ArgumentNullException("onRemove"); - this.onAdd = onAdd; - this.onRemove = onRemove; - } - - /// - protected override void ClearItems() - { - if (onRemove != null) { - foreach (T val in this) - onRemove(val); - } - base.ClearItems(); - } - - /// - protected override void InsertItem(int index, T item) - { - if (onAdd != null) - onAdd(item); - base.InsertItem(index, item); - } - - /// - protected override void RemoveItem(int index) - { - if (onRemove != null) - onRemove(this[index]); - base.RemoveItem(index); - } - - /// - 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); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/PixelSnapHelpers.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/PixelSnapHelpers.cs deleted file mode 100644 index 1fe7d99dd..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/PixelSnapHelpers.cs +++ /dev/null @@ -1,107 +0,0 @@ -// 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 -{ - /// - /// Contains static helper methods for aligning stuff on a whole number of pixels. - /// - public static class PixelSnapHelpers - { - /// - /// Gets the pixel size on the screen containing visual. - /// This method does not take transforms on visual into account. - /// - 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); - } - } - - /// - /// Aligns on the next middle of a pixel. - /// - /// The value that should be aligned - /// The size of one pixel - 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); - } - - /// - /// Aligns the borders of rect on the middles of pixels. - /// - 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; - } - - /// - /// Rounds to whole number of pixels. - /// - public static Point Round(Point point, Size pixelSize) - { - return new Point(Round(point.X, pixelSize.Width), Round(point.Y, pixelSize.Height)); - } - - /// - /// Rounds val to whole number of pixels. - /// - 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)); - } - - /// - /// Rounds to a whole number of pixels. - /// - public static double Round(double value, double pixelSize) - { - return pixelSize * Math.Round(value / pixelSize); - } - - /// - /// Rounds to an whole odd number of pixels. - /// - public static double RoundToOdd(double value, double pixelSize) - { - return Round(value - pixelSize, pixelSize * 2) + pixelSize; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/PlainRichTextWriter.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/PlainRichTextWriter.cs deleted file mode 100644 index 01146caa0..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/PlainRichTextWriter.cs +++ /dev/null @@ -1,140 +0,0 @@ -// 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 -{ - /// - /// RichTextWriter implementation that writes plain text only - /// and ignores all formatted spans. - /// - class PlainRichTextWriter : RichTextWriter - { - /// - /// The text writer that was passed to the PlainRichTextWriter constructor. - /// - protected readonly TextWriter textWriter; - string indentationString = "\t"; - int indentationLevel; - char prevChar; - - /// - /// Creates a new PlainRichTextWriter instance that writes the text to the specified text writer. - /// - public PlainRichTextWriter(TextWriter textWriter) - { - if (textWriter == null) - throw new ArgumentNullException("textWriter"); - this.textWriter = textWriter; - } - - /// - /// Gets/Sets the string used to indent by one level. - /// - public string IndentationString { - get { - return indentationString; - } - set { - indentationString = value; - } - } - - /// - protected override void BeginUnhandledSpan() - { - } - - /// - public override void EndSpan() - { - } - - void WriteIndentation() - { - for (int i = 0; i < indentationLevel; i++) { - textWriter.Write(indentationString); - } - } - - /// - /// Writes the indentation, if necessary. - /// - protected void WriteIndentationIfNecessary() - { - if (prevChar == '\n') { - WriteIndentation(); - prevChar = '\0'; - } - } - - /// - /// Is called after a write operation. - /// - protected virtual void AfterWrite() - { - } - - /// - public override void Write(char value) - { - if (prevChar == '\n') - WriteIndentation(); - textWriter.Write(value); - prevChar = value; - AfterWrite(); - } - - /// - public override void Indent() - { - indentationLevel++; - } - - /// - public override void Unindent() - { - if (indentationLevel == 0) - throw new NotSupportedException(); - indentationLevel--; - } - - /// - public override Encoding Encoding { - get { return textWriter.Encoding; } - } - - /// - public override IFormatProvider FormatProvider { - get { return textWriter.FormatProvider; } - } - - /// - public override string NewLine { - get { - return textWriter.NewLine; - } - set { - textWriter.NewLine = value; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/PropertyChangedWeakEventManager.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/PropertyChangedWeakEventManager.cs deleted file mode 100644 index c0d7394f3..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/PropertyChangedWeakEventManager.cs +++ /dev/null @@ -1,41 +0,0 @@ -// 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 -{ - /// - /// WeakEventManager for INotifyPropertyChanged.PropertyChanged. - /// - public sealed class PropertyChangedWeakEventManager : WeakEventManagerBase - { - /// - protected override void StartListening(INotifyPropertyChanged source) - { - source.PropertyChanged += DeliverEvent; - } - - /// - protected override void StopListening(INotifyPropertyChanged source) - { - source.PropertyChanged -= DeliverEvent; - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/RichTextWriter.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/RichTextWriter.cs deleted file mode 100644 index 2db6dd59c..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/RichTextWriter.cs +++ /dev/null @@ -1,124 +0,0 @@ -// 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) - - /// - /// A text writer that supports creating spans of highlighted text. - /// - abstract class RichTextWriter : TextWriter - { - /// - /// Gets called by the RichTextWriter base class when a BeginSpan() method - /// that is not overwritten gets called. - /// - protected abstract void BeginUnhandledSpan(); - - /// - /// Writes the RichText instance. - /// - public void Write(RichText richText) - { - Write(richText, 0, richText.Length); - } - - /// - /// Writes the RichText instance. - /// - 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(); - } - } - - /// - /// Begin a colored span. - /// - public virtual void BeginSpan(Color foregroundColor) - { - BeginUnhandledSpan(); - } - - /// - /// Begin a span with modified font weight. - /// - public virtual void BeginSpan(FontWeight fontWeight) - { - BeginUnhandledSpan(); - } - - /// - /// Begin a span with modified font style. - /// - public virtual void BeginSpan(FontStyle fontStyle) - { - BeginUnhandledSpan(); - } - - /// - /// Begin a span with modified font family. - /// - public virtual void BeginSpan(FontFamily fontFamily) - { - BeginUnhandledSpan(); - } - - /// - /// Begin a highlighted span. - /// - public virtual void BeginSpan(Highlighting.HighlightingColor highlightingColor) - { - BeginUnhandledSpan(); - } - - /// - /// Begin a span that links to the specified URI. - /// - public virtual void BeginHyperlinkSpan(Uri uri) - { - BeginUnhandledSpan(); - } - - /// - /// Marks the end of the current span. - /// - public abstract void EndSpan(); - - /// - /// Increases the indentation level. - /// - public abstract void Indent(); - - /// - /// Decreases the indentation level. - /// - public abstract void Unindent(); - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Rope.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Rope.cs deleted file mode 100644 index 2e489c236..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Rope.cs +++ /dev/null @@ -1,854 +0,0 @@ -// 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 -{ - /// - /// A kind of List<T>, but more efficient for random insertions/removal. - /// Also has cheap Clone() and SubRope() implementations. - /// - /// - /// 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. - /// - [Serializable] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] - public sealed class Rope : IList, ICloneable - { - internal RopeNode root; - - internal Rope(RopeNode root) - { - this.root = root; - root.CheckInvariants(); - } - - /// - /// Creates a new rope representing the empty string. - /// - public Rope() - { - // we'll construct the empty rope as a clone of an imaginary static empty rope - this.root = RopeNode.emptyRopeNode; - root.CheckInvariants(); - } - - /// - /// Creates a rope from the specified input. - /// This operation runs in O(N). - /// - /// input is null. - public Rope(IEnumerable input) - { - if (input == null) - throw new ArgumentNullException("input"); - Rope inputRope = input as Rope; - 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, then T must be char - ((Rope)(object)this).root = CharRope.InitFromString(text); - } else { - T[] arr = ToArray(input); - this.root = RopeNode.CreateFromArray(arr, 0, arr.Length); - } - } - this.root.CheckInvariants(); - } - - /// - /// Creates a rope from a part of the array. - /// This operation runs in O(N). - /// - /// input is null. - public Rope(T[] array, int arrayIndex, int count) - { - VerifyArrayWithRange(array, arrayIndex, count); - this.root = RopeNode.CreateFromArray(array, arrayIndex, count); - this.root.CheckInvariants(); - } - - /// - /// Creates a new rope that lazily initalizes its content. - /// - /// The length of the rope that will be lazily loaded. - /// - /// The callback that provides the content for this rope. - /// 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. - /// - /// - /// 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 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. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] - public Rope(int length, Func> 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.emptyRopeNode; - } else { - this.root = new FunctionNode(length, initializer); - } - this.root.CheckInvariants(); - } - - static T[] ToArray(IEnumerable input) - { - T[] arr = input as T[]; - return arr ?? input.ToArray(); - } - - /// - /// 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). - /// - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - public Rope 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(root); - } - - object ICloneable.Clone() - { - return this.Clone(); - } - - /// - /// Resets the rope to an empty list. - /// Runs in O(1). - /// - public void Clear() - { - root = RopeNode.emptyRopeNode; - OnChanged(); - } - - /// - /// Gets the length of the rope. - /// Runs in O(1). - /// - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - public int Length { - get { return root.length; } - } - - /// - /// Gets the length of the rope. - /// Runs in O(1). - /// - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - public int Count { - get { return root.length; } - } - - /// - /// Inserts another rope into this rope. - /// Runs in O(lg N + lg M), plus a per-node cost as if newElements.Clone() was called. - /// - /// newElements is null. - /// index or length is outside the valid range. - public void InsertRange(int index, Rope 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(); - } - - /// - /// 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. - /// - /// newElements is null. - /// index or length is outside the valid range. - public void InsertRange(int index, IEnumerable newElements) - { - if (newElements == null) - throw new ArgumentNullException("newElements"); - Rope newElementsRope = newElements as Rope; - if (newElementsRope != null) { - InsertRange(index, newElementsRope); - } else { - T[] arr = ToArray(newElements); - InsertRange(index, arr, 0, arr.Length); - } - } - - /// - /// 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. - /// - /// newElements is null. - /// index or length is outside the valid range. - 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(); - } - } - - /// - /// 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. - /// - /// newElements is null. - public void AddRange(IEnumerable newElements) - { - InsertRange(this.Length, newElements); - } - - /// - /// Appends another rope to the end of this rope. - /// Runs in O(lg N + lg M), plus a per-node cost as if newElements.Clone() was called. - /// - /// newElements is null. - public void AddRange(Rope newElements) - { - InsertRange(this.Length, newElements); - } - - /// - /// 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. - /// - /// array is null. - public void AddRange(T[] array, int arrayIndex, int count) - { - InsertRange(this.Length, array, arrayIndex, count); - } - - /// - /// Removes a range of elements from the rope. - /// Runs in O(lg N). - /// - /// offset or length is outside the valid range. - public void RemoveRange(int index, int count) - { - VerifyRange(index, count); - if (count > 0) { - root = root.RemoveRange(index, count); - OnChanged(); - } - } - - /// - /// Copies a range of the specified array into the rope, overwriting existing elements. - /// Runs in O(lg N + M). - /// - 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(); - } - } - - /// - /// 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 this.Clone() was called. - /// - /// offset or length is outside the valid range. - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - public Rope GetRange(int index, int count) - { - VerifyRange(index, count); - Rope newRope = Clone(); - int endIndex = index + count; - newRope.RemoveRange(endIndex, newRope.Length - endIndex); - newRope.RemoveRange(0, index); - return newRope; - } - - /* - #region Equality - /// - /// Gets whether the two ropes have the same content. - /// Runs in O(N + M). - /// - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - 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; - } - } - } - - /// - /// Gets whether two ropes have the same content. - /// Runs in O(N + M). - /// - public override bool Equals(object obj) - { - return Equals(obj as Rope); - } - - /// - /// Calculates the hash code of the rope's content. - /// Runs in O(N). - /// - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - 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 - */ - - /// - /// Concatenates two ropes. The input ropes are not modified. - /// Runs in O(lg N + lg M). - /// - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] - public static Rope Concat(Rope left, Rope right) - { - if (left == null) - throw new ArgumentNullException("left"); - if (right == null) - throw new ArgumentNullException("right"); - left.root.Publish(); - right.root.Publish(); - return new Rope(RopeNode.Concat(left.root, right.root)); - } - - /// - /// Concatenates multiple ropes. The input ropes are not modified. - /// - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] - public static Rope Concat(params Rope[] ropes) - { - if (ropes == null) - throw new ArgumentNullException("ropes"); - Rope result = new Rope(); - foreach (Rope r in ropes) - result.AddRange(r); - return result; - } - - #region Caches / Changed event - internal struct RopeCacheEntry - { - internal readonly RopeNode node; - internal readonly int nodeStartIndex; - - internal RopeCacheEntry(RopeNode 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 lastUsedNodeStack; - - internal void OnChanged() - { - lastUsedNodeStack = null; - - root.CheckInvariants(); - } - #endregion - - #region GetChar / SetChar - /// - /// 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). - /// - /// Offset is outside the valid range (0 to Length-1). - /// - /// The getter counts as a read access and may be called concurrently to other read accesses. - /// - 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 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 FindNodeUsingCache(int index) - { - Debug.Assert(index >= 0 && index < this.Length); - - // thread safety: fetch stack into local variable - ImmutableStack stack = lastUsedNodeStack; - ImmutableStack oldStack = stack; - - if (stack == null) { - stack = ImmutableStack.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)); - } - } - - /// - /// Creates a string from the rope. Runs in O(N). - /// - /// A string consisting of all elements in the rope as comma-separated list in {}. - /// As a special case, Rope<char> will return its contents as string without any additional separators or braces, - /// so it can be used like StringBuilder.ToString(). - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - public override string ToString() - { - Rope charRope = this as Rope; - 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.IsReadOnly { - get { return false; } - } - - /// - /// Finds the first occurance of item. - /// Runs in O(N). - /// - /// The index of the first occurance of item, or -1 if it cannot be found. - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - public int IndexOf(T item) - { - return IndexOf(item, 0, this.Length); - } - - /// - /// Gets the index of the first occurrence the specified item. - /// - /// Item to search for. - /// Start index of the search. - /// Length of the area to search. - /// The first index where the item was found; or -1 if no occurrence was found. - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - 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; - } - - /// - /// Gets the index of the last occurrence of the specified item in this rope. - /// - public int LastIndexOf(T item) - { - return LastIndexOf(item, 0, this.Length); - } - - /// - /// Gets the index of the last occurrence of the specified item in this rope. - /// - /// The search item - /// Start index of the area to search. - /// Length of the area to search. - /// The last index where the item was found; or -1 if no occurrence was found. - /// The search proceeds backwards from (startIndex+count) to startIndex. - /// This is different than the meaning of the parameters on Array.LastIndexOf! - public int LastIndexOf(T item, int startIndex, int count) - { - VerifyRange(startIndex, count); - - var comparer = EqualityComparer.Default; - for (int i = startIndex + count - 1; i >= startIndex; i--) { - if (comparer.Equals(this[i], item)) - return i; - } - return -1; - } - - /// - /// Inserts the item at the specified index in the rope. - /// Runs in O(lg N). - /// - public void Insert(int index, T item) - { - InsertRange(index, new[] { item }, 0, 1); - } - - /// - /// Removes a single item from the rope. - /// Runs in O(lg N). - /// - public void RemoveAt(int index) - { - RemoveRange(index, 1); - } - - /// - /// Appends the item at the end of the rope. - /// Runs in O(lg N). - /// - public void Add(T item) - { - InsertRange(this.Length, new[] { item }, 0, 1); - } - - /// - /// Searches the item in the rope. - /// Runs in O(N). - /// - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - public bool Contains(T item) - { - return IndexOf(item) >= 0; - } - - /// - /// Copies the whole content of the rope into the specified array. - /// Runs in O(N). - /// - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - public void CopyTo(T[] array, int arrayIndex) - { - CopyTo(0, array, arrayIndex, this.Length); - } - - /// - /// Copies the a part of the rope into the specified array. - /// Runs in O(lg N + M). - /// - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - 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); - } - - /// - /// Removes the first occurance of an item from the rope. - /// Runs in O(N). - /// - public bool Remove(T item) - { - int index = IndexOf(item); - if (index >= 0) { - RemoveAt(index); - return true; - } - return false; - } - - /// - /// 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. - /// - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - public IEnumerator GetEnumerator() - { - this.root.Publish(); - return Enumerate(root); - } - - /// - /// Creates an array and copies the contents of the rope into it. - /// Runs in O(N). - /// - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - public T[] ToArray() - { - T[] arr = new T[this.Length]; - this.root.CopyTo(0, arr, 0, arr.Length); - return arr; - } - - /// - /// Creates an array and copies the contents of the rope into it. - /// Runs in O(N). - /// - /// - /// This method counts as a read access and may be called concurrently to other read accesses. - /// - public T[] ToArray(int startIndex, int count) - { - VerifyRange(startIndex, count); - T[] arr = new T[count]; - CopyTo(startIndex, arr, 0, count); - return arr; - } - - static IEnumerator Enumerate(RopeNode node) - { - Stack> stack = new Stack>(); - 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(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/RopeNode.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/RopeNode.cs deleted file mode 100644 index c0afe9885..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/RopeNode.cs +++ /dev/null @@ -1,620 +0,0 @@ -// 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 - - [Serializable] - class RopeNode - { - internal const int NodeSize = 256; - - internal static readonly RopeNode emptyRopeNode = new RopeNode { isShared = true, contents = new T[RopeNode.NodeSize] }; - - // Fields for pointers to sub-nodes. Only non-null for concat nodes (height>=1) - internal RopeNode 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); - 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 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 { - length = this.length, - contents = newContents - }; - } else { - return new RopeNode { - left = this.left, - right = this.right, - length = this.length, - height = this.height - }; - } - } - - internal RopeNode 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 CreateFromArray(T[] arr, int index, int length) - { - if (length == 0) { - return emptyRopeNode; - } - RopeNode node = CreateNodes(length); - return node.StoreElements(0, arr, index, length); - } - - internal static RopeNode CreateNodes(int totalLength) - { - int leafCount = (totalLength + NodeSize - 1) / NodeSize; - return CreateNodes(leafCount, totalLength); - } - - static RopeNode CreateNodes(int leafCount, int totalLength) - { - Debug.Assert(leafCount > 0); - Debug.Assert(totalLength > 0); - RopeNode result = new RopeNode(); - 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; - } - - /// - /// 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. - /// - 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 a = left; - RopeNode b = right.left; - RopeNode c = right.right; - // reuse right concat node, if possible - this.left = right.isShared ? new RopeNode() : 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 a = left.left; - RopeNode b = left.right; - RopeNode c = right; - // reuse left concat node, if possible - this.right = left.isShared ? new RopeNode() : 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.Array; - #endif - } - this.left = null; - right.CopyTo(0, this.contents, lengthOnLeftSide, this.right.length); - this.right = null; - } - } - - /// - /// Copies from the array to this node. - /// - internal RopeNode StoreElements(int index, T[] array, int arrayIndex, int count) - { - RopeNode 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; - } - - /// - /// Copies from this node to the array. - /// - 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 SetElement(int offset, T value) - { - RopeNode 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 Concat(RopeNode left, RopeNode 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 concatNode = new RopeNode(); - concatNode.left = left; - concatNode.right = right; - concatNode.length = left.length + right.length; - concatNode.Rebalance(); - return concatNode; - } - } - - /// - /// Splits this leaf node at offset and returns a new node with the part of the text after offset. - /// - RopeNode SplitAfter(int offset) - { - Debug.Assert(!isShared && height == 0 && contents != null); - RopeNode newPart = new RopeNode(); - 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 Insert(int offset, RopeNode 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 result = CloneIfShared(); - if (result.height == 0) { - // leaf node: we'll need to split this node - RopeNode left = result; - RopeNode 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 Insert(int offset, T[] array, int arrayIndex, int count) - { - Debug.Assert(count > 0); - - if (this.length + count < RopeNode.NodeSize) { - RopeNode 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 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 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 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 - - /// - /// 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. - /// - internal virtual RopeNode GetContentNode() - { - throw new InvalidOperationException("Called GetContentNode() on non-FunctionNode."); - } - } - - sealed class FunctionNode : RopeNode - { - Func> initializer; - RopeNode cachedResults; - - public FunctionNode(int length, Func> 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 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> initializerCopy = this.initializer; - this.initializer = null; - Rope resultRope = initializerCopy(); - if (resultRope == null) - throw new InvalidOperationException("Rope initializer returned null."); - RopeNode 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 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 - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/RopeTextReader.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/RopeTextReader.cs deleted file mode 100644 index 43cd2bd81..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/RopeTextReader.cs +++ /dev/null @@ -1,120 +0,0 @@ -// 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 -{ - /// - /// TextReader implementation that reads text from a rope. - /// - public sealed class RopeTextReader : TextReader - { - Stack> stack = new Stack>(); - RopeNode currentNode; - int indexInsideNode; - - /// - /// 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. - /// - public RopeTextReader(Rope 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); - } - - /// - public override int Peek() - { - if (currentNode == null) - return -1; - return currentNode.contents[indexInsideNode]; - } - - /// - 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(); - } - } - - /// - 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; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/StringSegment.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/StringSegment.cs deleted file mode 100644 index e6de84e5b..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/StringSegment.cs +++ /dev/null @@ -1,122 +0,0 @@ -// 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 -{ - /// - /// Represents a string with a segment. - /// Similar to System.ArraySegment<T>, but for strings instead of arrays. - /// - public struct StringSegment : IEquatable - { - readonly string text; - readonly int offset; - readonly int count; - - /// - /// Creates a new StringSegment. - /// - 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; - } - - /// - /// Creates a new StringSegment. - /// - public StringSegment(string text) - { - if (text == null) - throw new ArgumentNullException("text"); - this.text = text; - this.offset = 0; - this.count = text.Length; - } - - /// - /// Gets the string used for this segment. - /// - public string Text { - get { return text; } - } - - /// - /// Gets the start offset of the segment with the text. - /// - public int Offset { - get { return offset; } - } - - /// - /// Gets the length of the segment. - /// - public int Count { - get { return count; } - } - - #region Equals and GetHashCode implementation - /// - public override bool Equals(object obj) - { - if (obj is StringSegment) - return Equals((StringSegment)obj); // use Equals method below - else - return false; - } - - /// - public bool Equals(StringSegment other) - { - // add comparisions for all members here - return object.ReferenceEquals(this.text, other.text) && offset == other.offset && count == other.count; - } - - /// - public override int GetHashCode() - { - return text.GetHashCode() ^ offset ^ count; - } - - /// - /// Equality operator. - /// - public static bool operator ==(StringSegment left, StringSegment right) - { - return left.Equals(right); - } - - /// - /// Inequality operator. - /// - public static bool operator !=(StringSegment left, StringSegment right) - { - return !left.Equals(right); - } - #endregion - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/TextFormatterFactory.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/TextFormatterFactory.cs deleted file mode 100644 index 96a662a2e..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/TextFormatterFactory.cs +++ /dev/null @@ -1,143 +0,0 @@ -// 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 -{ - /// - /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. - /// - 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 - - /// - /// Creates a using the formatting mode used by the specified owner object. - /// - 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 - } - - /// - /// Returns whether the specified dependency property affects the text formatter creation. - /// Controls should re-create their text formatter for such property changes. - /// - public static bool PropertyChangeAffectsTextFormatter(DependencyProperty dp) - { - #if DOTNET4 - return dp == TextOptions.TextFormattingModeProperty; - #else - return dp == TextFormattingModeProperty && TextFormattingModeProperty != null; - #endif - } - - /// - /// Creates formatted text. - /// - /// The owner element. The text formatter setting are read from this element. - /// The text. - /// The typeface to use. If this parameter is null, the typeface of the will be used. - /// The font size. If this parameter is null, the font size of the will be used. - /// The foreground color. If this parameter is null, the foreground of the will be used. - /// A FormattedText object using the specified settings. - 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 - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/ThrowUtil.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/ThrowUtil.cs deleted file mode 100644 index eaa7b0320..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/ThrowUtil.cs +++ /dev/null @@ -1,71 +0,0 @@ -// 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 -{ - /// - /// Contains exception-throwing helper methods. - /// - static class ThrowUtil - { - /// - /// Throws an ArgumentNullException if is null; otherwise - /// returns val. - /// - /// - /// Use this method to throw an ArgumentNullException when using parameters for base - /// constructor calls. - /// - /// public VisualLineText(string text) : base(ThrowUtil.CheckNotNull(text, "text").Length) - /// - /// - public static T CheckNotNull(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"); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/WeakEventManagerBase.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/WeakEventManagerBase.cs deleted file mode 100644 index 5cbde6743..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/WeakEventManagerBase.cs +++ /dev/null @@ -1,101 +0,0 @@ -// 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 -{ - /// - /// WeakEventManager with AddListener/RemoveListener and CurrentManager implementation. - /// Helps implementing the WeakEventManager pattern with less code. - /// - public abstract class WeakEventManagerBase : WeakEventManager - where TManager : WeakEventManagerBase, new() - where TEventSource : class - { - /// - /// Creates a new WeakEventManagerBase instance. - /// - protected WeakEventManagerBase() - { - Debug.Assert(GetType() == typeof(TManager)); - } - - /// - /// Adds a weak event listener. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] - public static void AddListener(TEventSource source, IWeakEventListener listener) - { - CurrentManager.ProtectedAddListener(source, listener); - } - - /// - /// Removes a weak event listener. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] - public static void RemoveListener(TEventSource source, IWeakEventListener listener) - { - CurrentManager.ProtectedRemoveListener(source, listener); - } - - /// - protected sealed override void StartListening(object source) - { - if (source == null) - throw new ArgumentNullException("source"); - StartListening((TEventSource)source); - } - - /// - protected sealed override void StopListening(object source) - { - if (source == null) - throw new ArgumentNullException("source"); - StopListening((TEventSource)source); - } - - /// - /// Attaches the event handler. - /// - protected abstract void StartListening(TEventSource source); - - /// - /// Detaches the event handler. - /// - protected abstract void StopListening(TEventSource source); - - /// - /// Gets the current manager. - /// - [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; - } - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Win32.cs b/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Win32.cs deleted file mode 100644 index 81340534e..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/Utils/Win32.cs +++ /dev/null @@ -1,100 +0,0 @@ -// 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 -{ - /// - /// Wrapper around Win32 functions. - /// - static class Win32 - { - /// - /// Gets the caret blink time. - /// - public static TimeSpan CaretBlinkTime { - get { return TimeSpan.FromMilliseconds(SafeNativeMethods.GetCaretBlinkTime()); } - } - - /// - /// Creates an invisible Win32 caret for the specified Visual with the specified size (coordinates local to the owner visual). - /// - 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; - } - } - - /// - /// Sets the position of the caret previously created using . position is relative to the owner visual. - /// - 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; - } - } - - /// - /// Destroys the caret previously created using . - /// - 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(); - } - } -} diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/themes/RightArrow.cur b/AvalonEdit/ICSharpCode.AvalonEdit/themes/RightArrow.cur deleted file mode 100644 index 5691efbaf8997b9957eff92ce6b842edf232689a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 326 zcmb8pF%H5o5Jb^2NTfj`6`~_0rH_z~>*NS@TnmYUYmh3fJ17vtUlJ*G)_NZA%91Uu zl+-lRR#HyVo;-n(S|rxLrWl)fw>>utP6zIWcsFc9Ev+*;6zPZ^Dny^4&>^D+#UB>c h!0r2_C;OLO7?!jBu0|K~h9}B2`;cEaT=BqQ{{a3le&zrG diff --git a/AvalonEdit/ICSharpCode.AvalonEdit/themes/generic.xaml b/AvalonEdit/ICSharpCode.AvalonEdit/themes/generic.xaml deleted file mode 100644 index 310539941..000000000 --- a/AvalonEdit/ICSharpCode.AvalonEdit/themes/generic.xaml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - diff --git a/AvalonEdit/copyright.txt b/AvalonEdit/copyright.txt deleted file mode 100644 index 055998e68..000000000 --- a/AvalonEdit/copyright.txt +++ /dev/null @@ -1,10 +0,0 @@ -Copyright 2002-2012 by - - AlphaSierraPapa, Christoph Wille - Vordernberger Strasse 27/8 - A-8700 Leoben - Austria - - email: office@alphasierrapapa.com - court of jurisdiction: Landesgericht Leoben - diff --git a/AvalonEdit/license.txt b/AvalonEdit/license.txt deleted file mode 100644 index e8fd74ca4..000000000 --- a/AvalonEdit/license.txt +++ /dev/null @@ -1,458 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS diff --git a/Mono.Cecil/.gitignore b/Mono.Cecil/.gitignore deleted file mode 100644 index 8dcb32b7f..000000000 --- a/Mono.Cecil/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -bin -obj -*.suo -*.user -*.pidb -*.userprefs -*.xml -*.nupkg -**/test-results/* -*Resharper* diff --git a/Mono.Cecil/Mono.Cecil.Cil/Code.cs b/Mono.Cecil/Mono.Cecil.Cil/Code.cs deleted file mode 100644 index fa88b63d6..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/Code.cs +++ /dev/null @@ -1,252 +0,0 @@ -// -// 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, - } -} diff --git a/Mono.Cecil/Mono.Cecil.Cil/CodeReader.cs b/Mono.Cecil/Mono.Cecil.Cil/CodeReader.cs deleted file mode 100644 index 12ca5a23b..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/CodeReader.cs +++ /dev/null @@ -1,598 +0,0 @@ -// -// 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.symbol_reader; - - 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 + 1) / 2); - - 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 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 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 read_entry, Func 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.symbol_reader; - 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 - - } -} diff --git a/Mono.Cecil/Mono.Cecil.Cil/CodeWriter.cs b/Mono.Cecil/Mono.Cecil.Cil/CodeWriter.cs deleted file mode 100644 index ac093cae4..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/CodeWriter.cs +++ /dev/null @@ -1,649 +0,0 @@ -// -// 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 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 (); - } - - 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 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 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 stack_sizes) - { - if (handler_start == null) - return; - - if (stack_sizes == null) - stack_sizes = new Dictionary (); - - stack_sizes [handler_start] = 1; - } - - static void ComputeStackSize (Instruction instruction, ref Dictionary 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 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 stack_sizes, Instruction target, int stack_size) - { - if (stack_sizes == null) - stack_sizes = new Dictionary (); - - 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; - // pop 'this' argument - if (method.HasImplicitThis() && instruction.opcode.Code != Code.Newobj) - stack_size--; - // pop normal arguments - if (method.HasParameters) - stack_size -= method.Parameters.Count; - // pop function pointer - if (instruction.opcode.Code == Code.Calli) - stack_size--; - // push return value - if (method.ReturnType.etype != ElementType.Void || instruction.opcode.Code == Code.Newobj) - stack_size++; - 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 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 (start == null) - throw new ArgumentException (); - - if (end == null) - return true; - - return end.Offset - start.Offset > 255 || start.Offset > 65535; - } - - void WriteSmallSection (Collection 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 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 handlers, Action write_entry, Action 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 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 diff --git a/Mono.Cecil/Mono.Cecil.Cil/Document.cs b/Mono.Cecil/Mono.Cecil.Cil/Document.cs deleted file mode 100644 index 1dbdc4474..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/Document.cs +++ /dev/null @@ -1,112 +0,0 @@ -// -// 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, - FSharp, - } - - 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.Array; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Cil/ExceptionHandler.cs b/Mono.Cecil/Mono.Cecil.Cil/ExceptionHandler.cs deleted file mode 100644 index c61ff235e..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/ExceptionHandler.cs +++ /dev/null @@ -1,89 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Cil/ILProcessor.cs b/Mono.Cecil/Mono.Cecil.Cil/ILProcessor.cs deleted file mode 100644 index cd5dbb40f..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/ILProcessor.cs +++ /dev/null @@ -1,278 +0,0 @@ -// -// 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 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"); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Cil/Instruction.cs b/Mono.Cecil/Mono.Cecil.Cil/Instruction.cs deleted file mode 100644 index c28d4c992..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/Instruction.cs +++ /dev/null @@ -1,321 +0,0 @@ -// -// 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); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Cil/MethodBody.cs b/Mono.Cecil/Mono.Cecil.Cil/MethodBody.cs deleted file mode 100644 index c65c12269..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/MethodBody.cs +++ /dev/null @@ -1,247 +0,0 @@ -// -// 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 System.Threading; - -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 instructions; - internal Collection exceptions; - internal Collection 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 Instructions { - get { return instructions ?? (instructions = new InstructionCollection ()); } - } - - public bool HasExceptionHandlers { - get { return !exceptions.IsNullOrEmpty (); } - } - - public Collection ExceptionHandlers { - get { return exceptions ?? (exceptions = new Collection ()); } - } - - public bool HasVariables { - get { return !variables.IsNullOrEmpty (); } - } - - public Collection 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 (); - - if (!method.HasThis) - return null; - - if (this_parameter == null) - Interlocked.CompareExchange (ref this_parameter, ThisParameterFor (method), null); - - return this_parameter; - } - } - - static ParameterDefinition ThisParameterFor (MethodDefinition method) - { - var declaring_type = method.DeclaringType; - var type = declaring_type.IsValueType || declaring_type.IsPrimitive - ? new PointerType (declaring_type) - : declaring_type as TypeReference; - - return new ParameterDefinition (type, method); - } - - public MethodBody (MethodDefinition method) - { - this.method = method; - } - - public ILProcessor GetILProcessor () - { - return new ILProcessor (this); - } - } - - public interface IVariableDefinitionProvider { - bool HasVariables { get; } - Collection Variables { get; } - } - - class VariableDefinitionCollection : Collection { - - 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 { - - 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Cil/OpCode.cs b/Mono.Cecil/Mono.Cecil.Cil/OpCode.cs deleted file mode 100644 index 1a1442130..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/OpCode.cs +++ /dev/null @@ -1,455 +0,0 @@ -// -// 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); - } - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Cil/OpCodes.cs b/Mono.Cecil/Mono.Cecil.Cil/OpCodes.cs deleted file mode 100644 index 85712ec8b..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/OpCodes.cs +++ /dev/null @@ -1,912 +0,0 @@ -// -// 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); - } -} diff --git a/Mono.Cecil/Mono.Cecil.Cil/SequencePoint.cs b/Mono.Cecil/Mono.Cecil.Cil/SequencePoint.cs deleted file mode 100644 index ef87e30f1..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/SequencePoint.cs +++ /dev/null @@ -1,70 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Cil/Symbols.cs b/Mono.Cecil/Mono.Cecil.Cil/Symbols.cs deleted file mode 100644 index 426c4a7e1..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/Symbols.cs +++ /dev/null @@ -1,277 +0,0 @@ -// -// 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 scopes; - Collection 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 Scopes { - get { - if (scopes == null) - scopes = new Collection (); - - return scopes; - } - } - - public bool HasVariables { - get { return !variables.IsNullOrEmpty (); } - } - - public Collection Variables { - get { - if (variables == null) - variables = new Collection (); - - 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 variables; - internal Collection instructions; - - public bool HasVariables { - get { return !variables.IsNullOrEmpty (); } - } - - public Collection Variables { - get { - if (variables == null) - variables = new Collection (); - - return variables; - } - } - - public Collection Instructions { - get { - if (instructions == null) - instructions = new Collection (); - - 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 -} diff --git a/Mono.Cecil/Mono.Cecil.Cil/VariableDefinition.cs b/Mono.Cecil/Mono.Cecil.Cil/VariableDefinition.cs deleted file mode 100644 index f501bca6e..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/VariableDefinition.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Cil/VariableReference.cs b/Mono.Cecil/Mono.Cecil.Cil/VariableReference.cs deleted file mode 100644 index ce0b4cdb4..000000000 --- a/Mono.Cecil/Mono.Cecil.Cil/VariableReference.cs +++ /dev/null @@ -1,75 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Metadata/BlobHeap.cs b/Mono.Cecil/Mono.Cecil.Metadata/BlobHeap.cs deleted file mode 100644 index e7e2928c8..000000000 --- a/Mono.Cecil/Mono.Cecil.Metadata/BlobHeap.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// 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.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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Metadata/Buffers.cs b/Mono.Cecil/Mono.Cecil.Metadata/Buffers.cs deleted file mode 100644 index b63412dea..000000000 --- a/Mono.Cecil/Mono.Cecil.Metadata/Buffers.cs +++ /dev/null @@ -1,373 +0,0 @@ -// -// 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 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 (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 (Table.FieldRVA); - if (table.length == 0) - return; - - var field_idx_size = GetTable (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 strings = new Dictionary (StringComparer.Ordinal); - - 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 blobs = new Dictionary (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 diff --git a/Mono.Cecil/Mono.Cecil.Metadata/CodedIndex.cs b/Mono.Cecil/Mono.Cecil.Metadata/CodedIndex.cs deleted file mode 100644 index 3e30fd87f..000000000 --- a/Mono.Cecil/Mono.Cecil.Metadata/CodedIndex.cs +++ /dev/null @@ -1,46 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil.Metadata/ElementType.cs b/Mono.Cecil/Mono.Cecil.Metadata/ElementType.cs deleted file mode 100644 index 72fc1ccaf..000000000 --- a/Mono.Cecil/Mono.Cecil.Metadata/ElementType.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -// 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 token - ByRef = 0x10, // Followed by token - ValueType = 0x11, // Followed by token - Class = 0x12, // Followed by token - Var = 0x13, // Followed by generic parameter number - Array = 0x14, // - GenericInst = 0x15, // ... */ - 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil.Metadata/GuidHeap.cs b/Mono.Cecil/Mono.Cecil.Metadata/GuidHeap.cs deleted file mode 100644 index 1adc0795e..000000000 --- a/Mono.Cecil/Mono.Cecil.Metadata/GuidHeap.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// 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); - - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Metadata/Heap.cs b/Mono.Cecil/Mono.Cecil.Metadata/Heap.cs deleted file mode 100644 index bc21acde2..000000000 --- a/Mono.Cecil/Mono.Cecil.Metadata/Heap.cs +++ /dev/null @@ -1,48 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Metadata/MetadataToken.cs b/Mono.Cecil/Mono.Cecil.Metadata/MetadataToken.cs deleted file mode 100644 index bda56b0f4..000000000 --- a/Mono.Cecil/Mono.Cecil.Metadata/MetadataToken.cs +++ /dev/null @@ -1,105 +0,0 @@ -// -// 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")); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Metadata/Row.cs b/Mono.Cecil/Mono.Cecil.Metadata/Row.cs deleted file mode 100644 index dfda00a77..000000000 --- a/Mono.Cecil/Mono.Cecil.Metadata/Row.cs +++ /dev/null @@ -1,170 +0,0 @@ -// -// 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 { - internal T1 Col1; - internal T2 Col2; - - public Row (T1 col1, T2 col2) - { - Col1 = col1; - Col2 = col2; - } - } - - struct Row { - 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 { - 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 { - 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 { - 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 { - 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>, IEqualityComparer>, IEqualityComparer> { - - public bool Equals (Row x, Row y) - { - return x.Col1 == y.Col1 - && x.Col2 == y.Col2; - } - - public int GetHashCode (Row obj) - { - string x = obj.Col1, y = obj.Col2; - return (x != null ? x.GetHashCode () : 0) ^ (y != null ? y.GetHashCode () : 0); - } - - public bool Equals (Row x, Row y) - { - return x.Col1 == y.Col1 - && x.Col2 == y.Col2; - } - - public int GetHashCode (Row obj) - { - return (int) (obj.Col1 ^ obj.Col2); - } - - public bool Equals (Row x, Row y) - { - return x.Col1 == y.Col1 - && x.Col2 == y.Col2 - && x.Col3 == y.Col3; - } - - public int GetHashCode (Row obj) - { - return (int) (obj.Col1 ^ obj.Col2 ^ obj.Col3); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Metadata/StringHeap.cs b/Mono.Cecil/Mono.Cecil.Metadata/StringHeap.cs deleted file mode 100644 index 4a0a0af43..000000000 --- a/Mono.Cecil/Mono.Cecil.Metadata/StringHeap.cs +++ /dev/null @@ -1,81 +0,0 @@ -// -// 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 strings = new Dictionary (); - - 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); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Metadata/TableHeap.cs b/Mono.Cecil/Mono.Cecil.Metadata/TableHeap.cs deleted file mode 100644 index 9bc0edd36..000000000 --- a/Mono.Cecil/Mono.Cecil.Metadata/TableHeap.cs +++ /dev/null @@ -1,111 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Metadata/TokenType.cs b/Mono.Cecil/Mono.Cecil.Metadata/TokenType.cs deleted file mode 100644 index 2c2010ff9..000000000 --- a/Mono.Cecil/Mono.Cecil.Metadata/TokenType.cs +++ /dev/null @@ -1,56 +0,0 @@ -// -// 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, - } -} diff --git a/Mono.Cecil/Mono.Cecil.Metadata/UserStringHeap.cs b/Mono.Cecil/Mono.Cecil.Metadata/UserStringHeap.cs deleted file mode 100644 index 59105087f..000000000 --- a/Mono.Cecil/Mono.Cecil.Metadata/UserStringHeap.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// 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); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.Metadata/Utilities.cs b/Mono.Cecil/Mono.Cecil.Metadata/Utilities.cs deleted file mode 100644 index d752b24b1..000000000 --- a/Mono.Cecil/Mono.Cecil.Metadata/Utilities.cs +++ /dev/null @@ -1,529 +0,0 @@ -// -// 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 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.PE/BinaryStreamReader.cs b/Mono.Cecil/Mono.Cecil.PE/BinaryStreamReader.cs deleted file mode 100644 index ec2477c3a..000000000 --- a/Mono.Cecil/Mono.Cecil.PE/BinaryStreamReader.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// 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 ()); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.PE/BinaryStreamWriter.cs b/Mono.Cecil/Mono.Cecil.PE/BinaryStreamWriter.cs deleted file mode 100644 index 2bf6cccfa..000000000 --- a/Mono.Cecil/Mono.Cecil.PE/BinaryStreamWriter.cs +++ /dev/null @@ -1,96 +0,0 @@ -// -// 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 diff --git a/Mono.Cecil/Mono.Cecil.PE/ByteBuffer.cs b/Mono.Cecil/Mono.Cecil.PE/ByteBuffer.cs deleted file mode 100644 index c7ae7aee1..000000000 --- a/Mono.Cecil/Mono.Cecil.PE/ByteBuffer.cs +++ /dev/null @@ -1,359 +0,0 @@ -// -// 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.Array; - } - - public ByteBuffer (int length) - { - this.buffer = new byte [length]; - } - - public ByteBuffer (byte [] buffer) - { - this.buffer = buffer ?? Empty.Array; - this.length = this.buffer.Length; - } - - public void Reset (byte [] buffer) - { - this.buffer = buffer ?? Empty.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 () >> 1); - if ((value & 1) == 0) - return value; - if (value < 0x40) - return value - 0x40; - if (value < 0x2000) - return value - 0x2000; - if (value < 0x10000000) - return value - 0x10000000; - return value - 0x20000000; - } - - 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) - { - if (value >= 0) { - WriteCompressedUInt32 ((uint) (value << 1)); - return; - } - - if (value > -0x40) - value = 0x40 + value; - else if (value >= -0x2000) - value = 0x2000 + value; - else if (value >= -0x20000000) - value = 0x20000000 + value; - - WriteCompressedUInt32 ((uint) ((value << 1) | 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 - - } -} diff --git a/Mono.Cecil/Mono.Cecil.PE/ByteBufferEqualityComparer.cs b/Mono.Cecil/Mono.Cecil.PE/ByteBufferEqualityComparer.cs deleted file mode 100644 index 70e89164c..000000000 --- a/Mono.Cecil/Mono.Cecil.PE/ByteBufferEqualityComparer.cs +++ /dev/null @@ -1,78 +0,0 @@ -// -// 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 { - - 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 - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.PE/DataDirectory.cs b/Mono.Cecil/Mono.Cecil.PE/DataDirectory.cs deleted file mode 100644 index fedd0e2dd..000000000 --- a/Mono.Cecil/Mono.Cecil.PE/DataDirectory.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.PE/Image.cs b/Mono.Cecil/Mono.Cecil.PE/Image.cs deleted file mode 100644 index a11cf1c40..000000000 --- a/Mono.Cecil/Mono.Cecil.PE/Image.cs +++ /dev/null @@ -1,161 +0,0 @@ -// -// 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 ModuleCharacteristics Characteristics; - public string FileName; - - public Section [] Sections; - - public Section MetadataSection; - - public uint EntryPointToken; - public ModuleAttributes Attributes; - - public DataDirectory Debug; - public DataDirectory Resources; - public DataDirectory StrongName; - - 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 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.PE/ImageReader.cs b/Mono.Cecil/Mono.Cecil.PE/ImageReader.cs deleted file mode 100644 index c96c1db31..000000000 --- a/Mono.Cecil/Mono.Cecil.PE/ImageReader.cs +++ /dev/null @@ -1,681 +0,0 @@ -// -// 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, dll_characteristics; - ReadOptionalHeaders (out subsystem, out dll_characteristics); - ReadSections (sections); - ReadCLIHeader (); - ReadMetadata (); - - image.Kind = GetModuleKind (characteristics, subsystem); - image.Characteristics = (ModuleCharacteristics) dll_characteristics; - } - - TargetArchitecture ReadArchitecture () - { - var machine = ReadUInt16 (); - switch (machine) { - case 0x014c: - return TargetArchitecture.I386; - case 0x8664: - return TargetArchitecture.AMD64; - case 0x0200: - return TargetArchitecture.IA64; - case 0x01c4: - return TargetArchitecture.ARMv7; - } - - 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, out ushort dll_characteristics) - { - // - 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 - dll_characteristics = ReadUInt16 (); - // 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 ? 88 : 72); - - // 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; - - 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 - image.StrongName = ReadDataDirectory (); - // 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); - } - } - } -} diff --git a/Mono.Cecil/Mono.Cecil.PE/ImageWriter.cs b/Mono.Cecil/Mono.Cecil.PE/ImageWriter.cs deleted file mode 100644 index c62427c6a..000000000 --- a/Mono.Cecil/Mono.Cecil.PE/ImageWriter.cs +++ /dev/null @@ -1,824 +0,0 @@ -// -// 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.pe64 = module.Architecture != TargetArchitecture.I386; - this.GetDebugHeader (); - this.GetWin32Resources (); - this.text_map = BuildTextMap (); - this.sections = (ushort) (pe64 ? 1 : 2); // text + reloc - 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.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; - } - - if (!pe64) - 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 (); - } - - Section LastSection () - { - if (reloc != null) - return reloc; - - if (rsrc != null) - return rsrc; - - return text; - } - - void WriteOptionalHeaders () - { - WriteUInt16 ((ushort) (!pe64 ? 0x10b : 0x20b)); // Magic - WriteByte (8); // LMajor - WriteByte (0); // LMinor - WriteUInt32 (text.SizeOfRawData); // CodeSize - WriteUInt32 ((reloc != null ? reloc.SizeOfRawData : 0) - + (rsrc != null ? rsrc.SizeOfRawData : 0)); // InitializedDataSize - WriteUInt32 (0); // UninitializedDataSize - - var startub_stub = text_map.GetRange (TextSegment.StartupStub); - WriteUInt32 (startub_stub.Length > 0 ? startub_stub.Start : 0); // 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 - - var last_section = LastSection(); - WriteUInt32 (last_section.VirtualAddress + Align (last_section.VirtualSize, section_alignment)); // ImageSize - WriteUInt32 (text.PointerToRawData); // HeaderSize - - WriteUInt32 (0); // Checksum - WriteUInt16 (GetSubSystem ()); // SubSystem - WriteUInt16 ((ushort) module.Characteristics); // 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 != null ? reloc.VirtualAddress : 0); // BaseRelocationTable - WriteUInt32 (reloc != null ? reloc.VirtualSize : 0); - - 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); - - if (reloc != null) - 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 - - if (!pe64) { - 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 (); - } - - if (pe64) - return; - - // 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; - default: - throw new NotSupportedException (); - } - } - - 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; - default: - throw new NotSupportedException(); - } - - WriteBytes (new byte [file_alignment - reloc.VirtualSize]); - } - - public void WriteImage () - { - WriteDOSHeader (); - WritePEFileHeader (); - WriteOptionalHeaders (); - WriteSectionHeaders (); - WriteText (); - if (rsrc != null) - WriteRsrc (); - if (reloc != null) - 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); - - if (pe64) { - var start = map.GetNextRVA (TextSegment.DebugDirectory); - map.AddMap (TextSegment.ImportDirectory, new Range (start, 0)); - map.AddMap (TextSegment.ImportHintNameTable, new Range (start, 0)); - map.AddMap (TextSegment.StartupStub, new Range (start, 0)); - return map; - } - - RVA import_dir_rva = map.GetNextRVA (TextSegment.DebugDirectory); - RVA import_hnt_rva = import_dir_rva + 48u; - 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; - default: - throw new NotSupportedException (); - } - } - - 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.Assembly == null) - return 0; - - var public_key = module.Assembly.Name.PublicKey; - if (public_key.IsNullOrEmpty ()) - return 0; - - // 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 diff --git a/Mono.Cecil/Mono.Cecil.PE/Section.cs b/Mono.Cecil/Mono.Cecil.PE/Section.cs deleted file mode 100644 index 6a4c7bab7..000000000 --- a/Mono.Cecil/Mono.Cecil.PE/Section.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// 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; - } -} diff --git a/Mono.Cecil/Mono.Cecil.PE/TextMap.cs b/Mono.Cecil/Mono.Cecil.PE/TextMap.cs deleted file mode 100644 index 047a4c1d4..000000000 --- a/Mono.Cecil/Mono.Cecil.PE/TextMap.cs +++ /dev/null @@ -1,129 +0,0 @@ -// -// 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 diff --git a/Mono.Cecil/Mono.Cecil.csproj b/Mono.Cecil/Mono.Cecil.csproj deleted file mode 100644 index 3a237c11b..000000000 --- a/Mono.Cecil/Mono.Cecil.csproj +++ /dev/null @@ -1,264 +0,0 @@ - - - - net_4_0_Debug - AnyCPU - 9.0.30729 - 2.0 - {D68133BD-1E63-496E-9EDE-4FBDBF77B486} - Library - Properties - Mono.Cecil - Mono.Cecil - 512 - true - mono.snk - - - true - full - false - bin\net_2_0_Debug\ - DEBUG;TRACE - prompt - 4 - v2.0 - - - pdbonly - true - bin\net_2_0_Release\ - TRACE - prompt - 4 - v2.0 - - - true - full - false - bin\net_3_5_Debug\ - DEBUG;TRACE;NET_3_5 - prompt - 4 - v3.5 - - - pdbonly - true - bin\net_3_5_Release\ - TRACE;NET_3_5 - prompt - 4 - v3.5 - - - true - full - false - bin\net_4_0_Debug\ - DEBUG;TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - pdbonly - true - bin\net_4_0_Release\ - TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - true - full - false - bin\silverlight_Debug\ - DEBUG;TRACE;NET_3_5;NET_4_0;SILVERLIGHT - prompt - 4 - Silverlight - v4.0 - - - pdbonly - true - bin\silverlight_Release\ - TRACE;NET_3_5;NET_4_0;SILVERLIGHT - prompt - 4 - Silverlight - v4.0 - - - true - full - false - bin\winphone_Debug\ - DEBUG;TRACE;NET_3_5;NET_4_0;SILVERLIGHT;CF - prompt - 4 - WindowsPhone - Silverlight - v4.0 - - - pdbonly - true - bin\winphone_Release\ - TRACE;NET_3_5;NET_4_0;SILVERLIGHT;CF - prompt - 4 - WindowsPhone - Silverlight - v4.0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Mono.Cecil/Mono.Cecil.nunit b/Mono.Cecil/Mono.Cecil.nunit deleted file mode 100755 index 1cb0ebab1..000000000 --- a/Mono.Cecil/Mono.Cecil.nunit +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/Mono.Cecil/Mono.Cecil.nuspec b/Mono.Cecil/Mono.Cecil.nuspec deleted file mode 100644 index ffab04f49..000000000 --- a/Mono.Cecil/Mono.Cecil.nuspec +++ /dev/null @@ -1,23 +0,0 @@ - - - - Mono.Cecil - 0.9.5.3 - Mono.Cecil - Jb Evain - Jb Evain - http://opensource.org/licenses/mit-license.php - false - http://github.com/jbevain/cecil/ - Cecil is a library written by Jb Evain to generate and inspect programs and libraries in the ECMA CIL format. - Cecil is a library written by Jb Evain to generate and inspect programs and libraries in the ECMA CIL format. It has full support for generics, and support some debugging symbol format. In simple English, with Cecil, you can load existing managed assemblies, browse all the contained types, modify them on the fly and save back to the disk the modified assembly. - en-US - assembly assemblies module modules il cil msil bytecode reflection injection cecil mono aop - - - - - - - - diff --git a/Mono.Cecil/Mono.Cecil.sln b/Mono.Cecil/Mono.Cecil.sln deleted file mode 100644 index 7f2eda7f9..000000000 --- a/Mono.Cecil/Mono.Cecil.sln +++ /dev/null @@ -1,197 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{74E5ECE0-06B4-401C-AEBA-E8DD53E17943}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Symbols", "Symbols", "{929D5B3B-E29A-40CC-93D8-0FF43A6F9FA1}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Cecil", "Mono.Cecil.csproj", "{D68133BD-1E63-496E-9EDE-4FBDBF77B486}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Cecil.Tests", "Test\Mono.Cecil.Tests.csproj", "{A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dbg", "dbg\dbg.csproj", "{89A775F3-64AB-485E-B958-60C25254B732}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Cecil.Mdb", "symbols\mdb\Mono.Cecil.Mdb.csproj", "{8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Cecil.Mdb.Tests", "symbols\mdb\Test\Mono.Cecil.Mdb.Tests.csproj", "{AC71DF9C-99FA-4A63-990A-66C8010355A6}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Cecil.Pdb", "symbols\pdb\Mono.Cecil.Pdb.csproj", "{63E6915C-7EA4-4D76-AB28-0D7191EEA626}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Cecil.Pdb.Tests", "symbols\pdb\Test\Mono.Cecil.Pdb.Tests.csproj", "{29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Cecil.Rocks.Tests", "rocks\Test\Mono.Cecil.Rocks.Tests.csproj", "{C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Cecil.Rocks", "rocks\Mono.Cecil.Rocks.csproj", "{FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - net_2_0_Debug|Any CPU = net_2_0_Debug|Any CPU - net_2_0_Release|Any CPU = net_2_0_Release|Any CPU - net_3_5_Debug|Any CPU = net_3_5_Debug|Any CPU - net_3_5_Release|Any CPU = net_3_5_Release|Any CPU - net_4_0_Debug|Any CPU = net_4_0_Debug|Any CPU - net_4_0_Release|Any CPU = net_4_0_Release|Any CPU - silverlight_Debug|Any CPU = silverlight_Debug|Any CPU - silverlight_Release|Any CPU = silverlight_Release|Any CPU - winphone_Debug|Any CPU = winphone_Debug|Any CPU - winphone_Release|Any CPU = winphone_Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_2_0_Debug|Any CPU.ActiveCfg = net_2_0_Debug|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_2_0_Debug|Any CPU.Build.0 = net_2_0_Debug|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_2_0_Release|Any CPU.ActiveCfg = net_2_0_Release|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_2_0_Release|Any CPU.Build.0 = net_2_0_Release|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_3_5_Debug|Any CPU.ActiveCfg = net_3_5_Debug|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_3_5_Debug|Any CPU.Build.0 = net_3_5_Debug|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_3_5_Release|Any CPU.ActiveCfg = net_3_5_Release|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_3_5_Release|Any CPU.Build.0 = net_3_5_Release|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_0_Debug|Any CPU.ActiveCfg = net_4_0_Debug|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_0_Debug|Any CPU.Build.0 = net_4_0_Debug|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.silverlight_Debug|Any CPU.ActiveCfg = silverlight_Debug|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.silverlight_Debug|Any CPU.Build.0 = silverlight_Debug|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.silverlight_Release|Any CPU.ActiveCfg = silverlight_Release|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.silverlight_Release|Any CPU.Build.0 = silverlight_Release|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.winphone_Debug|Any CPU.ActiveCfg = winphone_Debug|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.winphone_Debug|Any CPU.Build.0 = winphone_Debug|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.winphone_Release|Any CPU.ActiveCfg = winphone_Release|Any CPU - {D68133BD-1E63-496E-9EDE-4FBDBF77B486}.winphone_Release|Any CPU.Build.0 = winphone_Release|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_2_0_Debug|Any CPU.ActiveCfg = net_2_0_Debug|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_2_0_Debug|Any CPU.Build.0 = net_2_0_Debug|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_2_0_Release|Any CPU.ActiveCfg = net_2_0_Release|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_2_0_Release|Any CPU.Build.0 = net_2_0_Release|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_3_5_Debug|Any CPU.ActiveCfg = net_3_5_Debug|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_3_5_Debug|Any CPU.Build.0 = net_3_5_Debug|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_3_5_Release|Any CPU.ActiveCfg = net_3_5_Release|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_3_5_Release|Any CPU.Build.0 = net_3_5_Release|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_4_0_Debug|Any CPU.ActiveCfg = net_4_0_Debug|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_4_0_Debug|Any CPU.Build.0 = net_4_0_Debug|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.silverlight_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.silverlight_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.winphone_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055}.winphone_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.net_2_0_Debug|Any CPU.ActiveCfg = net_4_0_Debug|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.net_2_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.net_3_5_Debug|Any CPU.ActiveCfg = net_3_5_Debug|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.net_3_5_Debug|Any CPU.Build.0 = net_3_5_Debug|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.net_3_5_Release|Any CPU.ActiveCfg = net_3_5_Release|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.net_3_5_Release|Any CPU.Build.0 = net_3_5_Release|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.net_4_0_Debug|Any CPU.ActiveCfg = net_4_0_Debug|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.net_4_0_Debug|Any CPU.Build.0 = net_4_0_Debug|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.silverlight_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.silverlight_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.winphone_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {89A775F3-64AB-485E-B958-60C25254B732}.winphone_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_2_0_Debug|Any CPU.ActiveCfg = net_2_0_Debug|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_2_0_Debug|Any CPU.Build.0 = net_2_0_Debug|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_2_0_Release|Any CPU.ActiveCfg = net_2_0_Release|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_2_0_Release|Any CPU.Build.0 = net_2_0_Release|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_3_5_Debug|Any CPU.ActiveCfg = net_3_5_Debug|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_3_5_Debug|Any CPU.Build.0 = net_3_5_Debug|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_3_5_Release|Any CPU.ActiveCfg = net_3_5_Release|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_3_5_Release|Any CPU.Build.0 = net_3_5_Release|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_4_0_Debug|Any CPU.ActiveCfg = net_4_0_Debug|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_4_0_Debug|Any CPU.Build.0 = net_4_0_Debug|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.silverlight_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.silverlight_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.winphone_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD}.winphone_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_2_0_Debug|Any CPU.ActiveCfg = net_2_0_Debug|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_2_0_Debug|Any CPU.Build.0 = net_2_0_Debug|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_2_0_Release|Any CPU.ActiveCfg = net_2_0_Release|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_2_0_Release|Any CPU.Build.0 = net_2_0_Release|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_3_5_Debug|Any CPU.ActiveCfg = net_3_5_Debug|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_3_5_Debug|Any CPU.Build.0 = net_3_5_Debug|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_3_5_Release|Any CPU.ActiveCfg = net_3_5_Release|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_3_5_Release|Any CPU.Build.0 = net_3_5_Release|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_4_0_Debug|Any CPU.ActiveCfg = net_4_0_Debug|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_4_0_Debug|Any CPU.Build.0 = net_4_0_Debug|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.silverlight_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.silverlight_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.winphone_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {AC71DF9C-99FA-4A63-990A-66C8010355A6}.winphone_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_2_0_Debug|Any CPU.ActiveCfg = net_2_0_Debug|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_2_0_Debug|Any CPU.Build.0 = net_2_0_Debug|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_2_0_Release|Any CPU.ActiveCfg = net_2_0_Release|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_2_0_Release|Any CPU.Build.0 = net_2_0_Release|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_3_5_Debug|Any CPU.ActiveCfg = net_3_5_Debug|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_3_5_Debug|Any CPU.Build.0 = net_3_5_Debug|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_3_5_Release|Any CPU.ActiveCfg = net_3_5_Release|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_3_5_Release|Any CPU.Build.0 = net_3_5_Release|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_4_0_Debug|Any CPU.ActiveCfg = net_4_0_Debug|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_4_0_Debug|Any CPU.Build.0 = net_4_0_Debug|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.silverlight_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.silverlight_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.winphone_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {63E6915C-7EA4-4D76-AB28-0D7191EEA626}.winphone_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_2_0_Debug|Any CPU.ActiveCfg = net_2_0_Debug|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_2_0_Debug|Any CPU.Build.0 = net_2_0_Debug|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_2_0_Release|Any CPU.ActiveCfg = net_2_0_Release|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_2_0_Release|Any CPU.Build.0 = net_2_0_Release|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_3_5_Debug|Any CPU.ActiveCfg = net_3_5_Debug|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_3_5_Debug|Any CPU.Build.0 = net_3_5_Debug|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_3_5_Release|Any CPU.ActiveCfg = net_3_5_Release|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_3_5_Release|Any CPU.Build.0 = net_3_5_Release|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_4_0_Debug|Any CPU.ActiveCfg = net_4_0_Debug|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_4_0_Debug|Any CPU.Build.0 = net_4_0_Debug|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.silverlight_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.silverlight_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.winphone_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA}.winphone_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_2_0_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_2_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_3_5_Debug|Any CPU.ActiveCfg = net_3_5_Debug|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_3_5_Debug|Any CPU.Build.0 = net_3_5_Debug|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_3_5_Release|Any CPU.ActiveCfg = net_3_5_Release|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_3_5_Release|Any CPU.Build.0 = net_3_5_Release|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_4_0_Debug|Any CPU.ActiveCfg = net_4_0_Debug|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_4_0_Debug|Any CPU.Build.0 = net_4_0_Debug|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.silverlight_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.silverlight_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.winphone_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52}.winphone_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_2_0_Debug|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_2_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_3_5_Debug|Any CPU.ActiveCfg = net_3_5_Debug|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_3_5_Debug|Any CPU.Build.0 = net_3_5_Debug|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_3_5_Release|Any CPU.ActiveCfg = net_3_5_Release|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_3_5_Release|Any CPU.Build.0 = net_3_5_Release|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_4_0_Debug|Any CPU.ActiveCfg = net_4_0_Debug|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_4_0_Debug|Any CPU.Build.0 = net_4_0_Debug|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_4_0_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.net_4_0_Release|Any CPU.Build.0 = net_4_0_Release|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.silverlight_Debug|Any CPU.ActiveCfg = silverlight_Debug|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.silverlight_Debug|Any CPU.Build.0 = silverlight_Debug|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.silverlight_Release|Any CPU.ActiveCfg = silverlight_Release|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.silverlight_Release|Any CPU.Build.0 = silverlight_Release|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.winphone_Debug|Any CPU.ActiveCfg = winphone_Debug|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.winphone_Debug|Any CPU.Build.0 = winphone_Debug|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.winphone_Release|Any CPU.ActiveCfg = winphone_Release|Any CPU - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC}.winphone_Release|Any CPU.Build.0 = winphone_Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055} = {74E5ECE0-06B4-401C-AEBA-E8DD53E17943} - {AC71DF9C-99FA-4A63-990A-66C8010355A6} = {74E5ECE0-06B4-401C-AEBA-E8DD53E17943} - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA} = {74E5ECE0-06B4-401C-AEBA-E8DD53E17943} - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52} = {74E5ECE0-06B4-401C-AEBA-E8DD53E17943} - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD} = {929D5B3B-E29A-40CC-93D8-0FF43A6F9FA1} - {63E6915C-7EA4-4D76-AB28-0D7191EEA626} = {929D5B3B-E29A-40CC-93D8-0FF43A6F9FA1} - EndGlobalSection -EndGlobal diff --git a/Mono.Cecil/Mono.Cecil/ArrayType.cs b/Mono.Cecil/Mono.Cecil/ArrayType.cs deleted file mode 100644 index 55c59d872..000000000 --- a/Mono.Cecil/Mono.Cecil/ArrayType.cs +++ /dev/null @@ -1,159 +0,0 @@ -// -// 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 dimensions; - - public Collection Dimensions { - get { - if (dimensions != null) - return dimensions; - - dimensions = new Collection (); - 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 (rank); - for (int i = 0; i < rank; i++) - dimensions.Add (new ArrayDimension ()); - this.etype = MD.ElementType.Array; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/AssemblyDefinition.cs b/Mono.Cecil/Mono.Cecil/AssemblyDefinition.cs deleted file mode 100644 index f4e69cfed..000000000 --- a/Mono.Cecil/Mono.Cecil/AssemblyDefinition.cs +++ /dev/null @@ -1,189 +0,0 @@ -// -// 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 modules; - Collection custom_attributes; - Collection 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 Modules { - get { - if (modules != null) - return modules; - - if (main_module.HasImage) - return main_module.Read (ref modules, this, (_, reader) => reader.ReadModules ()); - - return modules = new Collection (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 CustomAttributes { - get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, main_module)); } - } - - public bool HasSecurityDeclarations { - get { - if (security_declarations != null) - return security_declarations.Count > 0; - - return this.GetHasSecurityDeclarations (main_module); - } - } - - public Collection SecurityDeclarations { - get { return security_declarations ?? (this.GetSecurityDeclarations (ref security_declarations, 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/AssemblyFlags.cs b/Mono.Cecil/Mono.Cecil/AssemblyFlags.cs deleted file mode 100644 index 72a0eb06c..000000000 --- a/Mono.Cecil/Mono.Cecil/AssemblyFlags.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -// 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, - WindowsRuntime = 0x0200, - DisableJITCompileOptimizer = 0x4000, - EnableJITCompileTracking = 0x8000, - } -} diff --git a/Mono.Cecil/Mono.Cecil/AssemblyHashAlgorithm.cs b/Mono.Cecil/Mono.Cecil/AssemblyHashAlgorithm.cs deleted file mode 100644 index 79a5699db..000000000 --- a/Mono.Cecil/Mono.Cecil/AssemblyHashAlgorithm.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/AssemblyInfo.cs b/Mono.Cecil/Mono.Cecil/AssemblyInfo.cs deleted file mode 100644 index 8a9f8097e..000000000 --- a/Mono.Cecil/Mono.Cecil/AssemblyInfo.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -// 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.CompilerServices; -using System.Runtime.InteropServices; - -[assembly: AssemblyTitle ("Mono.Cecil")] -[assembly: AssemblyProduct ("Mono.Cecil")] -[assembly: AssemblyCopyright ("Copyright © 2008 - 2011 Jb Evain")] - -[assembly: ComVisible (false)] - -[assembly: Guid ("fd225bb4-fa53-44b2-a6db-85f5e48dcb54")] - -[assembly: AssemblyVersion ("0.9.5.0")] -#if !CF -[assembly: AssemblyFileVersion ("0.9.5.0")] -#endif - -[assembly: InternalsVisibleTo ("Mono.Cecil.Pdb, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")] -[assembly: InternalsVisibleTo ("Mono.Cecil.Mdb, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")] -[assembly: InternalsVisibleTo ("Mono.Cecil.Rocks, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")] -[assembly: InternalsVisibleTo ("Mono.Cecil.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")] diff --git a/Mono.Cecil/Mono.Cecil/AssemblyLinkedResource.cs b/Mono.Cecil/Mono.Cecil/AssemblyLinkedResource.cs deleted file mode 100644 index 4d8bac0bb..000000000 --- a/Mono.Cecil/Mono.Cecil/AssemblyLinkedResource.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/AssemblyNameDefinition.cs b/Mono.Cecil/Mono.Cecil/AssemblyNameDefinition.cs deleted file mode 100644 index dc6b9057f..000000000 --- a/Mono.Cecil/Mono.Cecil/AssemblyNameDefinition.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -// 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.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); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/AssemblyNameReference.cs b/Mono.Cecil/Mono.Cecil/AssemblyNameReference.cs deleted file mode 100644 index a8ad42c3c..000000000 --- a/Mono.Cecil/Mono.Cecil/AssemblyNameReference.cs +++ /dev/null @@ -1,270 +0,0 @@ -// -// 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 bool IsWindowsRuntime { - get { return attributes.GetAttributes ((uint) AssemblyAttributes.WindowsRuntime); } - set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.WindowsRuntime, value); } - } - - public byte [] PublicKey { - get { return public_key ?? Empty.Array; } - set { - public_key = value; - HasPublicKey = !public_key.IsNullOrEmpty (); - public_key_token = Empty.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 - byte[] local_public_key_token = new byte [8]; - Array.Copy (hash, (hash.Length - 8), local_public_key_token, 0, 8); - Array.Reverse (local_public_key_token, 0, 8); - public_key_token = local_public_key_token; // publish only once finished (required for thread-safety) - } - return public_key_token ?? Empty.Array; - } - 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="); - - var pk_token = PublicKeyToken; - if (!pk_token.IsNullOrEmpty () && pk_token.Length > 0) { - for (int i = 0 ; i < pk_token.Length ; i++) { - builder.Append (pk_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].ToLowerInvariant ()) { - case "version": - name.Version = new Version (parts [1]); - break; - case "culture": - name.Culture = parts [1]; - break; - case "publickeytoken": - var 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/AssemblyReader.cs b/Mono.Cecil/Mono.Cecil/AssemblyReader.cs deleted file mode 100644 index 00eba7437..000000000 --- a/Mono.Cecil/Mono.Cecil/AssemblyReader.cs +++ /dev/null @@ -1,3166 +0,0 @@ -// -// 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; - - if (parameters.MetadataResolver != null) - module.metadata_resolver = parameters.MetadataResolver; - - 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 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.Array; - } - - return blob_heap.Read (ReadBlobIndex ()); - } - - byte [] ReadBlob (uint signature) - { - var blob_heap = image.BlobHeap; - if (blob_heap == null) - return Empty.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 ReadAssemblyReferences () - { - InitializeAssemblyReferences (); - - return new Collection (metadata.AssemblyReferences); - } - - public MethodDefinition ReadEntryPoint () - { - if (module.Image.EntryPointToken == 0) - return null; - - var token = new MetadataToken (module.Image.EntryPointToken); - return GetMethodDefinition (token.RID); - } - - public Collection ReadModules () - { - var modules = new Collection (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 ReadModuleReferences () - { - InitializeModuleReferences (); - - return new Collection (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 ReadResources () - { - int length = MoveTo (Table.ManifestResource); - var resources = new Collection (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 ReadFileRecord (uint rid) - { - var position = this.position; - - if (!MoveTo (Table.File, rid)) - throw new ArgumentException (); - - var record = new Row ( - (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 ReadNestedTypes (TypeDefinition type) - { - InitializeNestedTypes (); - uint [] mapping; - if (!metadata.TryGetNestedTypeMapping (type, out mapping)) - return new MemberDefinitionCollection (type); - - var nested_types = new MemberDefinitionCollection (type, mapping.Length); - - for (int i = 0; i < mapping.Length; i++) { - var nested_type = GetTypeDefinition (mapping [i]); - - if (nested_type != null) - nested_types.Add (nested_type); - } - - metadata.RemoveNestedTypeMapping (type); - - return nested_types; - } - - void InitializeNestedTypes () - { - if (metadata.NestedTypes != null) - return; - - var length = MoveTo (Table.NestedClass); - - metadata.NestedTypes = new Dictionary (length); - metadata.ReverseNestedTypes = new Dictionary (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 (Dictionary 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 ReadTypeLayout (TypeDefinition type) - { - InitializeTypeLayouts (); - Row class_layout; - var rid = type.token.RID; - if (!metadata.ClassLayouts.TryGetValue (rid, out class_layout)) - return new Row (Mixin.NoDataMarker, Mixin.NoDataMarker); - - type.PackingSize = (short) class_layout.Col1; - type.ClassSize = (int) class_layout.Col2; - - metadata.ClassLayouts.Remove (rid); - - return new Row ((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> (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 (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.TryProcessPrimitiveTypeReference (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 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 ReadInterfaces (TypeDefinition type) - { - InitializeInterfaces (); - MetadataToken [] mapping; - - if (!metadata.TryGetInterfaceMapping (type, out mapping)) - return new Collection (); - - var interfaces = new Collection (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 (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 ReadFields (TypeDefinition type) - { - var fields_range = type.fields_range; - if (fields_range.Length == 0) - return new MemberDefinitionCollection (type); - - var fields = new MemberDefinitionCollection (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 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.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 (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 (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 ReadEvents (TypeDefinition type) - { - InitializeEvents (); - Range range; - - if (!metadata.TryGetEventsRange (type, out range)) - return new MemberDefinitionCollection (type); - - var events = new MemberDefinitionCollection (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 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 (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 ReadProperties (TypeDefinition type) - { - InitializeProperties (); - - Range range; - - if (!metadata.TryGetPropertiesRange (type, out range)) - return new MemberDefinitionCollection (type); - - metadata.RemovePropertiesRange (type); - - var properties = new MemberDefinitionCollection (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 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 (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 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 (); - - @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 (); - - 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 (Collection 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> (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 (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_ready) - continue; - - method.sem_attrs = ReadMethodSemantics (method); - method.sem_attrs_ready = true; - } - } - - Range ReadParametersRange (uint method_rid) - { - return ReadListRange (method_rid, Table.Method, Table.Param); - } - - public Collection ReadMethods (TypeDefinition type) - { - var methods_range = type.methods_range; - if (methods_range.Length == 0) - return new MemberDefinitionCollection (type); - - var methods = new MemberDefinitionCollection (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 (Table ptr, Table table, Range range, Collection members, Action> 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 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 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> (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 (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 ReadGenericParameters (IGenericParameterProvider provider) - { - InitializeGenericParameters (); - - Range range; - if (!metadata.TryGetGenericParameterRange (provider, out range) - || !MoveTo (Table.GenericParam, range.Start)) - return new GenericParameterCollection (provider); - - metadata.RemoveGenericParameterRange (provider); - - var generic_parameters = new GenericParameterCollection (provider, (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 InitializeRanges (Table table, Func get_next) - { - int length = MoveTo (table); - var ranges = new Dictionary (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 ReadGenericConstraints (GenericParameter generic_parameter) - { - InitializeGenericConstraints (); - - MetadataToken [] mapping; - if (!metadata.TryGetGenericConstraintMapping (generic_parameter, out mapping)) - return new Collection (); - - var constraints = new Collection (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 (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 ReadOverrides (MethodDefinition method) - { - InitializeOverrides (); - - MetadataToken [] mapping; - if (!metadata.TryGetOverrideMapping (method, out mapping)) - return new Collection (); - - var overrides = new Collection (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 (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); - - if (!declaring_type.IsArray) - 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 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> (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 (type, signature)); - } - } - - public object ReadConstant (IConstantProvider owner) - { - InitializeConstants (); - - Row 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 ReadCustomAttributes (ICustomAttributeProvider owner) - { - InitializeCustomAttributes (); - - Range range; - if (!metadata.TryGetCustomAttributeRange (owner, out range) - || !MoveTo (Table.CustomAttribute, range.Start)) - return new Collection (); - - var custom_attributes = new Collection ((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.CanReadMore ()) - return; - - 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 (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 ReadSecurityDeclarations (ISecurityDeclarationProvider owner) - { - InitializeSecurityDeclarations (); - - Range range; - if (!metadata.TryGetSecurityDeclarationRange (owner, out range) - || !MoveTo (Table.DeclSecurity, range.Start)) - return new Collection (); - - var security_declarations = new Collection ((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 ((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 (1); - - var attribute = new SecurityAttribute ( - module.TypeSystem.LookupType ("System.Security.Permissions", "PermissionSetAttribute")); - - attribute.properties = new Collection (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 ReadExportedTypes () - { - var length = MoveTo (Table.ExportedType); - if (length == 0) - return new Collection (); - - var exported_types = new Collection (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; - int index = (int) var; - - if (context == null) - return GetUnboundGenericParameter (type, index); - - IGenericParameterProvider provider; - - switch (type) { - case GenericParameterType.Type: - provider = context.Type; - break; - case GenericParameterType.Method: - provider = context.Method; - break; - default: - throw new NotSupportedException (); - } - - if (!context.IsDefinition) - CheckGenericContext (provider, index); - - if (index >= provider.GenericParameters.Count) - return GetUnboundGenericParameter (type, index); - - return provider.GenericParameters [index]; - } - - GenericParameter GetUnboundGenericParameter (GenericParameterType type, int index) - { - return new GenericParameter (index, type, reader.module); - } - - 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 && !generic_context.DeclaringType.IsArray) - 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 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 parameters) - { - var count = parameters.Count; - if (count == 0) - return; - - attribute.arguments = new Collection (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 fields, ref Collection properties) - { - for (int i = 0; i < count; i++) - ReadCustomAttributeNamedArgument (ref fields, ref properties); - } - - void ReadCustomAttributeNamedArgument (ref Collection fields, ref Collection properties) - { - var kind = ReadByte (); - var type = ReadCustomAttributeFieldOrPropType (); - var name = ReadUTF8String (); - - Collection 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 GetCustomAttributeNamedArgumentCollection (ref Collection collection) - { - if (collection != null) - return collection; - - return collection = new Collection (); - } - - CustomAttributeArgument ReadCustomAttributeFixedArrayArgument (ArrayType type) - { - var length = ReadUInt32 (); - - if (length == 0xffffffff) - return new CustomAttributeArgument (type, null); - - if (length == 0) - return new CustomAttributeArgument (type, Empty.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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/AssemblyWriter.cs b/Mono.Cecil/Mono.Cecil/AssemblyWriter.cs deleted file mode 100644 index bffa439c6..000000000 --- a/Mono.Cecil/Mono.Cecil/AssemblyWriter.cs +++ /dev/null @@ -1,2571 +0,0 @@ -// -// 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; - using TypeDefRow = Row; - using FieldRow = Row; - using MethodRow = Row; - using ParamRow = Row; - using InterfaceImplRow = Row; - using MemberRefRow = Row; - using ConstantRow = Row; - using CustomAttributeRow = Row; - using FieldMarshalRow = Row; - using DeclSecurityRow = Row; - using ClassLayoutRow = Row; - using FieldLayoutRow = Row; - using EventMapRow = Row; - using EventRow = Row; - using PropertyMapRow = Row; - using PropertyRow = Row; - using MethodSemanticsRow = Row; - using MethodImplRow = Row; - using ImplMapRow = Row; - using FieldRVARow = Row; - using AssemblyRow = Row; - using AssemblyRefRow = Row; - using FileRow = Row; - using ExportedTypeRow = Row; - using ManifestResourceRow = Row; - using NestedClassRow = Row; - using GenericParamRow = Row; - using MethodSpecRow = Row; - using GenericParamConstraintRow = Row; - - 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; - module.Attributes |= ModuleAttributes.StrongNameSigned; - } -#endif - var metadata = new MetadataBuilder (module, fq_name, - symbol_writer_provider, symbol_writer); - - BuildMetadata (module, metadata); - - if (module.symbol_reader != null) - module.symbol_reader.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 : MetadataTable where TRow : struct { - - internal TRow row; - - public sealed override int Length { - get { return 1; } - } - - public sealed override void Sort () - { - } - } - - abstract class MetadataTable : 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 : MetadataTable, IComparer 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - public override void Write (TableHeapBuffer buffer) - { - for (int i = 0; i < length; i++) - buffer.WriteBlob (rows [i]); - } - } - - sealed class EventMapTable : MetadataTable { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - public override void Write (TableHeapBuffer buffer) - { - for (int i = 0; i < length; i++) - buffer.WriteString (rows [i]); // Name - } - } - - sealed class TypeSpecTable : MetadataTable { - - public override void Write (TableHeapBuffer buffer) - { - for (int i = 0; i < length; i++) - buffer.WriteBlob (rows [i]); // Signature - } - } - - sealed class ImplMapTable : SortedTable { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 { - - 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 type_ref_map; - readonly Dictionary type_spec_map; - readonly Dictionary member_ref_map; - readonly Dictionary method_spec_map; - readonly Collection generic_parameters; - readonly Dictionary 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 (Table.TypeRef); - this.type_def_table = GetTable (Table.TypeDef); - this.field_table = GetTable (Table.Field); - this.method_table = GetTable (Table.Method); - this.param_table = GetTable (Table.Param); - this.iface_impl_table = GetTable (Table.InterfaceImpl); - this.member_ref_table = GetTable (Table.MemberRef); - this.constant_table = GetTable (Table.Constant); - this.custom_attribute_table = GetTable (Table.CustomAttribute); - this.declsec_table = GetTable (Table.DeclSecurity); - this.standalone_sig_table = GetTable (Table.StandAloneSig); - this.event_map_table = GetTable (Table.EventMap); - this.event_table = GetTable (Table.Event); - this.property_map_table = GetTable (Table.PropertyMap); - this.property_table = GetTable (Table.Property); - this.typespec_table = GetTable (Table.TypeSpec); - this.method_spec_table = GetTable (Table.MethodSpec); - - var row_equality_comparer = new RowEqualityComparer (); - type_ref_map = new Dictionary (row_equality_comparer); - type_spec_map = new Dictionary (); - member_ref_map = new Dictionary (row_equality_comparer); - method_spec_map = new Dictionary (row_equality_comparer); - generic_parameters = new Collection (); - if (write_symbols) - method_def_map = new Dictionary (); - } - - TextMap CreateTextMap () - { - var map = new TextMap (); - map.AddMap (TextSegment.ImportAddressTable, module.Architecture == TargetArchitecture.I386 ? 8 : 0); - map.AddMap (TextSegment.CLIHeader, 0x48, 8); - return map; - } - - TTable GetTable (Table table) where TTable : MetadataTable, new () - { - return table_heap.GetTable (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 { - - 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 (Table.GenericParam); - var generic_param_constraint_table = GetTable (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 (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 (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 (Table.FieldRVA); - table.AddRow (new FieldRVARow ( - data.AddData (field.InitialValue), - field.token.RID)); - } - - void AddFieldLayout (FieldDefinition field) - { - var table = GetTable (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) - return; - - var table = GetTable (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 (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 (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 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 (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 variables) - { - return GetBlobIndex (GetVariablesSignature (variables)); - } - - public uint GetCallSiteBlobIndex (CallSite call_site) - { - return GetBlobIndex (GetMethodSignature (call_site)); - } - - SignatureWriter GetVariablesSignature (Collection 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 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 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 (1); // 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 - -} diff --git a/Mono.Cecil/Mono.Cecil/BaseAssemblyResolver.cs b/Mono.Cecil/Mono.Cecil/BaseAssemblyResolver.cs deleted file mode 100644 index 10ab2c34a..000000000 --- a/Mono.Cecil/Mono.Cecil/BaseAssemblyResolver.cs +++ /dev/null @@ -1,363 +0,0 @@ -// -// 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; - } - } - -#if !SILVERLIGHT && !CF - [Serializable] -#endif - 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; - } - -#if !SILVERLIGHT && !CF - protected AssemblyResolutionException ( - System.Runtime.Serialization.SerializationInfo info, - System.Runtime.Serialization.StreamingContext context) - : base (info, context) - { - } -#endif - } - - public abstract class BaseAssemblyResolver : IAssemblyResolver { - - static readonly bool on_mono = Type.GetType ("Mono.Runtime") != null; - - readonly Collection directories; - -#if !SILVERLIGHT && !CF - Collection 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 (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 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 GetGacPaths () - { - if (on_mono) - return GetDefaultMonoGacPaths (); - - var paths = new Collection (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 GetDefaultMonoGacPaths () - { - var paths = new Collection (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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/CallSite.cs b/Mono.Cecil/Mono.Cecil/CallSite.cs deleted file mode 100644 index 2d4ed4175..000000000 --- a/Mono.Cecil/Mono.Cecil/CallSite.cs +++ /dev/null @@ -1,124 +0,0 @@ -// -// 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 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/CustomAttribute.cs b/Mono.Cecil/Mono.Cecil/CustomAttribute.cs deleted file mode 100644 index e8eb05723..000000000 --- a/Mono.Cecil/Mono.Cecil/CustomAttribute.cs +++ /dev/null @@ -1,231 +0,0 @@ -// -// 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 Fields { get; } - Collection Properties { get; } - } - - public sealed class CustomAttribute : ICustomAttribute { - - readonly internal uint signature; - internal bool resolved; - MethodReference constructor; - byte [] blob; - internal Collection arguments; - internal Collection fields; - internal Collection 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 ConstructorArguments { - get { - Resolve (); - - return arguments ?? (arguments = new Collection ()); - } - } - - public bool HasFields { - get { - Resolve (); - - return !fields.IsNullOrEmpty (); - } - } - - public Collection Fields { - get { - Resolve (); - - return fields ?? (fields = new Collection ()); - } - } - - public bool HasProperties { - get { - Resolve (); - - return !properties.IsNullOrEmpty (); - } - } - - public Collection Properties { - get { - Resolve (); - - return properties ?? (properties = new Collection ()); - } - } - - 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) - throw new NotSupportedException (); - - return Module.Read (ref blob, this, (attribute, reader) => reader.ReadCustomAttributeBlob (attribute.signature)); - } - - void Resolve () - { - if (resolved || !HasImage) - return; - - Module.Read (this, (attribute, reader) => { - try { - reader.ReadCustomAttributeSignature (attribute); - resolved = true; - } catch (ResolutionException) { - if (arguments != null) - arguments.Clear (); - if (fields != null) - fields.Clear (); - if (properties != null) - properties.Clear (); - - resolved = false; - } - return this; - }); - } - } - - 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"); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/DefaultAssemblyResolver.cs b/Mono.Cecil/Mono.Cecil/DefaultAssemblyResolver.cs deleted file mode 100644 index e0baedf77..000000000 --- a/Mono.Cecil/Mono.Cecil/DefaultAssemblyResolver.cs +++ /dev/null @@ -1,70 +0,0 @@ -// -// 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 class DefaultAssemblyResolver : BaseAssemblyResolver { - - readonly IDictionary cache; - - public DefaultAssemblyResolver () - { - cache = new Dictionary (StringComparer.Ordinal); - } - - 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/EmbeddedResource.cs b/Mono.Cecil/Mono.Cecil/EmbeddedResource.cs deleted file mode 100644 index e12dd0b37..000000000 --- a/Mono.Cecil/Mono.Cecil/EmbeddedResource.cs +++ /dev/null @@ -1,105 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/EventAttributes.cs b/Mono.Cecil/Mono.Cecil/EventAttributes.cs deleted file mode 100644 index 815efa57b..000000000 --- a/Mono.Cecil/Mono.Cecil/EventAttributes.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/EventDefinition.cs b/Mono.Cecil/Mono.Cecil/EventDefinition.cs deleted file mode 100644 index a78f76f3b..000000000 --- a/Mono.Cecil/Mono.Cecil/EventDefinition.cs +++ /dev/null @@ -1,170 +0,0 @@ -// -// 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 custom_attributes; - - internal MethodDefinition add_method; - internal MethodDefinition invoke_method; - internal MethodDefinition remove_method; - internal Collection 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 OtherMethods { - get { - if (other_methods != null) - return other_methods; - - InitializeMethods (); - - if (other_methods != null) - return other_methods; - - return other_methods = new Collection (); - } - } - - public bool HasCustomAttributes { - get { - if (custom_attributes != null) - return custom_attributes.Count > 0; - - return this.GetHasCustomAttributes (Module); - } - } - - public Collection CustomAttributes { - get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, 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 () - { - var module = this.Module; - lock (module.SyncRoot) { - if (add_method != null - || invoke_method != null - || remove_method != null) - return; - - if (!module.HasImage ()) - return; - - module.Read (this, (@event, reader) => reader.ReadMethods (@event)); - } - } - - public override EventDefinition Resolve () - { - return this; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/EventReference.cs b/Mono.Cecil/Mono.Cecil/EventReference.cs deleted file mode 100644 index 8952002d6..000000000 --- a/Mono.Cecil/Mono.Cecil/EventReference.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -// 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 (); - } -} diff --git a/Mono.Cecil/Mono.Cecil/ExportedType.cs b/Mono.Cecil/Mono.Cecil/ExportedType.cs deleted file mode 100644 index c25f8d05e..000000000 --- a/Mono.Cecil/Mono.Cecil/ExportedType.cs +++ /dev/null @@ -1,249 +0,0 @@ -// -// 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, - }; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/FieldAttributes.cs b/Mono.Cecil/Mono.Cecil/FieldAttributes.cs deleted file mode 100644 index dd6bf361d..000000000 --- a/Mono.Cecil/Mono.Cecil/FieldAttributes.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/FieldDefinition.cs b/Mono.Cecil/Mono.Cecil/FieldDefinition.cs deleted file mode 100644 index f992b2bb4..000000000 --- a/Mono.Cecil/Mono.Cecil/FieldDefinition.cs +++ /dev/null @@ -1,271 +0,0 @@ -// -// 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 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.Array; - - return initial_value; - } - set { initial_value = value; } - } - - public FieldAttributes Attributes { - get { return (FieldAttributes) attributes; } - set { attributes = (ushort) value; } - } - - public bool HasConstant { - get { - this.ResolveConstant (ref constant, Module); - - return constant != Mixin.NoValue; - } - set { if (!value) constant = Mixin.NoValue; } - } - - public object Constant { - get { return HasConstant ? constant : null; } - set { constant = value; } - } - - public bool HasCustomAttributes { - get { - if (custom_attributes != null) - return custom_attributes.Count > 0; - - return this.GetHasCustomAttributes (Module); - } - } - - public Collection CustomAttributes { - get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); } - } - - public bool HasMarshalInfo { - get { - if (marshal_info != null) - return true; - - return this.GetHasMarshalInfo (Module); - } - } - - public MarshalInfo MarshalInfo { - get { return marshal_info ?? (this.GetMarshalInfo (ref marshal_info, 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; - } -} diff --git a/Mono.Cecil/Mono.Cecil/FieldReference.cs b/Mono.Cecil/Mono.Cecil/FieldReference.cs deleted file mode 100644 index be58d3d06..000000000 --- a/Mono.Cecil/Mono.Cecil/FieldReference.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -// 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); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/FileAttributes.cs b/Mono.Cecil/Mono.Cecil/FileAttributes.cs deleted file mode 100644 index 4d3b6ca7f..000000000 --- a/Mono.Cecil/Mono.Cecil/FileAttributes.cs +++ /dev/null @@ -1,35 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/FunctionPointerType.cs b/Mono.Cecil/Mono.Cecil/FunctionPointerType.cs deleted file mode 100644 index db80f7621..000000000 --- a/Mono.Cecil/Mono.Cecil/FunctionPointerType.cs +++ /dev/null @@ -1,128 +0,0 @@ -// -// 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 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/GenericInstanceMethod.cs b/Mono.Cecil/Mono.Cecil/GenericInstanceMethod.cs deleted file mode 100644 index dbe720df5..000000000 --- a/Mono.Cecil/Mono.Cecil/GenericInstanceMethod.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -// 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 arguments; - - public bool HasGenericArguments { - get { return !arguments.IsNullOrEmpty (); } - } - - public Collection GenericArguments { - get { return arguments ?? (arguments = new Collection ()); } - } - - 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) - { - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/GenericInstanceType.cs b/Mono.Cecil/Mono.Cecil/GenericInstanceType.cs deleted file mode 100644 index 6554ff0e8..000000000 --- a/Mono.Cecil/Mono.Cecil/GenericInstanceType.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -// 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 arguments; - - public bool HasGenericArguments { - get { return !arguments.IsNullOrEmpty (); } - } - - public Collection GenericArguments { - get { return arguments ?? (arguments = new Collection ()); } - } - - 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/GenericParameter.cs b/Mono.Cecil/Mono.Cecil/GenericParameter.cs deleted file mode 100644 index 0cbdb36da..000000000 --- a/Mono.Cecil/Mono.Cecil/GenericParameter.cs +++ /dev/null @@ -1,277 +0,0 @@ -// -// 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 { - - internal int position; - internal GenericParameterType type; - internal IGenericParameterProvider owner; - - ushort attributes; - Collection constraints; - Collection custom_attributes; - - public GenericParameterAttributes Attributes { - get { return (GenericParameterAttributes) attributes; } - set { attributes = (ushort) value; } - } - - public int Position { - get { return position; } - } - - public GenericParameterType Type { - get { return type; } - } - - 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 Constraints { - get { - if (constraints != null) - return constraints; - - if (HasImage) - return Module.Read (ref constraints, this, (generic_parameter, reader) => reader.ReadGenericConstraints (generic_parameter)); - - return constraints = new Collection (); - } - } - - public bool HasCustomAttributes { - get { - if (custom_attributes != null) - return custom_attributes.Count > 0; - - return this.GetHasCustomAttributes (Module); - } - } - - public Collection CustomAttributes { - get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); } - } - - public override IMetadataScope Scope { - get { - if (owner == null) - return null; - - return owner.GenericParameterType == GenericParameterType.Method - ? ((MethodReference) owner).DeclaringType.Scope - : ((TypeReference) owner).Scope; - } - } - - public override ModuleDefinition Module { - get { return module ?? owner.Module; } - } - - public override string Name { - get { - if (!string.IsNullOrEmpty (base.Name)) - return base.Name; - - return base.Name = (type == GenericParameterType.Method ? "!!" : "!") + 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.position = -1; - this.owner = owner; - this.type = owner.GenericParameterType; - this.etype = ConvertGenericParameterType (this.type); - } - - public GenericParameter (int position, GenericParameterType type, ModuleDefinition module) - : base (string.Empty, string.Empty) - { - if (module == null) - throw new ArgumentNullException (); - - this.position = position; - this.type = type; - this.etype = ConvertGenericParameterType (type); - this.module = module; - } - - static ElementType ConvertGenericParameterType (GenericParameterType type) - { - switch (type) { - case GenericParameterType.Type: - return ElementType.Var; - case GenericParameterType.Method: - return ElementType.MVar; - } - - throw new ArgumentOutOfRangeException (); - } - - public override TypeDefinition Resolve () - { - return null; - } - } - - sealed class GenericParameterCollection : Collection { - - readonly IGenericParameterProvider owner; - - internal GenericParameterCollection (IGenericParameterProvider owner) - { - this.owner = owner; - } - - internal GenericParameterCollection (IGenericParameterProvider owner, int capacity) - : base (capacity) - { - this.owner = owner; - } - - protected override void OnAdd (GenericParameter item, int index) - { - UpdateGenericParameter (item, index); - } - - protected override void OnInsert (GenericParameter item, int index) - { - UpdateGenericParameter (item, index); - - for (int i = index; i < size; i++) - items[i].position = i + 1; - } - - protected override void OnSet (GenericParameter item, int index) - { - UpdateGenericParameter (item, index); - } - - void UpdateGenericParameter (GenericParameter item, int index) - { - item.owner = owner; - item.position = index; - item.type = owner.GenericParameterType; - } - - protected override void OnRemove (GenericParameter item, int index) - { - item.owner = null; - item.position = -1; - item.type = GenericParameterType.Type; - - for (int i = index + 1; i < size; i++) - items[i].position = i - 1; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/GenericParameterAttributes.cs b/Mono.Cecil/Mono.Cecil/GenericParameterAttributes.cs deleted file mode 100644 index 6d77956de..000000000 --- a/Mono.Cecil/Mono.Cecil/GenericParameterAttributes.cs +++ /dev/null @@ -1,45 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/IConstantProvider.cs b/Mono.Cecil/Mono.Cecil/IConstantProvider.cs deleted file mode 100644 index 74dab4049..000000000 --- a/Mono.Cecil/Mono.Cecil/IConstantProvider.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -// 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) - { - lock (module.SyncRoot) { - if (constant != Mixin.NotResolved) - return; - if (module.HasImage ()) - constant = module.Read (self, (provider, reader) => reader.ReadConstant (provider)); - else - constant = Mixin.NoValue; - } - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/ICustomAttributeProvider.cs b/Mono.Cecil/Mono.Cecil/ICustomAttributeProvider.cs deleted file mode 100644 index 86bd3748c..000000000 --- a/Mono.Cecil/Mono.Cecil/ICustomAttributeProvider.cs +++ /dev/null @@ -1,60 +0,0 @@ -// -// 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 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)); - } - - public static Collection GetCustomAttributes ( - this ICustomAttributeProvider self, - ref Collection variable, - ModuleDefinition module) - { - return module.HasImage () - ? module.Read (ref variable, self, (provider, reader) => reader.ReadCustomAttributes (provider)) - : variable = new Collection(); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/IGenericInstance.cs b/Mono.Cecil/Mono.Cecil/IGenericInstance.cs deleted file mode 100644 index edc406ca1..000000000 --- a/Mono.Cecil/Mono.Cecil/IGenericInstance.cs +++ /dev/null @@ -1,66 +0,0 @@ -// -// 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 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 (">"); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/IGenericParameterProvider.cs b/Mono.Cecil/Mono.Cecil/IGenericParameterProvider.cs deleted file mode 100644 index 7a392b9cc..000000000 --- a/Mono.Cecil/Mono.Cecil/IGenericParameterProvider.cs +++ /dev/null @@ -1,74 +0,0 @@ -// -// 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 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)); - } - - public static Collection GetGenericParameters ( - this IGenericParameterProvider self, - ref Collection collection, - ModuleDefinition module) - { - return module.HasImage () - ? module.Read (ref collection, self, (provider, reader) => reader.ReadGenericParameters (provider)) - : collection = new GenericParameterCollection (self); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/IMarshalInfoProvider.cs b/Mono.Cecil/Mono.Cecil/IMarshalInfoProvider.cs deleted file mode 100644 index e22040092..000000000 --- a/Mono.Cecil/Mono.Cecil/IMarshalInfoProvider.cs +++ /dev/null @@ -1,56 +0,0 @@ -// -// 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)); - } - - public static MarshalInfo GetMarshalInfo ( - this IMarshalInfoProvider self, - ref MarshalInfo variable, - ModuleDefinition module) - { - return module.HasImage () - ? module.Read (ref variable, self, (provider, reader) => reader.ReadMarshalInfo (provider)) - : null; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/IMemberDefinition.cs b/Mono.Cecil/Mono.Cecil/IMemberDefinition.cs deleted file mode 100644 index ee73d9da4..000000000 --- a/Mono.Cecil/Mono.Cecil/IMemberDefinition.cs +++ /dev/null @@ -1,100 +0,0 @@ -// -// 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)); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/IMetadataScope.cs b/Mono.Cecil/Mono.Cecil/IMetadataScope.cs deleted file mode 100644 index 04a022810..000000000 --- a/Mono.Cecil/Mono.Cecil/IMetadataScope.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// 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; } - } -} diff --git a/Mono.Cecil/Mono.Cecil/IMetadataTokenProvider.cs b/Mono.Cecil/Mono.Cecil/IMetadataTokenProvider.cs deleted file mode 100644 index 6621835b2..000000000 --- a/Mono.Cecil/Mono.Cecil/IMetadataTokenProvider.cs +++ /dev/null @@ -1,35 +0,0 @@ -// -// 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; } - } -} diff --git a/Mono.Cecil/Mono.Cecil/IMethodSignature.cs b/Mono.Cecil/Mono.Cecil/IMethodSignature.cs deleted file mode 100644 index e3d288ba9..000000000 --- a/Mono.Cecil/Mono.Cecil/IMethodSignature.cs +++ /dev/null @@ -1,75 +0,0 @@ -// -// 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 Parameters { get; } - TypeReference ReturnType { get; set; } - MethodReturnType MethodReturnType { get; } - } - - static partial class Mixin { - - public static bool HasImplicitThis (this IMethodSignature self) - { - return self.HasThis && !self.ExplicitThis; - } - - 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 (")"); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/Import.cs b/Mono.Cecil/Mono.Cecil/Import.cs deleted file mode 100644 index 38d012041..000000000 --- a/Mono.Cecil/Mono.Cecil/Import.cs +++ /dev/null @@ -1,566 +0,0 @@ -// -// 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_etype_mapping = new Dictionary (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 ?? string.Empty; - - 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.TryProcessPrimitiveTypeReference (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.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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/LinkedResource.cs b/Mono.Cecil/Mono.Cecil/LinkedResource.cs deleted file mode 100644 index 16c1d59b5..000000000 --- a/Mono.Cecil/Mono.Cecil/LinkedResource.cs +++ /dev/null @@ -1,60 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/ManifestResourceAttributes.cs b/Mono.Cecil/Mono.Cecil/ManifestResourceAttributes.cs deleted file mode 100644 index 7d6bb190f..000000000 --- a/Mono.Cecil/Mono.Cecil/ManifestResourceAttributes.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/MarshalInfo.cs b/Mono.Cecil/Mono.Cecil/MarshalInfo.cs deleted file mode 100644 index 9d5873892..000000000 --- a/Mono.Cecil/Mono.Cecil/MarshalInfo.cs +++ /dev/null @@ -1,171 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/MemberDefinitionCollection.cs b/Mono.Cecil/Mono.Cecil/MemberDefinitionCollection.cs deleted file mode 100644 index 707f36fb9..000000000 --- a/Mono.Cecil/Mono.Cecil/MemberDefinitionCollection.cs +++ /dev/null @@ -1,92 +0,0 @@ -// -// 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 : Collection 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/MemberReference.cs b/Mono.Cecil/Mono.Cecil/MemberReference.cs deleted file mode 100644 index b658c513d..000000000 --- a/Mono.Cecil/Mono.Cecil/MemberReference.cs +++ /dev/null @@ -1,101 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/MetadataResolver.cs b/Mono.Cecil/Mono.Cecil/MetadataResolver.cs deleted file mode 100644 index e69fcd715..000000000 --- a/Mono.Cecil/Mono.Cecil/MetadataResolver.cs +++ /dev/null @@ -1,364 +0,0 @@ -// -// 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 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 interface IMetadataResolver { - TypeDefinition Resolve (TypeReference type); - FieldDefinition Resolve (FieldReference field); - MethodDefinition Resolve (MethodReference method); - } - -#if !SILVERLIGHT && !CF - [Serializable] -#endif - 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; - } - -#if !SILVERLIGHT && !CF - protected ResolutionException ( - System.Runtime.Serialization.SerializationInfo info, - System.Runtime.Serialization.StreamingContext context) - : base (info, context) - { - } -#endif - } - - public class MetadataResolver : IMetadataResolver { - - readonly IAssemblyResolver assembly_resolver; - - public IAssemblyResolver AssemblyResolver { - get { return assembly_resolver; } - } - - public MetadataResolver (IAssemblyResolver assemblyResolver) - { - if (assemblyResolver == null) - throw new ArgumentNullException ("assemblyResolver"); - - assembly_resolver = assemblyResolver; - } - - public virtual TypeDefinition Resolve (TypeReference type) - { - if (type == null) - throw new ArgumentNullException ("type"); - - type = type.GetElementType (); - - var scope = type.Scope; - switch (scope.MetadataScopeType) { - case MetadataScopeType.AssemblyNameReference: - var assembly = assembly_resolver.Resolve ((AssemblyNameReference) scope); - if (assembly == null) - return null; - - return GetType (assembly.MainModule, type); - case MetadataScopeType.ModuleDefinition: - return GetType ((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 (netmodule, type); - } - break; - } - - throw new NotSupportedException (); - } - - static TypeDefinition GetType (ModuleDefinition module, TypeReference reference) - { - var type = GetTypeDefinition (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 GetTypeDefinition (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 virtual FieldDefinition Resolve (FieldReference field) - { - if (field == null) - throw new ArgumentNullException ("field"); - - var type = Resolve (field.DeclaringType); - if (type == null) - return null; - - if (!type.HasFields) - return null; - - return GetField (type, field); - } - - FieldDefinition GetField (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 (type.BaseType); - } - - return null; - } - - static FieldDefinition GetField (Collection 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 virtual MethodDefinition Resolve (MethodReference method) - { - if (method == null) - throw new ArgumentNullException ("method"); - - var type = Resolve (method.DeclaringType); - if (type == null) - return null; - - method = method.GetElementMethod (); - - if (!type.HasMethods) - return null; - - return GetMethod (type, method); - } - - MethodDefinition GetMethod (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 (type.BaseType); - } - - return null; - } - - public static MethodDefinition GetMethod (Collection 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 a, Collection 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); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/MetadataSystem.cs b/Mono.Cecil/Mono.Cecil/MetadataSystem.cs deleted file mode 100644 index 72b04f285..000000000 --- a/Mono.Cecil/Mono.Cecil/MetadataSystem.cs +++ /dev/null @@ -1,395 +0,0 @@ -// -// 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 NestedTypes; - internal Dictionary ReverseNestedTypes; - internal Dictionary Interfaces; - internal Dictionary> ClassLayouts; - internal Dictionary FieldLayouts; - internal Dictionary FieldRVAs; - internal Dictionary FieldMarshals; - internal Dictionary> Constants; - internal Dictionary Overrides; - internal Dictionary CustomAttributes; - internal Dictionary SecurityDeclarations; - internal Dictionary Events; - internal Dictionary Properties; - internal Dictionary> Semantics; - internal Dictionary> PInvokes; - internal Dictionary GenericParameters; - internal Dictionary GenericConstraints; - - static Dictionary> primitive_value_types; - - static void InitializePrimitives () - { - primitive_value_types = new Dictionary> (18, StringComparer.Ordinal) { - { "Void", new Row (ElementType.Void, false) }, - { "Boolean", new Row (ElementType.Boolean, true) }, - { "Char", new Row (ElementType.Char, true) }, - { "SByte", new Row (ElementType.I1, true) }, - { "Byte", new Row (ElementType.U1, true) }, - { "Int16", new Row (ElementType.I2, true) }, - { "UInt16", new Row (ElementType.U2, true) }, - { "Int32", new Row (ElementType.I4, true) }, - { "UInt32", new Row (ElementType.U4, true) }, - { "Int64", new Row (ElementType.I8, true) }, - { "UInt64", new Row (ElementType.U8, true) }, - { "Single", new Row (ElementType.R4, true) }, - { "Double", new Row (ElementType.R8, true) }, - { "String", new Row (ElementType.String, false) }, - { "TypedReference", new Row (ElementType.TypedByRef, false) }, - { "IntPtr", new Row (ElementType.I, true) }, - { "UIntPtr", new Row (ElementType.U, true) }, - { "Object", new Row (ElementType.Object, false) }, - }; - } - - public static void TryProcessPrimitiveTypeReference (TypeReference type) - { - if (type.Namespace != "System") - return; - - var scope = type.scope; - if (scope == null || scope.MetadataScopeType != MetadataScopeType.AssemblyNameReference) - return; - - Row primitive_data; - if (!TryGetPrimitiveData (type, out primitive_data)) - return; - - type.etype = primitive_data.Col1; - type.IsValueType = primitive_data.Col2; - } - - public static bool TryGetPrimitiveElementType (TypeDefinition type, out ElementType etype) - { - etype = ElementType.None; - - if (type.Namespace != "System") - return false; - - Row primitive_data; - if (TryGetPrimitiveData (type, out primitive_data) && primitive_data.Col1.IsPrimitive ()) { - etype = primitive_data.Col1; - return true; - } - - return false; - } - - static bool TryGetPrimitiveData (TypeReference type, out Row primitive_data) - { - if (primitive_value_types == null) - InitializePrimitives (); - - return primitive_value_types.TryGetValue (type.Name, out primitive_data); - } - - 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/MethodAttributes.cs b/Mono.Cecil/Mono.Cecil/MethodAttributes.cs deleted file mode 100644 index 626a97b3e..000000000 --- a/Mono.Cecil/Mono.Cecil/MethodAttributes.cs +++ /dev/null @@ -1,66 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/MethodCallingConvention.cs b/Mono.Cecil/Mono.Cecil/MethodCallingConvention.cs deleted file mode 100644 index bd7188dbe..000000000 --- a/Mono.Cecil/Mono.Cecil/MethodCallingConvention.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -// 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, - } -} diff --git a/Mono.Cecil/Mono.Cecil/MethodDefinition.cs b/Mono.Cecil/Mono.Cecil/MethodDefinition.cs deleted file mode 100644 index 90ac6999b..000000000 --- a/Mono.Cecil/Mono.Cecil/MethodDefinition.cs +++ /dev/null @@ -1,495 +0,0 @@ -// -// 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 volatile bool sem_attrs_ready; - internal MethodSemanticsAttributes sem_attrs; - Collection custom_attributes; - Collection security_declarations; - - internal RVA rva; - internal PInvokeInfo pinvoke; - Collection 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_ready) - return sem_attrs; - - if (HasImage) { - ReadSemantics (); - return sem_attrs; - } - - sem_attrs = MethodSemanticsAttributes.None; - sem_attrs_ready = true; - return sem_attrs; - } - set { sem_attrs = value; } - } - - internal void ReadSemantics () - { - if (sem_attrs_ready) - 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 SecurityDeclarations { - get { return security_declarations ?? (this.GetSecurityDeclarations (ref security_declarations, Module)); } - } - - public bool HasCustomAttributes { - get { - if (custom_attributes != null) - return custom_attributes.Count > 0; - - return this.GetHasCustomAttributes (Module); - } - } - - public Collection CustomAttributes { - get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, 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 { - MethodBody localBody = this.body; - if (localBody != null) - return localBody; - - if (!HasBody) - return null; - - if (HasImage && rva != 0) - return Module.Read (ref body, this, (method, reader) => reader.ReadMethodBody (method)); - - return body = new MethodBody (this); - } - set { - // we reset Body to null in ILSpy to save memory; so we need that operation to be thread-safe - lock (Module.SyncRoot) { - 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 Module.Read (ref pinvoke, 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 Overrides { - get { - if (overrides != null) - return overrides; - - if (HasImage) - return Module.Read (ref overrides, this, (method, reader) => reader.ReadOverrides (method)); - - return overrides = new Collection (); - } - } - - public override bool HasGenericParameters { - get { - if (generic_parameters != null) - return generic_parameters.Count > 0; - - return this.GetHasGenericParameters (Module); - } - } - - public override Collection GenericParameters { - get { return generic_parameters ?? (this.GetGenericParameters (ref generic_parameters, 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/MethodImplAttributes.cs b/Mono.Cecil/Mono.Cecil/MethodImplAttributes.cs deleted file mode 100644 index b24fcf704..000000000 --- a/Mono.Cecil/Mono.Cecil/MethodImplAttributes.cs +++ /dev/null @@ -1,53 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/MethodReference.cs b/Mono.Cecil/Mono.Cecil/MethodReference.cs deleted file mode 100644 index 0adab452e..000000000 --- a/Mono.Cecil/Mono.Cecil/MethodReference.cs +++ /dev/null @@ -1,214 +0,0 @@ -// -// 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 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 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 GenericParameters { - get { - if (generic_parameters != null) - return generic_parameters; - - return generic_parameters = new GenericParameterCollection (this); - } - } - - 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/MethodReturnType.cs b/Mono.Cecil/Mono.Cecil/MethodReturnType.cs deleted file mode 100644 index c9d260ef1..000000000 --- a/Mono.Cecil/Mono.Cecil/MethodReturnType.cs +++ /dev/null @@ -1,111 +0,0 @@ -// -// 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 System.Threading; - -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 { - if (parameter == null) - Interlocked.CompareExchange (ref parameter, new ParameterDefinition (return_type, method), null); - - return parameter; - } - } - - public MetadataToken MetadataToken { - get { return Parameter.MetadataToken; } - set { Parameter.MetadataToken = value; } - } - - public ParameterAttributes Attributes { - get { return Parameter.Attributes; } - set { Parameter.Attributes = value; } - } - - public bool HasCustomAttributes { - get { return parameter != null && parameter.HasCustomAttributes; } - } - - public Collection 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/MethodSemanticsAttributes.cs b/Mono.Cecil/Mono.Cecil/MethodSemanticsAttributes.cs deleted file mode 100644 index dd0f4742c..000000000 --- a/Mono.Cecil/Mono.Cecil/MethodSemanticsAttributes.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/MethodSpecification.cs b/Mono.Cecil/Mono.Cecil/MethodSpecification.cs deleted file mode 100644 index 73b5c14ad..000000000 --- a/Mono.Cecil/Mono.Cecil/MethodSpecification.cs +++ /dev/null @@ -1,103 +0,0 @@ -// -// 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 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 (); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/Modifiers.cs b/Mono.Cecil/Mono.Cecil/Modifiers.cs deleted file mode 100644 index ad31bc04f..000000000 --- a/Mono.Cecil/Mono.Cecil/Modifiers.cs +++ /dev/null @@ -1,137 +0,0 @@ -// -// 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"); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/ModuleDefinition.cs b/Mono.Cecil/Mono.Cecil/ModuleDefinition.cs deleted file mode 100644 index fc5b7a838..000000000 --- a/Mono.Cecil/Mono.Cecil/ModuleDefinition.cs +++ /dev/null @@ -1,1095 +0,0 @@ -// -// 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 System.Threading; -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; - IMetadataResolver metadata_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 IMetadataResolver MetadataResolver { - get { return metadata_resolver; } - set { metadata_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; - IMetadataResolver metadata_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 IMetadataResolver MetadataResolver { - get { return metadata_resolver; } - set { metadata_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 symbol_reader; - internal IAssemblyResolver assembly_resolver; - internal IMetadataResolver metadata_resolver; - internal TypeSystem type_system; - - readonly MetadataReader reader; - readonly string fq_name; - - internal ModuleKind kind; - TargetRuntime runtime; - TargetArchitecture architecture; - ModuleAttributes attributes; - ModuleCharacteristics characteristics; - Guid mvid; - - internal AssemblyDefinition assembly; - MethodDefinition entry_point; - -#if !READ_ONLY - MetadataImporter importer; -#endif - Collection custom_attributes; - Collection references; - Collection modules; - Collection resources; - Collection 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 ModuleCharacteristics Characteristics { - get { return characteristics; } - set { characteristics = 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 symbol_reader != null; } - } - - public ISymbolReader SymbolReader { - get { return symbol_reader; } - } - - public override MetadataScopeType MetadataScopeType { - get { return MetadataScopeType.ModuleDefinition; } - } - - public AssemblyDefinition Assembly { - get { return assembly; } - } - -#if !READ_ONLY - internal MetadataImporter MetadataImporter { - get { - if (importer == null) - Interlocked.CompareExchange (ref importer, new MetadataImporter (this), null); - return importer; - } - } -#endif - - public IAssemblyResolver AssemblyResolver { - get { return assembly_resolver ?? (assembly_resolver = new DefaultAssemblyResolver ()); } - } - - public IMetadataResolver MetadataResolver { - get { - if (metadata_resolver == null) - Interlocked.CompareExchange (ref metadata_resolver, new MetadataResolver (this.AssemblyResolver), null); - - return metadata_resolver; - } - } - - public TypeSystem TypeSystem { - get { - if (type_system == null) - Interlocked.CompareExchange (ref type_system, TypeSystem.CreateTypeSystem (this), null); - return type_system; - } - } - - public bool HasAssemblyReferences { - get { - if (references != null) - return references.Count > 0; - - return HasImage && Image.HasTable (Table.AssemblyRef); - } - } - - public Collection AssemblyReferences { - get { - if (references != null) - return references; - - if (HasImage) - return Read (ref references, this, (_, reader) => reader.ReadAssemblyReferences ()); - - return references = new Collection (); - } - } - - public bool HasModuleReferences { - get { - if (modules != null) - return modules.Count > 0; - - return HasImage && Image.HasTable (Table.ModuleRef); - } - } - - public Collection ModuleReferences { - get { - if (modules != null) - return modules; - - if (HasImage) - return Read (ref modules, this, (_, reader) => reader.ReadModuleReferences ()); - - return modules = new Collection (); - } - } - - 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 Resources { - get { - if (resources != null) - return resources; - - if (HasImage) - return Read (ref resources, this, (_, reader) => reader.ReadResources ()); - - return resources = new Collection (); - } - } - - public bool HasCustomAttributes { - get { - if (custom_attributes != null) - return custom_attributes.Count > 0; - - return this.GetHasCustomAttributes (this); - } - } - - public Collection CustomAttributes { - get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, this)); } - } - - public bool HasTypes { - get { - if (types != null) - return types.Count > 0; - - return HasImage && Image.HasTable (Table.TypeDef); - } - } - - public Collection Types { - get { - if (types != null) - return types; - - if (HasImage) - return Read (ref types, 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 ExportedTypes { - get { - if (exported_types != null) - return exported_types; - - if (HasImage) - return Read (ref exported_types, this, (_, reader) => reader.ReadExportedTypes ()); - - return exported_types = new Collection (); - } - } - - public MethodDefinition EntryPoint { - get { - if (entry_point != null) - return entry_point; - - if (HasImage) - return Read (ref entry_point, 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); - } - - 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.characteristics = image.Characteristics; - 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 (scope, fullname), (row, reader) => reader.GetTypeReference (row.Col1, row.Col2)); - } - - public IEnumerable GetTypeReferences () - { - if (!HasImage) - return Empty.Array; - - return Read (this, (_, reader) => reader.GetTypeReferences ()); - } - - public IEnumerable GetMemberReferences () - { - if (!HasImage) - return Empty.Array; - - return Read (this, (_, reader) => reader.GetMemberReferences ()); - } - - public TypeReference GetType (string fullName, bool runtimeName) - { - return runtimeName - ? TypeParser.ParseType (this, fullName) - : GetType (fullName); - } - - 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 GetTypes () - { - return GetTypes (Types); - } - - static IEnumerable GetTypes (Collection 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 (field); - } - - internal MethodDefinition Resolve (MethodReference method) - { - return MetadataResolver.Resolve (method); - } - - internal TypeDefinition Resolve (TypeReference type) - { - return MetadataResolver.Resolve (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)); - } - - readonly object module_lock = new object(); - - internal object SyncRoot { - get { return module_lock; } - } - - internal TRet Read (TItem item, Func read) - { - lock (module_lock) { - var position = reader.position; - var context = reader.context; - - var ret = read (item, reader); - - reader.position = position; - reader.context = context; - - return ret; - } - } - - internal TRet Read (ref TRet variable, TItem item, Func read) where TRet : class - { - lock (module_lock) { - if (variable != null) - return variable; - - var position = reader.position; - var context = reader.context; - - var ret = read (item, reader); - - reader.position = position; - reader.context = context; - - return variable = ret; - } - } - - public bool HasDebugHeader { - get { return Image != null && !Image.Debug.IsZero; } - } - - public ImageDebugDirectory GetDebugHeader (out byte [] header) - { - if (!HasDebugHeader) - throw new InvalidOperationException (); - - return Image.GetDebugHeader (out header); - } - - void ProcessDebugHeader () - { - if (!HasDebugHeader) - return; - - byte [] header; - var directory = GetDebugHeader (out header); - - if (!symbol_reader.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, - Characteristics = (ModuleCharacteristics) 0x8540, - }; - - if (parameters.AssemblyResolver != null) - module.assembly_resolver = parameters.AssemblyResolver; - - if (parameters.MetadataResolver != null) - module.metadata_resolver = parameters.MetadataResolver; - - if (parameters.Kind != ModuleKind.NetModule) { - var assembly = new AssemblyDefinition (); - module.assembly = assembly; - module.assembly.Name = CreateAssemblyName (name); - assembly.main_module = module; - } - - module.Types.Add (new TypeDefinition (string.Empty, "", TypeAttributes.NotPublic)); - - return module; - } - - static AssemblyNameDefinition CreateAssemblyName (string name) - { - if (name.EndsWith (".dll") || name.EndsWith (".exe")) - name = name.Substring (0, name.Length - 4); - - return new AssemblyNameDefinition (name, new Version (0, 0, 0, 0)); - } - -#endif - - public void ReadSymbols () - { - if (string.IsNullOrEmpty (fq_name)) - throw new InvalidOperationException (); - - var provider = SymbolProvider.GetPlatformReaderProvider (); - if (provider == null) - throw new InvalidOperationException (); - - ReadSymbols (provider.GetSymbolReader (this, fq_name)); - } - - public void ReadSymbols (ISymbolReader reader) - { - if (reader == null) - throw new ArgumentNullException ("reader"); - - symbol_reader = 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 bool IsCorlib (this ModuleDefinition module) - { - if (module.Assembly == null) - return false; - - return module.Assembly.Name.Name == "mscorlib"; - } - - 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; - } - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/ModuleKind.cs b/Mono.Cecil/Mono.Cecil/ModuleKind.cs deleted file mode 100644 index c29da887d..000000000 --- a/Mono.Cecil/Mono.Cecil/ModuleKind.cs +++ /dev/null @@ -1,64 +0,0 @@ -// -// 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, - ARMv7, - } - - [Flags] - public enum ModuleAttributes { - ILOnly = 1, - Required32Bit = 2, - StrongNameSigned = 8, - Preferred32Bit = 0x00020000, - } - - [Flags] - public enum ModuleCharacteristics { - HighEntropyVA = 0x0020, - DynamicBase = 0x0040, - NoSEH = 0x0400, - NXCompat = 0x0100, - AppContainer = 0x1000, - TerminalServerAware = 0x8000, - } -} diff --git a/Mono.Cecil/Mono.Cecil/ModuleReference.cs b/Mono.Cecil/Mono.Cecil/ModuleReference.cs deleted file mode 100644 index 3934b3ceb..000000000 --- a/Mono.Cecil/Mono.Cecil/ModuleReference.cs +++ /dev/null @@ -1,67 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/NativeType.cs b/Mono.Cecil/Mono.Cecil/NativeType.cs deleted file mode 100644 index 88da9805e..000000000 --- a/Mono.Cecil/Mono.Cecil/NativeType.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/PInvokeAttributes.cs b/Mono.Cecil/Mono.Cecil/PInvokeAttributes.cs deleted file mode 100644 index bb3683825..000000000 --- a/Mono.Cecil/Mono.Cecil/PInvokeAttributes.cs +++ /dev/null @@ -1,62 +0,0 @@ -// -// 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, - } -} diff --git a/Mono.Cecil/Mono.Cecil/PInvokeInfo.cs b/Mono.Cecil/Mono.Cecil/PInvokeInfo.cs deleted file mode 100644 index cfd817c8d..000000000 --- a/Mono.Cecil/Mono.Cecil/PInvokeInfo.cs +++ /dev/null @@ -1,138 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/ParameterAttributes.cs b/Mono.Cecil/Mono.Cecil/ParameterAttributes.cs deleted file mode 100644 index e0bc825d8..000000000 --- a/Mono.Cecil/Mono.Cecil/ParameterAttributes.cs +++ /dev/null @@ -1,45 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/ParameterDefinition.cs b/Mono.Cecil/Mono.Cecil/ParameterDefinition.cs deleted file mode 100644 index 928da8940..000000000 --- a/Mono.Cecil/Mono.Cecil/ParameterDefinition.cs +++ /dev/null @@ -1,164 +0,0 @@ -// -// 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 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.HasImplicitThis () ? index + 1 : index; - } - } - - public bool HasConstant { - get { - this.ResolveConstant (ref constant, parameter_type.Module); - - return constant != Mixin.NoValue; - } - set { if (!value) constant = Mixin.NoValue; } - } - - public object Constant { - get { return HasConstant ? constant : null; } - set { constant = value; } - } - - public bool HasCustomAttributes { - get { - if (custom_attributes != null) - return custom_attributes.Count > 0; - - return this.GetHasCustomAttributes (parameter_type.Module); - } - } - - public Collection CustomAttributes { - get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, 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 ?? (this.GetMarshalInfo (ref marshal_info, 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 - - internal ParameterDefinition (TypeReference parameterType, IMethodSignature method) - : this (string.Empty, ParameterAttributes.None, parameterType) - { - this.method = method; - } - - 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/ParameterDefinitionCollection.cs b/Mono.Cecil/Mono.Cecil/ParameterDefinitionCollection.cs deleted file mode 100644 index bd8b1c139..000000000 --- a/Mono.Cecil/Mono.Cecil/ParameterDefinitionCollection.cs +++ /dev/null @@ -1,80 +0,0 @@ -// -// 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 { - - 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/ParameterReference.cs b/Mono.Cecil/Mono.Cecil/ParameterReference.cs deleted file mode 100644 index 46b057cd9..000000000 --- a/Mono.Cecil/Mono.Cecil/ParameterReference.cs +++ /dev/null @@ -1,75 +0,0 @@ -// -// 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 (); - } -} diff --git a/Mono.Cecil/Mono.Cecil/PinnedType.cs b/Mono.Cecil/Mono.Cecil/PinnedType.cs deleted file mode 100644 index ff59cfb7e..000000000 --- a/Mono.Cecil/Mono.Cecil/PinnedType.cs +++ /dev/null @@ -1,53 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/PointerType.cs b/Mono.Cecil/Mono.Cecil/PointerType.cs deleted file mode 100644 index a142e1440..000000000 --- a/Mono.Cecil/Mono.Cecil/PointerType.cs +++ /dev/null @@ -1,61 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/PropertyAttributes.cs b/Mono.Cecil/Mono.Cecil/PropertyAttributes.cs deleted file mode 100644 index 1be0413f2..000000000 --- a/Mono.Cecil/Mono.Cecil/PropertyAttributes.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/PropertyDefinition.cs b/Mono.Cecil/Mono.Cecil/PropertyDefinition.cs deleted file mode 100644 index 39ffcbf66..000000000 --- a/Mono.Cecil/Mono.Cecil/PropertyDefinition.cs +++ /dev/null @@ -1,259 +0,0 @@ -// -// 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 custom_attributes; - - internal MethodDefinition get_method; - internal MethodDefinition set_method; - internal Collection 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 CustomAttributes { - get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, 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 OtherMethods { - get { - if (other_methods != null) - return other_methods; - - InitializeMethods (); - - if (other_methods != null) - return other_methods; - - return other_methods = new Collection (); - } - } - - 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 Parameters { - get { - InitializeMethods (); - - if (get_method != null) - return MirrorParameters (get_method, 0); - - if (set_method != null) - return MirrorParameters (set_method, 1); - - return new Collection (); - } - } - - static Collection MirrorParameters (MethodDefinition method, int bound) - { - var parameters = new Collection (); - 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 { - this.ResolveConstant (ref constant, Module); - - return constant != Mixin.NoValue; - } - set { if (!value) constant = Mixin.NoValue; } - } - - public object Constant { - get { return HasConstant ? constant : null; } - set { constant = value; } - } - - #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 () - { - var module = this.Module; - lock (module.SyncRoot) { - if (get_method != null || set_method != null) - return; - - if (!module.HasImage ()) - return; - - module.Read (this, (property, reader) => reader.ReadMethods (property)); - } - } - - public override PropertyDefinition Resolve () - { - return this; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/PropertyReference.cs b/Mono.Cecil/Mono.Cecil/PropertyReference.cs deleted file mode 100644 index 0dcfc952f..000000000 --- a/Mono.Cecil/Mono.Cecil/PropertyReference.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// 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 Parameters { - get; - } - - internal PropertyReference (string name, TypeReference propertyType) - : base (name) - { - if (propertyType == null) - throw new ArgumentNullException ("propertyType"); - - property_type = propertyType; - } - - public abstract PropertyDefinition Resolve (); - } -} diff --git a/Mono.Cecil/Mono.Cecil/ReferenceType.cs b/Mono.Cecil/Mono.Cecil/ReferenceType.cs deleted file mode 100644 index 7940c617c..000000000 --- a/Mono.Cecil/Mono.Cecil/ReferenceType.cs +++ /dev/null @@ -1,61 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/Resource.cs b/Mono.Cecil/Mono.Cecil/Resource.cs deleted file mode 100644 index eff7f41aa..000000000 --- a/Mono.Cecil/Mono.Cecil/Resource.cs +++ /dev/null @@ -1,76 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/SecurityDeclaration.cs b/Mono.Cecil/Mono.Cecil/SecurityDeclaration.cs deleted file mode 100644 index 4213ffd3f..000000000 --- a/Mono.Cecil/Mono.Cecil/SecurityDeclaration.cs +++ /dev/null @@ -1,192 +0,0 @@ -// -// 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 System.Threading; -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 SecurityDeclarations { get; } - } - - public sealed class SecurityAttribute : ICustomAttribute { - - TypeReference attribute_type; - - internal Collection fields; - internal Collection properties; - - public TypeReference AttributeType { - get { return attribute_type; } - set { attribute_type = value; } - } - - public bool HasFields { - get { return !fields.IsNullOrEmpty (); } - } - - public Collection Fields { - get { return fields ?? (fields = new Collection ()); } - } - - public bool HasProperties { - get { return !properties.IsNullOrEmpty (); } - } - - public Collection Properties { - get { return properties ?? (properties = new Collection ()); } - } - - public SecurityAttribute (TypeReference attributeType) - { - this.attribute_type = attributeType; - } - } - - public sealed class SecurityDeclaration { - - readonly internal uint signature; - byte [] blob; - readonly ModuleDefinition module; - - internal bool resolved; - SecurityAction action; - internal Collection security_attributes; - - public SecurityAction Action { - get { return action; } - set { action = value; } - } - - public bool HasSecurityAttributes { - get { - Resolve (); - - return !security_attributes.IsNullOrEmpty (); - } - } - - public Collection SecurityAttributes { - get { - Resolve (); - - return security_attributes ?? (security_attributes = new Collection ()); - } - } - - 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 SecurityDeclaration (SecurityAction action, byte [] blob) - { - this.action = action; - 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, (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)); - } - - public static Collection GetSecurityDeclarations ( - this ISecurityDeclarationProvider self, - ref Collection variable, - ModuleDefinition module) - { - return module.HasImage () - ? module.Read (ref variable, self, (provider, reader) => reader.ReadSecurityDeclarations (provider)) - : variable = new Collection(); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/SentinelType.cs b/Mono.Cecil/Mono.Cecil/SentinelType.cs deleted file mode 100644 index 664d75bfd..000000000 --- a/Mono.Cecil/Mono.Cecil/SentinelType.cs +++ /dev/null @@ -1,53 +0,0 @@ -// -// 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/TargetRuntime.cs b/Mono.Cecil/Mono.Cecil/TargetRuntime.cs deleted file mode 100644 index 9b49a5f77..000000000 --- a/Mono.Cecil/Mono.Cecil/TargetRuntime.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// 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, - } -} diff --git a/Mono.Cecil/Mono.Cecil/TypeAttributes.cs b/Mono.Cecil/Mono.Cecil/TypeAttributes.cs deleted file mode 100644 index 86fbc4dba..000000000 --- a/Mono.Cecil/Mono.Cecil/TypeAttributes.cs +++ /dev/null @@ -1,81 +0,0 @@ -// -// 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 - WindowsRuntime = 0x00004000, // Windows Runtime type - - // 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 - } -} diff --git a/Mono.Cecil/Mono.Cecil/TypeDefinition.cs b/Mono.Cecil/Mono.Cecil/TypeDefinition.cs deleted file mode 100644 index e19c7d8f4..000000000 --- a/Mono.Cecil/Mono.Cecil/TypeDefinition.cs +++ /dev/null @@ -1,518 +0,0 @@ -// -// 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.Cecil.Metadata; -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 interfaces; - Collection nested_types; - Collection methods; - Collection fields; - Collection events; - Collection properties; - Collection custom_attributes; - Collection 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 Interfaces { - get { - if (interfaces != null) - return interfaces; - - if (HasImage) - return Module.Read (ref interfaces, this, (type, reader) => reader.ReadInterfaces (type)); - - return interfaces = new Collection (); - } - } - - 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 NestedTypes { - get { - if (nested_types != null) - return nested_types; - - if (HasImage) - return Module.Read (ref nested_types, this, (type, reader) => reader.ReadNestedTypes (type)); - - return nested_types = new MemberDefinitionCollection (this); - } - } - - public bool HasMethods { - get { - if (methods != null) - return methods.Count > 0; - - if (HasImage) - return methods_range.Length > 0; - - return false; - } - } - - public Collection Methods { - get { - if (methods != null) - return methods; - - if (HasImage) - return Module.Read (ref methods, this, (type, reader) => reader.ReadMethods (type)); - - return methods = new MemberDefinitionCollection (this); - } - } - - public bool HasFields { - get { - if (fields != null) - return fields.Count > 0; - - if (HasImage) - return fields_range.Length > 0; - - return false; - } - } - - public Collection Fields { - get { - if (fields != null) - return fields; - - if (HasImage) - return Module.Read (ref fields, this, (type, reader) => reader.ReadFields (type)); - - return fields = new MemberDefinitionCollection (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 Events { - get { - if (events != null) - return events; - - if (HasImage) - return Module.Read (ref events, this, (type, reader) => reader.ReadEvents (type)); - - return events = new MemberDefinitionCollection (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 Properties { - get { - if (properties != null) - return properties; - - if (HasImage) - return Module.Read (ref properties, this, (type, reader) => reader.ReadProperties (type)); - - return properties = new MemberDefinitionCollection (this); - } - } - - public bool HasSecurityDeclarations { - get { - if (security_declarations != null) - return security_declarations.Count > 0; - - return this.GetHasSecurityDeclarations (Module); - } - } - - public Collection SecurityDeclarations { - get { return security_declarations ?? (this.GetSecurityDeclarations (ref security_declarations, Module)); } - } - - public bool HasCustomAttributes { - get { - if (custom_attributes != null) - return custom_attributes.Count > 0; - - return this.GetHasCustomAttributes (Module); - } - } - - public Collection CustomAttributes { - get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); } - } - - public override bool HasGenericParameters { - get { - if (generic_parameters != null) - return generic_parameters.Count > 0; - - return this.GetHasGenericParameters (Module); - } - } - - public override Collection GenericParameters { - get { return generic_parameters ?? (this.GetGenericParameters (ref generic_parameters, 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 IsWindowsRuntime { - get { return attributes.GetAttributes ((uint) TypeAttributes.WindowsRuntime); } - set { attributes = attributes.SetAttributes ((uint) TypeAttributes.WindowsRuntime, 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 IsPrimitive { - get { - ElementType primitive_etype; - return MetadataSystem.TryGetPrimitiveElementType (this, out primitive_etype); - } - } - - public override MetadataType MetadataType { - get { - ElementType primitive_etype; - if (MetadataSystem.TryGetPrimitiveElementType (this, out primitive_etype)) - return (MetadataType) primitive_etype; - - return base.MetadataType; - } - } - - 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/TypeDefinitionCollection.cs b/Mono.Cecil/Mono.Cecil/TypeDefinitionCollection.cs deleted file mode 100644 index eae712282..000000000 --- a/Mono.Cecil/Mono.Cecil/TypeDefinitionCollection.cs +++ /dev/null @@ -1,118 +0,0 @@ -// -// 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; - - sealed class TypeDefinitionCollection : Collection { - - readonly ModuleDefinition container; - readonly Dictionary name_cache; - - internal TypeDefinitionCollection (ModuleDefinition container) - { - this.container = container; - this.name_cache = new Dictionary (new RowEqualityComparer ()); - } - - internal TypeDefinitionCollection (ModuleDefinition container, int capacity) - : base (capacity) - { - this.container = container; - this.name_cache = new Dictionary (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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/TypeParser.cs b/Mono.Cecil/Mono.Cecil/TypeParser.cs deleted file mode 100644 index 3e633ea8d..000000000 --- a/Mono.Cecil/Mono.Cecil/TypeParser.cs +++ /dev/null @@ -1,555 +0,0 @@ -// -// 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 (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 (string.IsNullOrEmpty (fullname)) - 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.TryProcessPrimitiveTypeReference (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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/TypeReference.cs b/Mono.Cecil/Mono.Cecil/TypeReference.cs deleted file mode 100644 index ff28c636f..000000000 --- a/Mono.Cecil/Mono.Cecil/TypeReference.cs +++ /dev/null @@ -1,330 +0,0 @@ -// -// 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 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 GenericParameters { - get { - if (generic_parameters != null) - return generic_parameters; - - return generic_parameters = new GenericParameterCollection (this); - } - } - - 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 virtual bool IsPrimitive { - get { return etype.IsPrimitive (); } - } - - 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 IsPrimitive (this ElementType self) - { - switch (self) { - 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 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; - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/TypeSpecification.cs b/Mono.Cecil/Mono.Cecil/TypeSpecification.cs deleted file mode 100644 index aa9b653f0..000000000 --- a/Mono.Cecil/Mono.Cecil/TypeSpecification.cs +++ /dev/null @@ -1,94 +0,0 @@ -// -// 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"); - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/TypeSystem.cs b/Mono.Cecil/Mono.Cecil/TypeSystem.cs deleted file mode 100644 index 4fec5d58a..000000000 --- a/Mono.Cecil/Mono.Cecil/TypeSystem.cs +++ /dev/null @@ -1,300 +0,0 @@ -// -// 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 CoreTypeSystem : TypeSystem { - - public CoreTypeSystem (ModuleDefinition module) - : base (module) - { - } - - internal override TypeReference LookupType (string @namespace, string name) - { - var type = LookupTypeDefinition (@namespace, name) ?? LookupTypeForwarded (@namespace, name); - if (type != null) - return type; - - throw new NotSupportedException (); - } - - TypeReference LookupTypeDefinition (string @namespace, string name) - { - var metadata = module.MetadataSystem; - if (metadata.Types == null) - Initialize (module.Types); - - return module.Read (new Row (@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; - }); - } - - TypeReference LookupTypeForwarded (string @namespace, string name) - { - 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 == name && exported_type.Namespace == @namespace) - return exported_type.CreateReference (); - } - - 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"; - const string systemruntime = "System.Runtime"; - - var references = module.AssemblyReferences; - - for (int i = 0; i < references.Count; i++) { - var reference = references [i]; - if (reference.Name == mscorlib || reference.Name == systemruntime) - 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 (module.IsCorlib ()) - return new CoreTypeSystem (module); - - return new CommonTypeSystem (module); - } - - internal abstract TypeReference LookupType (string @namespace, string name); - - TypeReference LookupSystemType (ref TypeReference typeRef, string name, ElementType element_type) - { - lock (module.SyncRoot) { - if (typeRef != null) - return typeRef; - var type = LookupType ("System", name); - type.etype = element_type; - return typeRef = type; - } - } - - TypeReference LookupSystemValueType (ref TypeReference typeRef, string name, ElementType element_type) - { - lock (module.SyncRoot) { - if (typeRef != null) - return typeRef; - var type = LookupType ("System", name); - type.etype = element_type; - type.IsValueType = true; - return typeRef = 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 ?? (LookupSystemType (ref type_object, "Object", ElementType.Object)); } - } - - public TypeReference Void { - get { return type_void ?? (LookupSystemType (ref type_void, "Void", ElementType.Void)); } - } - - public TypeReference Boolean { - get { return type_bool ?? (LookupSystemValueType (ref type_bool, "Boolean", ElementType.Boolean)); } - } - - public TypeReference Char { - get { return type_char ?? (LookupSystemValueType (ref type_char, "Char", ElementType.Char)); } - } - - public TypeReference SByte { - get { return type_sbyte ?? (LookupSystemValueType (ref type_sbyte, "SByte", ElementType.I1)); } - } - - public TypeReference Byte { - get { return type_byte ?? (LookupSystemValueType (ref type_byte, "Byte", ElementType.U1)); } - } - - public TypeReference Int16 { - get { return type_int16 ?? (LookupSystemValueType (ref type_int16, "Int16", ElementType.I2)); } - } - - public TypeReference UInt16 { - get { return type_uint16 ?? (LookupSystemValueType (ref type_uint16, "UInt16", ElementType.U2)); } - } - - public TypeReference Int32 { - get { return type_int32 ?? (LookupSystemValueType (ref type_int32, "Int32", ElementType.I4)); } - } - - public TypeReference UInt32 { - get { return type_uint32 ?? (LookupSystemValueType (ref type_uint32, "UInt32", ElementType.U4)); } - } - - public TypeReference Int64 { - get { return type_int64 ?? (LookupSystemValueType (ref type_int64, "Int64", ElementType.I8)); } - } - - public TypeReference UInt64 { - get { return type_uint64 ?? (LookupSystemValueType (ref type_uint64, "UInt64", ElementType.U8)); } - } - - public TypeReference Single { - get { return type_single ?? (LookupSystemValueType (ref type_single, "Single", ElementType.R4)); } - } - - public TypeReference Double { - get { return type_double ?? (LookupSystemValueType (ref type_double, "Double", ElementType.R8)); } - } - - public TypeReference IntPtr { - get { return type_intptr ?? (LookupSystemValueType (ref type_intptr, "IntPtr", ElementType.I)); } - } - - public TypeReference UIntPtr { - get { return type_uintptr ?? (LookupSystemValueType (ref type_uintptr, "UIntPtr", ElementType.U)); } - } - - public TypeReference String { - get { return type_string ?? (LookupSystemType (ref type_string, "String", ElementType.String)); } - } - - public TypeReference TypedReference { - get { return type_typedref ?? (LookupSystemValueType (ref type_typedref, "TypedReference", ElementType.TypedByRef)); } - } - } -} diff --git a/Mono.Cecil/Mono.Cecil/VariantType.cs b/Mono.Cecil/Mono.Cecil/VariantType.cs deleted file mode 100644 index 76562f6e6..000000000 --- a/Mono.Cecil/Mono.Cecil/VariantType.cs +++ /dev/null @@ -1,53 +0,0 @@ -// -// 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 - } -} diff --git a/Mono.Cecil/Mono.Collections.Generic/Collection.cs b/Mono.Cecil/Mono.Collections.Generic/Collection.cs deleted file mode 100644 index 4d9271760..000000000 --- a/Mono.Cecil/Mono.Collections.Generic/Collection.cs +++ /dev/null @@ -1,420 +0,0 @@ -// -// 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 : IList, 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.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.Array; - } - - public Collection (int capacity) - { - if (capacity < 0) - throw new ArgumentOutOfRangeException (); - - items = new T [capacity]; - } - - public Collection (ICollection 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 IEnumerable.GetEnumerator () - { - return new Enumerator (this); - } - - public struct Enumerator : IEnumerator, IDisposable { - - Collection 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 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; - } - } - } -} diff --git a/Mono.Cecil/Mono.Collections.Generic/ReadOnlyCollection.cs b/Mono.Cecil/Mono.Collections.Generic/ReadOnlyCollection.cs deleted file mode 100644 index 7f24df699..000000000 --- a/Mono.Cecil/Mono.Collections.Generic/ReadOnlyCollection.cs +++ /dev/null @@ -1,112 +0,0 @@ -// -// 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 : Collection, ICollection, IList { - - static ReadOnlyCollection empty; - - public static ReadOnlyCollection Empty { - get { return empty ?? (empty = new ReadOnlyCollection ()); } - } - - bool ICollection.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 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 (); - } - } -} diff --git a/Mono.Cecil/Mono.Security.Cryptography/CryptoConvert.cs b/Mono.Cecil/Mono.Security.Cryptography/CryptoConvert.cs deleted file mode 100644 index 26a4ba25b..000000000 --- a/Mono.Cecil/Mono.Security.Cryptography/CryptoConvert.cs +++ /dev/null @@ -1,243 +0,0 @@ -// -// CryptoConvert.cs - Crypto Convertion Routines -// -// Author: -// Sebastien Pouliot -// -// (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 diff --git a/Mono.Cecil/Mono.Security.Cryptography/CryptoService.cs b/Mono.Cecil/Mono.Security.Cryptography/CryptoService.cs deleted file mode 100644 index 58b6cfabc..000000000 --- a/Mono.Cecil/Mono.Security.Cryptography/CryptoService.cs +++ /dev/null @@ -1,177 +0,0 @@ -// -// 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.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 diff --git a/Mono.Cecil/Mono/Actions.cs b/Mono.Cecil/Mono/Actions.cs deleted file mode 100644 index 756438f84..000000000 --- a/Mono.Cecil/Mono/Actions.cs +++ /dev/null @@ -1,38 +0,0 @@ -// -// 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 arg1, T2 arg2); - //delegate void Action (T1 arg1, T2 arg2, T3 arg3); - //delegate void Action (T1 arg1, T2 arg2, T3 arg3, T4 arg4); -} - -#endif diff --git a/Mono.Cecil/Mono/Empty.cs b/Mono.Cecil/Mono/Empty.cs deleted file mode 100644 index d043a35fa..000000000 --- a/Mono.Cecil/Mono/Empty.cs +++ /dev/null @@ -1,53 +0,0 @@ -// -// 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 { - - public static readonly T [] Array = new T [0]; - } -} - -namespace Mono.Cecil { - - static partial class Mixin { - - public static bool IsNullOrEmpty (this T [] self) - { - return self == null || self.Length == 0; - } - - public static bool IsNullOrEmpty (this Collection self) - { - return self == null || self.size == 0; - } - } -} diff --git a/Mono.Cecil/Mono/Funcs.cs b/Mono.Cecil/Mono/Funcs.cs deleted file mode 100644 index 87bc6e977..000000000 --- a/Mono.Cecil/Mono/Funcs.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// 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 (); - delegate TResult Func (T arg1); - delegate TResult Func (T1 arg1, T2 arg2); - //delegate TResult Func (T1 arg1, T2 arg2, T3 arg3); - //delegate TResult Func (T1 arg1, T2 arg2, T3 arg3, T4 arg4); -} - -#endif diff --git a/Mono.Cecil/NOTES.txt b/Mono.Cecil/NOTES.txt deleted file mode 100644 index 6f3618bcc..000000000 --- a/Mono.Cecil/NOTES.txt +++ /dev/null @@ -1,189 +0,0 @@ -namespaces: - - Mono.Cecil.Binary: deleted, - Mono.Cecil.Metadata: metadata table/rows: deleted. - -collections: - - * Cecil now only exposes Collection of T as a public collection API. - -types: - -Mono.Cecil - - - AssemblyFactory: - Use static Read methods on ModuleDefinition and AssemblyDefinition - to get them. - - + ReadingMode: - specifies if the assembly is either loaded in a deffered - or immediate fashion. - - + ReaderParameters - + ReadingMode - + ISymbolReaderProvider - - + WriterParameters - + ISymbolWriterProvider - - * AssemblyDefinition: - - * Runtime, Kind: moved to ModuleDefiniton - - * ModuleDefinition: - - properties: - - - Image - - MemberReferences - - TypeReferences - - ExternTypes - - * Main -> IsMain. (set removed) : bool - + FullyQualifiedName : string - + Kind : ModuleKind - + Runtime : TargetRuntime - + Architecture : TargetArchitecture - + Attributes : ModuleAttributes - + HasSymbols : bool - + HasExportedTypes : bool - + ExportedTypes : ExportedTypeCollection - - * Types: doesn't contain NestedTypes anymore. - - - AssemblyKind: - renamed to ModuleKind. - - + ModuleKind: - + NetModule - - + TargetArchitecture: - + I386 - + AMD64 - + IA64 - - + ModuleAttributes: - + ILOnly - + Required32Bit - + StrongNameSigned - - * FieldDefinition: - - * RVA : int - - * IMethodSignature: - * ReturnType : TypeReference - + MethodReturnType : MethodReturnType - - * TypeDefinition: - - HasConstructors - - Constructors - * ctor: swapped namespace and name parameter. - - * ParameterDefinition: - * Method : IMethodSignature - * Sequence -> Index : int (0 based instead of 1) - - * ArrayType: - * IsSizedArray -> IsVector : bool - - * IHasConstant -> IConstantProvider - * IHasSecurity -> ISecurityDeclarationProvider - * IHasMarshal -> IMarshalInfoProvider - - * MemberReference - + Module : ModuleDefinition - - * MethodDefinition: - - This: moved to MethodBody - + HasPInvokeInfo : bool - - * PInvokeInfo: - - Method - - * MarshalSpec -> MarshalInfo - - - ModType - - * ModifierRequiredType -> RequiredModifierType - * ModifierOptionalType -> OptionalModifierType - * ReferenceType -> ByReferenceType - - * TypeReference - + IsArray : bool - + IsPointer : bool - + IsByReference : bool - + IsRequiredModifier : bool - + IsOptionalModifier : bool - + IsSentinel : bool - + IsGenericInstance : bool - + IsGenericParameter : bool - + IsPinned : bool - + IsFunctionPointer : bool - + IsDefinition : bool - - * GetOriginalType -> GetElementType - * ctor: swapped namespace and name parameter. - - * MethodReference - + IsGenericInstance : bool - + IsDefinition : bool - - * GetOriginalMethod -> GetElementMethod - - * FieldReference - + IsDefinition : bool - - + CustomAttributeArgument - + Type : TypeReference - + Value : object - - * CustomAttribute - * ConstructorParameters -> ConstructorArguments : CustomAttributeArgumentCollection - * Properties : CustomAttributeNamedArgumentCollection - * Fields : CustomAttributeNamedArgumentCollection - - * SecurityDeclaration - - PermissionSet - + SecurityAttributes : SecurityAttributeCollection - - + SecurityAttribute - + AttributeType : TypeReference - + Fields : CustomAttributeNamedArgumentCollection - + Properties : CustomAttributeNamedArgumentCollection - - * IMetadataScope - + MetadataScopeType - - + MetadataScopeType - + AssemblyNameReference - + ModuleDefinition - + ModuleReference - -Mono.Cecil.Cil: - - * ExceptionHandler - * Type -> HandlerType : TypeReference - - * VariableDefinition - - Method - - * Document* : from Guid to enums, the reader/writers are responsible for assigning them. - - * MethodBody - * LocalVarToken : MetadataToken - * MaxStack -> MaxStackSize : int - + ThisParameter: from MethodDefinition - - * OperandType - * ShortInlineParam : ShortInlineArg - * InlineParam : InlineArg - - * CilWorker -> ILProcessor - -TODO: - - * Mono.Cecil.Rocks - * ILGenerator - - * HOWTOs diff --git a/Mono.Cecil/System.Runtime.CompilerServices/ExtensionAttribute.cs b/Mono.Cecil/System.Runtime.CompilerServices/ExtensionAttribute.cs deleted file mode 100644 index bb24f980d..000000000 --- a/Mono.Cecil/System.Runtime.CompilerServices/ExtensionAttribute.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -// 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 diff --git a/Mono.Cecil/Test/.gitignore b/Mono.Cecil/Test/.gitignore deleted file mode 100644 index 2b75ccefb..000000000 --- a/Mono.Cecil/Test/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -bin -obj -*.suo -*.user -*.xml -*.pidb -*.userprefs diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests.csproj b/Mono.Cecil/Test/Mono.Cecil.Tests.csproj deleted file mode 100644 index 2ff2951f8..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests.csproj +++ /dev/null @@ -1,179 +0,0 @@ - - - - net_4_0_Debug - AnyCPU - 9.0.30729 - 2.0 - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055} - Library - Properties - Mono.Cecil.Tests - Mono.Cecil.Tests - 512 - true - ..\mono.snk - - - true - full - false - bin\net_2_0_Debug\ - DEBUG;TRACE - prompt - 4 - v2.0 - - - pdbonly - true - bin\net_2_0_Release\ - TRACE - prompt - 4 - v2.0 - - - true - full - false - bin\net_3_5_Debug\ - DEBUG;TRACE;NET_3_5 - prompt - 4 - v3.5 - - - pdbonly - true - bin\net_3_5_Release\ - TRACE;NET_3_5 - prompt - 4 - v3.5 - - - true - full - false - bin\net_4_0_Debug\ - DEBUG;TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - pdbonly - true - bin\net_4_0_Release\ - TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - - - - - False - libs\nunit-2.5.10\nunit.core.dll - - - False - libs\nunit-2.5.10\nunit.core.interfaces.dll - - - False - libs\nunit-2.5.10\nunit.framework.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {D68133BD-1E63-496E-9EDE-4FBDBF77B486} - Mono.Cecil - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/Addin.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/Addin.cs deleted file mode 100644 index 38b02ceca..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/Addin.cs +++ /dev/null @@ -1,305 +0,0 @@ -using System; -using System.IO; -using System.Reflection; - -using NUnit.Core; -using NUnit.Core.Extensibility; - -using Mono.Cecil.Cil; - -namespace Mono.Cecil.Tests { - - public abstract class TestCecilAttribute : Attribute { - - bool verify = true; - Type symbol_reader_provider; - Type symbol_writer_provider; - - public bool Verify { - get { return verify; } - set { verify = value; } - } - - public Type SymbolReaderProvider { - get { return symbol_reader_provider; } - set { symbol_reader_provider = value; } - } - - public Type SymbolWriterProvider { - get { return symbol_writer_provider; } - set { symbol_writer_provider = value; } - } - - public abstract string GetModuleLocation (Assembly assembly); - } - - [AttributeUsage (AttributeTargets.Method, AllowMultiple = false)] - public sealed class TestModuleAttribute : TestCecilAttribute { - - readonly string module; - - public string Module { - get { return module; } - } - - public TestModuleAttribute (string assembly) - { - this.module = assembly; - } - - public override string GetModuleLocation (Assembly assembly) - { - return BaseTestFixture.GetAssemblyResourcePath (module, assembly); - } - } - - [AttributeUsage (AttributeTargets.Method, AllowMultiple = false)] - public sealed class TestCSharpAttribute : TestCecilAttribute { - - readonly string file; - - public string File { - get { return file; } - } - - public TestCSharpAttribute (string file) - { - this.file = file; - } - - public override string GetModuleLocation (Assembly assembly) - { - return CompilationService.CompileResource ( - BaseTestFixture.GetCSharpResourcePath (file, assembly)); - } - } - - [AttributeUsage (AttributeTargets.Method, AllowMultiple = false)] - public sealed class TestILAttribute : TestCecilAttribute { - - readonly string file; - - public string File { - get { return file; } - } - - public TestILAttribute (string file) - { - this.file = file; - } - - public override string GetModuleLocation (Assembly assembly) - { - return CompilationService.CompileResource ( - BaseTestFixture.GetILResourcePath (file, assembly)); - } - } - - class CecilTestCase : NUnitTestMethod { - - readonly TestCecilAttribute attribute; - readonly TestCaseType type; - - public CecilTestCase (MethodInfo method, TestCecilAttribute attribute, TestCaseType type) - : base (method) - { - this.TestName.Name = type.ToString (); - this.TestName.FullName = method.DeclaringType.FullName + "." + method.Name + "." + type; - this.attribute = attribute; - this.type = type; - } - - ModuleDefinition GetModule () - { - var location = attribute.GetModuleLocation (this.Method.DeclaringType.Assembly); - - var parameters = new ReaderParameters { - SymbolReaderProvider = GetSymbolReaderProvider (attribute), - }; - - switch (type) { - case TestCaseType.ReadImmediate: - parameters.ReadingMode = ReadingMode.Immediate; - return ModuleDefinition.ReadModule (location, parameters); - case TestCaseType.ReadDeferred: - parameters.ReadingMode = ReadingMode.Deferred; - return ModuleDefinition.ReadModule (location, parameters); - case TestCaseType.WriteFromImmediate: - parameters.ReadingMode = ReadingMode.Immediate; - return RoundTrip (location, parameters, "cecil-irt"); - case TestCaseType.WriteFromDeferred: - parameters.ReadingMode = ReadingMode.Deferred; - return RoundTrip (location, parameters, "cecil-drt"); - default: - return null; - } - } - - static ISymbolReaderProvider GetSymbolReaderProvider (TestCecilAttribute attribute) - { - if (attribute.SymbolReaderProvider == null) - return null; - - return (ISymbolReaderProvider) Activator.CreateInstance (attribute.SymbolReaderProvider); - } - - static ISymbolWriterProvider GetSymbolWriterProvider (TestCecilAttribute attribute) - { - if (attribute.SymbolReaderProvider == null) - return null; - - return (ISymbolWriterProvider) Activator.CreateInstance (attribute.SymbolWriterProvider); - } - - ModuleDefinition RoundTrip (string location, ReaderParameters reader_parameters, string folder) - { - var module = ModuleDefinition.ReadModule (location, reader_parameters); - var rt_folder = Path.Combine (Path.GetTempPath (), folder); - if (!Directory.Exists (rt_folder)) - Directory.CreateDirectory (rt_folder); - var rt_module = Path.Combine (rt_folder, Path.GetFileName (location)); - - var writer_parameters = new WriterParameters { - SymbolWriterProvider = GetSymbolWriterProvider (attribute), - }; - - Reflect.InvokeMethod (Method, Fixture, new object [] { module }); - - module.Write (rt_module, writer_parameters); - - if (attribute.Verify) - CompilationService.Verify (rt_module); - - return ModuleDefinition.ReadModule (rt_module, reader_parameters); - } - - public override TestResult RunTest () - { - var result = new TestResult (TestName); - var module = GetModule (); - if (module == null) - return result; - - Reflect.InvokeMethod (Method, Fixture, new object [] { module }); - - result.Success (); - return result; - } - } - - class CecilTestSuite : TestSuite { - - public CecilTestSuite (MethodInfo method) - : base (method.DeclaringType.FullName, method.Name) - { - } - - public override TestResult Run (EventListener listener, ITestFilter filter) - { - if (this.Parent != null) - this.Fixture = this.Parent.Fixture; - - return base.Run (listener, filter); - } - - protected override void DoOneTimeSetUp (TestResult suiteResult) - { - } - - protected override void DoOneTimeTearDown (TestResult suiteResult) - { - } - } - - enum TestCaseType { - ReadImmediate, - ReadDeferred, - WriteFromImmediate, - WriteFromDeferred, - } - - static class CecilTestFactory { - - public static CecilTestSuite CreateTestSuite (MethodInfo method) - { - if (method == null) - throw new ArgumentNullException ("method"); - - var suite = new CecilTestSuite (method); - - NUnitFramework.ApplyCommonAttributes (method, suite); - PopulateTestSuite (method, suite); - - return suite; - } - - static void PopulateTestSuite (MethodInfo method, CecilTestSuite suite) - { - var attribute = GetTestCecilAttribute (method); - if (attribute == null) - throw new ArgumentException (); - - foreach (var value in Enum.GetValues (typeof (TestCaseType))) { - var test = CreateTestCase (method, attribute, (TestCaseType) value); - if (test != null) - suite.Add (test); - } - } - - static CecilTestCase CreateTestCase (MethodInfo method, TestCecilAttribute attribute, TestCaseType type) - { - return new CecilTestCase (method, attribute, type); - } - - static TestCecilAttribute GetTestCecilAttribute (MethodInfo method) - { - foreach (var attribute in method.GetCustomAttributes (false)) { - var test = attribute as TestCecilAttribute; - if (test != null) - return test; - } - - return null; - } - } - - [NUnitAddin] - public class CecilTestAddin : IAddin, ITestCaseBuilder { - - public bool Install (IExtensionHost host) - { - if (host == null) - throw new ArgumentNullException ("host"); - - var builders = host.GetExtensionPoint ("TestCaseBuilders"); - if (builders == null) - return false; - - builders.Install (this); - return true; - } - - public Test BuildFrom (MethodInfo method) - { - if (method == null) - throw new ArgumentNullException ("method"); - - return CecilTestFactory.CreateTestSuite (method); - } - - public bool CanBuildFrom (MethodInfo method) - { - if (method == null) - return false; - - return IsCecilTestMethod (method); - } - - static bool IsCecilTestMethod (MethodInfo method) - { - return Reflect.HasAttribute (method, typeof (TestModuleAttribute).FullName, false) - || Reflect.HasAttribute (method, typeof (TestILAttribute).FullName, false) - || Reflect.HasAttribute (method, typeof (TestCSharpAttribute).FullName, false); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/AssemblyInfo.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/AssemblyInfo.cs deleted file mode 100644 index ad7488f77..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/AssemblyInfo.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -[assembly: AssemblyTitle ("Mono.Cecil.Tests")] -[assembly: AssemblyProduct ("Mono.Cecil")] -[assembly: AssemblyCopyright ("Copyright © 2008 - 2011 Jb Evain")] - -[assembly: ComVisible (false)] - -[assembly: Guid ("da96c202-696a-457e-89af-5fa74e6bda0d")] - -[assembly: AssemblyVersion ("1.0.0.0")] -[assembly: AssemblyFileVersion ("1.0.0.0")] diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/AssemblyTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/AssemblyTests.cs deleted file mode 100644 index 3267f77a6..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/AssemblyTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; - -using Mono.Cecil; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class AssemblyTests : BaseTestFixture { - - [TestModule ("hello.exe")] - public void Name (ModuleDefinition module) - { - var name = module.Assembly.Name; - - Assert.IsNotNull (name); - - Assert.AreEqual ("hello", name.Name); - Assert.AreEqual (string.Empty, name.Culture); - Assert.AreEqual (new Version (0, 0, 0, 0), name.Version); - Assert.AreEqual (AssemblyHashAlgorithm.SHA1, name.HashAlgorithm); - } - - [Test] - public void ParseLowerCaseNameParts() - { - var name = AssemblyNameReference.Parse ("Foo, version=2.0.0.0, culture=fr-FR"); - Assert.AreEqual ("Foo", name.Name); - Assert.AreEqual (2, name.Version.Major); - Assert.AreEqual (0, name.Version.Minor); - Assert.AreEqual ("fr-FR", name.Culture); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/BaseTestFixture.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/BaseTestFixture.cs deleted file mode 100644 index e160f48af..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/BaseTestFixture.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.IO; -using System.Reflection; - -using NUnit.Framework; - -using Mono.Cecil.PE; - -namespace Mono.Cecil.Tests { - - public abstract class BaseTestFixture { - - public static string GetResourcePath (string name, Assembly assembly) - { - return Path.Combine (FindResourcesDirectory (assembly), name); - } - - public static string GetAssemblyResourcePath (string name, Assembly assembly) - { - return GetResourcePath (Path.Combine ("assemblies", name), assembly); - } - - public static string GetCSharpResourcePath (string name, Assembly assembly) - { - return GetResourcePath (Path.Combine ("cs", name), assembly); - } - - public static string GetILResourcePath (string name, Assembly assembly) - { - return GetResourcePath (Path.Combine ("il", name), assembly); - } - - public static ModuleDefinition GetResourceModule (string name) - { - return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, typeof (BaseTestFixture).Assembly)); - } - - public static ModuleDefinition GetResourceModule (string name, ReaderParameters parameters) - { - return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, typeof (BaseTestFixture).Assembly), parameters); - } - - public static ModuleDefinition GetResourceModule (string name, ReadingMode mode) - { - return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, typeof (BaseTestFixture).Assembly), new ReaderParameters (mode)); - } - - internal static Image GetResourceImage (string name) - { - using (var fs = new FileStream (GetAssemblyResourcePath (name, typeof (BaseTestFixture).Assembly), FileMode.Open, FileAccess.Read)) - return ImageReader.ReadImageFrom (fs); - } - - public static ModuleDefinition GetCurrentModule () - { - return ModuleDefinition.ReadModule (typeof (BaseTestFixture).Module.FullyQualifiedName); - } - - public static ModuleDefinition GetCurrentModule (ReaderParameters parameters) - { - return ModuleDefinition.ReadModule (typeof (BaseTestFixture).Module.FullyQualifiedName, parameters); - } - - public static string FindResourcesDirectory (Assembly assembly) - { - var path = Path.GetDirectoryName (new Uri (assembly.CodeBase).LocalPath); - while (!Directory.Exists (Path.Combine (path, "Resources"))) { - var old = path; - path = Path.GetDirectoryName (path); - Assert.AreNotEqual (old, path); - } - - return Path.Combine (path, "Resources"); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/CompilationService.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/CompilationService.cs deleted file mode 100644 index 5a2def5cd..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/CompilationService.cs +++ /dev/null @@ -1,237 +0,0 @@ -using System; -using System.CodeDom.Compiler; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Text; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - struct CompilationResult { - internal DateTime source_write_time; - internal string result_file; - - public CompilationResult (DateTime write_time, string result_file) - { - this.source_write_time = write_time; - this.result_file = result_file; - } - } - - abstract class CompilationService { - - Dictionary files = new Dictionary (); - - bool TryGetResult (string name, out string file_result) - { - file_result = null; - CompilationResult result; - if (!files.TryGetValue (name, out result)) - return false; - - if (result.source_write_time != File.GetLastWriteTime (name)) - return false; - - file_result = result.result_file; - return true; - } - - public string Compile (string name) - { - string result_file; - if (TryGetResult (name, out result_file)) - return result_file; - - result_file = CompileFile (name); - RegisterFile (name, result_file); - return result_file; - } - - void RegisterFile (string name, string result_file) - { - files [name] = new CompilationResult (File.GetLastWriteTime (name), result_file); - } - - protected abstract string CompileFile (string name); - - public static string CompileResource (string name) - { - var extension = Path.GetExtension (name); - if (extension == ".il") - return IlasmCompilationService.Instance.Compile (name); - - if (extension == ".cs" || extension == ".vb") - return CodeDomCompilationService.Instance.Compile (name); - - throw new NotSupportedException (extension); - } - - protected static string GetCompiledFilePath (string file_name) - { - var tmp_cecil = Path.Combine (Path.GetTempPath (), "cecil"); - if (!Directory.Exists (tmp_cecil)) - Directory.CreateDirectory (tmp_cecil); - - return Path.Combine (tmp_cecil, Path.GetFileName (file_name) + ".dll"); - } - - static bool OnMono { get { return typeof (object).Assembly.GetType ("Mono.Runtime") != null; } } - - public static void Verify (string name) - { - var output = OnMono ? ShellService.PEDump (name) : ShellService.PEVerify (name); - if (output.ExitCode != 0) - Assert.Fail (output.ToString ()); - } - } - - class IlasmCompilationService : CompilationService { - - public static readonly IlasmCompilationService Instance = new IlasmCompilationService (); - - protected override string CompileFile (string name) - { - string file = GetCompiledFilePath (name); - - var output = ShellService.ILAsm (name, file); - - AssertAssemblerResult (output); - - return file; - } - - static void AssertAssemblerResult (ShellService.ProcessOutput output) - { - if (output.ExitCode != 0) - Assert.Fail (output.ToString ()); - } - } - - class CodeDomCompilationService : CompilationService { - - public static readonly CodeDomCompilationService Instance = new CodeDomCompilationService (); - - protected override string CompileFile (string name) - { - string file = GetCompiledFilePath (name); - - using (var provider = GetProvider (name)) { - var parameters = GetDefaultParameters (name); - parameters.IncludeDebugInformation = false; - parameters.GenerateExecutable = false; - parameters.OutputAssembly = file; - - var results = provider.CompileAssemblyFromFile (parameters, name); - AssertCompilerResults (results); - } - - return file; - } - - static void AssertCompilerResults (CompilerResults results) - { - Assert.IsFalse (results.Errors.HasErrors, GetErrorMessage (results)); - } - - static string GetErrorMessage (CompilerResults results) - { - if (!results.Errors.HasErrors) - return string.Empty; - - var builder = new StringBuilder (); - foreach (CompilerError error in results.Errors) - builder.AppendLine (error.ToString ()); - return builder.ToString (); - } - - static CompilerParameters GetDefaultParameters (string name) - { - return GetCompilerInfo (name).CreateDefaultCompilerParameters (); - } - - static CodeDomProvider GetProvider (string name) - { - return GetCompilerInfo (name).CreateProvider (); - } - - static CompilerInfo GetCompilerInfo (string name) - { - return CodeDomProvider.GetCompilerInfo ( - CodeDomProvider.GetLanguageFromExtension (Path.GetExtension (name))); - } - } - - class ShellService { - - public class ProcessOutput { - - public int ExitCode; - public string StdOut; - public string StdErr; - - public ProcessOutput (int exitCode, string stdout, string stderr) - { - ExitCode = exitCode; - StdOut = stdout; - StdErr = stderr; - } - - public override string ToString () - { - return StdOut + StdErr; - } - } - - static ProcessOutput RunProcess (string target, params string [] arguments) - { - var stdout = new StringWriter (); - var stderr = new StringWriter (); - - var process = new Process { - StartInfo = new ProcessStartInfo { - FileName = target, - Arguments = string.Join (" ", arguments), - CreateNoWindow = true, - UseShellExecute = false, - RedirectStandardError = true, - RedirectStandardInput = true, - RedirectStandardOutput = true, - }, - }; - - process.Start (); - - process.OutputDataReceived += (_, args) => stdout.Write (args.Data); - process.ErrorDataReceived += (_, args) => stderr.Write (args.Data); - - process.BeginOutputReadLine (); - process.BeginErrorReadLine (); - - process.WaitForExit (); - - return new ProcessOutput (process.ExitCode, stdout.ToString (), stderr.ToString ()); - } - - public static ProcessOutput ILAsm (string source, string output) - { - return RunProcess ("ilasm", "/nologo", "/dll", "/out:" + Quote (output), Quote (source)); - } - - static string Quote (string file) - { - return "\"" + file + "\""; - } - - public static ProcessOutput PEVerify (string source) - { - return RunProcess ("peverify", "/nologo", Quote (source)); - } - - public static ProcessOutput PEDump (string source) - { - return RunProcess ("pedump", "--verify code,metadata", Quote (source)); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/CustomAttributesTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/CustomAttributesTests.cs deleted file mode 100644 index 9682dadbf..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/CustomAttributesTests.cs +++ /dev/null @@ -1,519 +0,0 @@ -using System; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; - -using Mono.Cecil; -using Mono.Cecil.Metadata; -using Mono.Cecil.PE; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class CustomAttributesTests : BaseTestFixture { - - [TestCSharp ("CustomAttributes.cs")] - public void StringArgumentOnType (ModuleDefinition module) - { - var hamster = module.GetType ("Hamster"); - - Assert.IsTrue (hamster.HasCustomAttributes); - Assert.AreEqual (1, hamster.CustomAttributes.Count); - - var attribute = hamster.CustomAttributes [0]; - Assert.AreEqual ("System.Void FooAttribute::.ctor(System.String)", - attribute.Constructor.FullName); - - Assert.IsTrue (attribute.HasConstructorArguments); - Assert.AreEqual (1, attribute.ConstructorArguments.Count); - - AssertArgument ("bar", attribute.ConstructorArguments [0]); - } - - [TestCSharp ("CustomAttributes.cs")] - public void NullString (ModuleDefinition module) - { - var dentist = module.GetType ("Dentist"); - - var attribute = GetAttribute (dentist, "Foo"); - Assert.IsNotNull (attribute); - - AssertArgument (null, attribute.ConstructorArguments [0]); - } - - [TestCSharp ("CustomAttributes.cs")] - public void Primitives1 (ModuleDefinition module) - { - var steven = module.GetType ("Steven"); - - var attribute = GetAttribute (steven, "Foo"); - Assert.IsNotNull (attribute); - - AssertArgument (-12, attribute.ConstructorArguments [0]); - AssertArgument (242, attribute.ConstructorArguments [1]); - AssertArgument (true, attribute.ConstructorArguments [2]); - AssertArgument (false, attribute.ConstructorArguments [3]); - AssertArgument (4242, attribute.ConstructorArguments [4]); - AssertArgument (-1983, attribute.ConstructorArguments [5]); - AssertArgument ('c', attribute.ConstructorArguments [6]); - } - - [TestCSharp ("CustomAttributes.cs")] - public void Primitives2 (ModuleDefinition module) - { - var seagull = module.GetType ("Seagull"); - - var attribute = GetAttribute (seagull, "Foo"); - Assert.IsNotNull (attribute); - - AssertArgument (-100000, attribute.ConstructorArguments [0]); - AssertArgument (200000, attribute.ConstructorArguments [1]); - AssertArgument (12.12f, attribute.ConstructorArguments [2]); - AssertArgument (long.MaxValue, attribute.ConstructorArguments [3]); - AssertArgument (ulong.MaxValue, attribute.ConstructorArguments [4]); - AssertArgument (64.646464, attribute.ConstructorArguments [5]); - } - - [TestCSharp ("CustomAttributes.cs")] - public void StringArgumentOnAssembly (ModuleDefinition module) - { - var assembly = module.Assembly; - - var attribute = GetAttribute (assembly, "Foo"); - Assert.IsNotNull (attribute); - - AssertArgument ("bingo", attribute.ConstructorArguments [0]); - } - - [TestCSharp ("CustomAttributes.cs")] - public void CharArray (ModuleDefinition module) - { - var rifle = module.GetType ("Rifle"); - - var attribute = GetAttribute (rifle, "Foo"); - Assert.IsNotNull (attribute); - - var argument = attribute.ConstructorArguments [0]; - - Assert.AreEqual ("System.Char[]", argument.Type.FullName); - - var array = argument.Value as CustomAttributeArgument []; - Assert.IsNotNull (array); - - var str = "cecil"; - - Assert.AreEqual (array.Length, str.Length); - - for (int i = 0; i < str.Length; i++) - AssertArgument (str [i], array [i]); - } - - [TestCSharp ("CustomAttributes.cs")] - public void BoxedArguments (ModuleDefinition module) - { - var worm = module.GetType ("Worm"); - - var attribute = GetAttribute (worm, "Foo"); - Assert.IsNotNull (attribute); - - Assert.AreEqual (".ctor ((Object:(String:\"2\")), (Object:(I4:2)))", PrettyPrint (attribute)); - } - - [TestCSharp ("CustomAttributes.cs")] - public void BoxedArraysArguments (ModuleDefinition module) - { - var sheep = module.GetType ("Sheep"); - - var attribute = GetAttribute (sheep, "Foo"); - Assert.IsNotNull (attribute); - - // [Foo (new object [] { "2", 2, 'c' }, new object [] { new object [] { 1, 2, 3}, null })] - AssertCustomAttribute (".ctor ((Object:(Object[]:{(Object:(String:\"2\")), (Object:(I4:2)), (Object:(Char:'c'))})), (Object:(Object[]:{(Object:(Object[]:{(Object:(I4:1)), (Object:(I4:2)), (Object:(I4:3))})), (Object:(String:null))})))", attribute); - } - - [TestCSharp ("CustomAttributes.cs")] - public void FieldsAndProperties (ModuleDefinition module) - { - var angola = module.GetType ("Angola"); - - var attribute = GetAttribute (angola, "Foo"); - Assert.IsNotNull (attribute); - - Assert.AreEqual (2, attribute.Fields.Count); - - var argument = attribute.Fields.Where (a => a.Name == "Pan").First (); - AssertCustomAttributeArgument ("(Object:(Object[]:{(Object:(I4:1)), (Object:(String:\"2\")), (Object:(Char:'3'))}))", argument); - - argument = attribute.Fields.Where (a => a.Name == "PanPan").First (); - AssertCustomAttributeArgument ("(String[]:{(String:\"yo\"), (String:\"yo\")})", argument); - - Assert.AreEqual (2, attribute.Properties.Count); - - argument = attribute.Properties.Where (a => a.Name == "Bang").First (); - AssertArgument (42, argument); - - argument = attribute.Properties.Where (a => a.Name == "Fiou").First (); - AssertArgument (null, argument); - } - - [TestCSharp ("CustomAttributes.cs")] - public void BoxedStringField (ModuleDefinition module) - { - var type = module.GetType ("BoxedStringField"); - - var attribute = GetAttribute (type, "Foo"); - Assert.IsNotNull (attribute); - - Assert.AreEqual (1, attribute.Fields.Count); - - var argument = attribute.Fields.Where (a => a.Name == "Pan").First (); - AssertCustomAttributeArgument ("(Object:(String:\"fiouuu\"))", argument); - } - - [TestCSharp ("CustomAttributes.cs")] - public void TypeDefinitionEnum (ModuleDefinition module) - { - var zero = module.GetType ("Zero"); - - var attribute = GetAttribute (zero, "Foo"); - Assert.IsNotNull (attribute); - - Assert.AreEqual (1, attribute.ConstructorArguments.Count); - - Assert.AreEqual ((short) 2, attribute.ConstructorArguments [0].Value); - Assert.AreEqual ("Bingo", attribute.ConstructorArguments [0].Type.FullName); - } - - [TestCSharp ("CustomAttributes.cs")] - public void TypeReferenceEnum (ModuleDefinition module) - { - var ace = module.GetType ("Ace"); - - var attribute = GetAttribute (ace, "Foo"); - Assert.IsNotNull (attribute); - - Assert.AreEqual (1, attribute.ConstructorArguments.Count); - - Assert.AreEqual ((byte) 0x04, attribute.ConstructorArguments [0].Value); - Assert.AreEqual ("System.Security.AccessControl.AceFlags", attribute.ConstructorArguments [0].Type.FullName); - Assert.AreEqual (module, attribute.ConstructorArguments [0].Type.Module); - } - - [TestCSharp ("CustomAttributes.cs")] - public void BoxedEnumReference (ModuleDefinition module) - { - var bzzz = module.GetType ("Bzzz"); - - var attribute = GetAttribute (bzzz, "Foo"); - Assert.IsNotNull (attribute); - - // [Foo (new object [] { Bingo.Fuel, Bingo.Binga }, null, Pan = System.Security.AccessControl.AceFlags.NoPropagateInherit)] - - Assert.AreEqual (2, attribute.ConstructorArguments.Count); - - var argument = attribute.ConstructorArguments [0]; - - AssertCustomAttributeArgument ("(Object:(Object[]:{(Object:(Bingo:2)), (Object:(Bingo:4))}))", argument); - - argument = attribute.ConstructorArguments [1]; - - AssertCustomAttributeArgument ("(Object:(String:null))", argument); - - argument = attribute.Fields.Where (a => a.Name == "Pan").First ().Argument; - - AssertCustomAttributeArgument ("(Object:(System.Security.AccessControl.AceFlags:4))", argument); - } - - [TestCSharp ("CustomAttributes.cs")] - public void TypeOfTypeDefinition (ModuleDefinition module) - { - var typed = module.GetType ("Typed"); - - var attribute = GetAttribute (typed, "Foo"); - Assert.IsNotNull (attribute); - - Assert.AreEqual (1, attribute.ConstructorArguments.Count); - - var argument = attribute.ConstructorArguments [0]; - - Assert.AreEqual ("System.Type", argument.Type.FullName); - - var type = argument.Value as TypeDefinition; - Assert.IsNotNull (type); - - Assert.AreEqual ("Bingo", type.FullName); - } - - [TestCSharp ("CustomAttributes.cs")] - public void TypeOfNestedTypeDefinition (ModuleDefinition module) - { - var typed = module.GetType ("NestedTyped"); - - var attribute = GetAttribute (typed, "Foo"); - Assert.IsNotNull (attribute); - - Assert.AreEqual (1, attribute.ConstructorArguments.Count); - - var argument = attribute.ConstructorArguments [0]; - - Assert.AreEqual ("System.Type", argument.Type.FullName); - - var type = argument.Value as TypeDefinition; - Assert.IsNotNull (type); - - Assert.AreEqual ("FooAttribute/Token", type.FullName); - } - - [TestCSharp ("CustomAttributes.cs")] - public void FieldTypeOf (ModuleDefinition module) - { - var truc = module.GetType ("Truc"); - - var attribute = GetAttribute (truc, "Foo"); - Assert.IsNotNull (attribute); - - var argument = attribute.Fields.Where (a => a.Name == "Chose").First ().Argument; - - Assert.AreEqual ("System.Type", argument.Type.FullName); - - var type = argument.Value as TypeDefinition; - Assert.IsNotNull (type); - - Assert.AreEqual ("Typed", type.FullName); - } - - [TestCSharp ("CustomAttributes.cs")] - public void FieldNullTypeOf (ModuleDefinition module) - { - var truc = module.GetType ("Machin"); - - var attribute = GetAttribute (truc, "Foo"); - Assert.IsNotNull (attribute); - - var argument = attribute.Fields.Where (a => a.Name == "Chose").First ().Argument; - - Assert.AreEqual ("System.Type", argument.Type.FullName); - - Assert.IsNull (argument.Value); - } - - [TestCSharp ("CustomAttributes.cs")] - public void OpenGenericTypeOf (ModuleDefinition module) - { - var open_generic = module.GetType ("OpenGeneric`2"); - Assert.IsNotNull (open_generic); - - var attribute = GetAttribute (open_generic, "Foo"); - Assert.IsNotNull (attribute); - - Assert.AreEqual (1, attribute.ConstructorArguments.Count); - - var argument = attribute.ConstructorArguments [0]; - - Assert.AreEqual ("System.Type", argument.Type.FullName); - - var type = argument.Value as TypeReference; - Assert.IsNotNull (type); - - Assert.AreEqual ("System.Collections.Generic.Dictionary`2", type.FullName); - } - - [TestCSharp ("CustomAttributes.cs")] - public void ClosedGenericTypeOf (ModuleDefinition module) - { - var closed_generic = module.GetType ("ClosedGeneric"); - Assert.IsNotNull (closed_generic); - - var attribute = GetAttribute (closed_generic, "Foo"); - Assert.IsNotNull (attribute); - - Assert.AreEqual (1, attribute.ConstructorArguments.Count); - - var argument = attribute.ConstructorArguments [0]; - - Assert.AreEqual ("System.Type", argument.Type.FullName); - - var type = argument.Value as TypeReference; - Assert.IsNotNull (type); - - Assert.AreEqual ("System.Collections.Generic.Dictionary`2[,]>", type.FullName); - } - - [TestIL ("types.il")] - public void EmptyBlob (ModuleDefinition module) - { - var attribute = module.GetType ("CustomAttribute"); - Assert.AreEqual (1, attribute.CustomAttributes.Count); - Assert.AreEqual (0, attribute.CustomAttributes [0].ConstructorArguments.Count); - } - - [Test] - public void DefineCustomAttributeFromBlob () - { - var file = Path.Combine (Path.GetTempPath (), "CaBlob.dll"); - - var module = ModuleDefinition.CreateModule ("CaBlob.dll", new ModuleParameters { Kind = ModuleKind.Dll, Runtime = TargetRuntime.Net_2_0 }); - var assembly_title_ctor = module.Import (typeof (System.Reflection.AssemblyTitleAttribute).GetConstructor (new [] {typeof (string)})); - - Assert.IsNotNull (assembly_title_ctor); - - var buffer = new ByteBuffer (); - buffer.WriteUInt16 (1); // ca signature - - var title = Encoding.UTF8.GetBytes ("CaBlob"); - - buffer.WriteCompressedUInt32 ((uint) title.Length); - buffer.WriteBytes (title); - - buffer.WriteUInt16 (0); // named arguments - - var blob = new byte [buffer.length]; - Buffer.BlockCopy (buffer.buffer, 0, blob, 0, buffer.length); - - var attribute = new CustomAttribute (assembly_title_ctor, blob); - module.Assembly.CustomAttributes.Add (attribute); - - module.Write (file); - - module = ModuleDefinition.ReadModule (file); - - attribute = GetAttribute (module.Assembly, "AssemblyTitle"); - - Assert.IsNotNull (attribute); - Assert.AreEqual ("CaBlob", (string) attribute.ConstructorArguments [0].Value); - } - - static void AssertCustomAttribute (string expected, CustomAttribute attribute) - { - Assert.AreEqual (expected, PrettyPrint (attribute)); - } - - static void AssertCustomAttributeArgument (string expected, CustomAttributeNamedArgument named_argument) - { - AssertCustomAttributeArgument (expected, named_argument.Argument); - } - - static void AssertCustomAttributeArgument (string expected, CustomAttributeArgument argument) - { - var result = new StringBuilder (); - PrettyPrint (argument, result); - - Assert.AreEqual (expected, result.ToString ()); - } - - static string PrettyPrint (CustomAttribute attribute) - { - var signature = new StringBuilder (); - signature.Append (".ctor ("); - - for (int i = 0; i < attribute.ConstructorArguments.Count; i++) { - if (i > 0) - signature.Append (", "); - - PrettyPrint (attribute.ConstructorArguments [i], signature); - } - - signature.Append (")"); - return signature.ToString (); - } - - static void PrettyPrint (CustomAttributeArgument argument, StringBuilder signature) - { - var value = argument.Value; - - signature.Append ("("); - - PrettyPrint (argument.Type, signature); - - signature.Append (":"); - - PrettyPrintValue (argument.Value, signature); - - signature.Append (")"); - } - - static void PrettyPrintValue (object value, StringBuilder signature) - { - if (value == null) { - signature.Append ("null"); - return; - } - - var arguments = value as CustomAttributeArgument []; - if (arguments != null) { - signature.Append ("{"); - for (int i = 0; i < arguments.Length; i++) { - if (i > 0) - signature.Append (", "); - - PrettyPrint (arguments [i], signature); - } - signature.Append ("}"); - - return; - } - - switch (Type.GetTypeCode (value.GetType ())) { - case TypeCode.String: - signature.AppendFormat ("\"{0}\"", value); - break; - case TypeCode.Char: - signature.AppendFormat ("'{0}'", (char) value); - break; - default: - var formattable = value as IFormattable; - if (formattable != null) { - signature.Append (formattable.ToString (null, CultureInfo.InvariantCulture)); - return; - } - - if (value is CustomAttributeArgument) { - PrettyPrint ((CustomAttributeArgument) value, signature); - return; - } - break; - } - } - - static void PrettyPrint (TypeReference type, StringBuilder signature) - { - if (type.IsArray) { - ArrayType array = (ArrayType) type; - signature.AppendFormat ("{0}[]", array.ElementType.etype.ToString ()); - } else if (type.etype == ElementType.None) { - signature.Append (type.FullName); - } else - signature.Append (type.etype.ToString ()); - } - - static void AssertArgument (T value, CustomAttributeNamedArgument named_argument) - { - AssertArgument (value, named_argument.Argument); - } - - static void AssertArgument (T value, CustomAttributeArgument argument) - { - AssertArgument (typeof (T).FullName, (object) value, argument); - } - - static void AssertArgument (string type, object value, CustomAttributeArgument argument) - { - Assert.AreEqual (type, argument.Type.FullName); - Assert.AreEqual (value, argument.Value); - } - - static CustomAttribute GetAttribute (ICustomAttributeProvider owner, string type) - { - Assert.IsTrue (owner.HasCustomAttributes); - - foreach (var attribute in owner.CustomAttributes) - if (attribute.Constructor.DeclaringType.Name.StartsWith (type)) - return attribute; - - return null; - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/EventTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/EventTests.cs deleted file mode 100644 index 15a599c58..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/EventTests.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; - -using Mono.Cecil; -using Mono.Cecil.Metadata; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class EventTests : BaseTestFixture { - - [TestCSharp ("Events.cs")] - public void AbstractMethod (ModuleDefinition module) - { - var type = module.GetType ("Foo"); - - Assert.IsTrue (type.HasEvents); - - var events = type.Events; - - Assert.AreEqual (1, events.Count); - - var @event = events [0]; - - Assert.IsNotNull (@event); - Assert.AreEqual ("Bar", @event.Name); - Assert.IsNotNull (@event.EventType); - Assert.AreEqual ("Pan", @event.EventType.FullName); - - Assert.IsNotNull (@event.AddMethod); - Assert.AreEqual (MethodSemanticsAttributes.AddOn, @event.AddMethod.SemanticsAttributes); - Assert.IsNotNull (@event.RemoveMethod); - Assert.AreEqual (MethodSemanticsAttributes.RemoveOn, @event.RemoveMethod.SemanticsAttributes); - } - - [TestIL ("others.il")] - public void OtherMethod (ModuleDefinition module) - { - var type = module.GetType ("Others"); - - Assert.IsTrue (type.HasEvents); - - var events = type.Events; - - Assert.AreEqual (1, events.Count); - - var @event = events [0]; - - Assert.IsNotNull (@event); - Assert.AreEqual ("Handler", @event.Name); - Assert.IsNotNull (@event.EventType); - Assert.AreEqual ("System.EventHandler", @event.EventType.FullName); - - Assert.IsTrue (@event.HasOtherMethods); - - Assert.AreEqual (2, @event.OtherMethods.Count); - - var other = @event.OtherMethods [0]; - Assert.AreEqual ("dang_Handler", other.Name); - - other = @event.OtherMethods [1]; - Assert.AreEqual ("fang_Handler", other.Name); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/Extensions.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/Extensions.cs deleted file mode 100644 index 0788d21bc..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/Extensions.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using System.Linq; -using SR = System.Reflection; - -using Mono.Cecil; - -namespace Mono.Cecil.Tests { - - public static class Extensions { - - public static MethodDefinition GetMethod (this TypeDefinition self, string name) - { - return self.Methods.Where (m => m.Name == name).First (); - } - - public static FieldDefinition GetField (this TypeDefinition self, string name) - { - return self.Fields.Where (f => f.Name == name).First (); - } - - public static TypeDefinition ToDefinition (this Type self) - { - var module = ModuleDefinition.ReadModule (self.Module.FullyQualifiedName); - return (TypeDefinition) module.LookupToken (self.MetadataToken); - } - - public static MethodDefinition ToDefinition (this SR.MethodBase method) - { - var declaring_type = method.DeclaringType.ToDefinition (); - return (MethodDefinition) declaring_type.Module.LookupToken (method.MetadataToken); - } - - public static FieldDefinition ToDefinition (this SR.FieldInfo field) - { - var declaring_type = field.DeclaringType.ToDefinition (); - return (FieldDefinition) declaring_type.Module.LookupToken (field.MetadataToken); - } - - public static TypeReference MakeGenericType (this TypeReference self, params TypeReference [] arguments) - { - if (self.GenericParameters.Count != arguments.Length) - throw new ArgumentException (); - - var instance = new GenericInstanceType (self); - foreach (var argument in arguments) - instance.GenericArguments.Add (argument); - - return instance; - } - - public static MethodReference MakeGenericMethod (this MethodReference self, params TypeReference [] arguments) - { - if (self.GenericParameters.Count != arguments.Length) - throw new ArgumentException (); - - var instance = new GenericInstanceMethod (self); - foreach (var argument in arguments) - instance.GenericArguments.Add (argument); - - return instance; - } - - public static MethodReference MakeGeneric (this MethodReference self, params TypeReference [] arguments) - { - var reference = new MethodReference { - Name = self.Name, - DeclaringType = self.DeclaringType.MakeGenericType (arguments), - HasThis = self.HasThis, - ExplicitThis = self.ExplicitThis, - ReturnType = self.ReturnType, - CallingConvention = self.CallingConvention, - }; - - foreach (var parameter in self.Parameters) - reference.Parameters.Add (new ParameterDefinition (parameter.ParameterType)); - - foreach (var generic_parameter in self.GenericParameters) - reference.GenericParameters.Add (new GenericParameter (generic_parameter.Name, reference)); - - return reference; - } - - public static FieldReference MakeGeneric (this FieldReference self, params TypeReference [] arguments) - { - return new FieldReference { - Name = self.Name, - DeclaringType = self.DeclaringType.MakeGenericType (arguments), - FieldType = self.FieldType, - }; - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/FieldTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/FieldTests.cs deleted file mode 100644 index 8c6345688..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/FieldTests.cs +++ /dev/null @@ -1,333 +0,0 @@ -using System; - -using Mono.Cecil; -using Mono.Cecil.Metadata; -using Mono.Cecil.PE; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class FieldTests : BaseTestFixture { - - [TestCSharp ("Fields.cs")] - public void TypeDefField (ModuleDefinition module) - { - var type = module.Types [1]; - Assert.AreEqual ("Foo", type.Name); - Assert.AreEqual (1, type.Fields.Count); - - var field = type.Fields [0]; - Assert.AreEqual ("bar", field.Name); - Assert.AreEqual (1, field.MetadataToken.RID); - Assert.IsNotNull (field.FieldType); - Assert.AreEqual ("Bar", field.FieldType.FullName); - Assert.AreEqual (TokenType.Field, field.MetadataToken.TokenType); - Assert.IsFalse (field.HasConstant); - Assert.IsNull (field.Constant); - } - - [TestCSharp ("Fields.cs")] - public void PrimitiveTypes (ModuleDefinition module) - { - var type = module.GetType ("Baz"); - - AssertField (type, "char", typeof (char)); - AssertField (type, "bool", typeof (bool)); - AssertField (type, "sbyte", typeof (sbyte)); - AssertField (type, "byte", typeof (byte)); - AssertField (type, "int16", typeof (short)); - AssertField (type, "uint16", typeof (ushort)); - AssertField (type, "int32", typeof (int)); - AssertField (type, "uint32", typeof (uint)); - AssertField (type, "int64", typeof (long)); - AssertField (type, "uint64", typeof (ulong)); - AssertField (type, "single", typeof (float)); - AssertField (type, "double", typeof (double)); - AssertField (type, "string", typeof (string)); - AssertField (type, "object", typeof (object)); - } - - [TestCSharp ("Fields.cs")] - public void VolatileField (ModuleDefinition module) - { - var type = module.GetType ("Bar"); - - Assert.IsTrue (type.HasFields); - Assert.AreEqual (1, type.Fields.Count); - - var field = type.Fields [0]; - - Assert.AreEqual ("oiseau", field.Name); - Assert.AreEqual ("System.Int32 modreq(System.Runtime.CompilerServices.IsVolatile)", field.FieldType.FullName); - - Assert.IsFalse (field.HasConstant); - } - - [TestCSharp ("Layouts.cs")] - public void FieldLayout (ModuleDefinition module) - { - var foo = module.GetType ("Foo"); - Assert.IsNotNull (foo); - - Assert.IsTrue (foo.HasFields); - - var fields = foo.Fields; - - var field = fields [0]; - - Assert.AreEqual ("Bar", field.Name); - Assert.IsTrue (field.HasLayoutInfo); - Assert.AreEqual (0, field.Offset); - - field = fields [1]; - - Assert.AreEqual ("Baz", field.Name); - Assert.IsTrue (field.HasLayoutInfo); - Assert.AreEqual (2, field.Offset); - - field = fields [2]; - - Assert.AreEqual ("Gazonk", field.Name); - Assert.IsTrue (field.HasLayoutInfo); - Assert.AreEqual (4, field.Offset); - } - - [TestCSharp ("Layouts.cs")] - public void FieldRVA (ModuleDefinition module) - { - var priv_impl = GetPrivateImplementationType (module); - Assert.IsNotNull (priv_impl); - - Assert.AreEqual (1, priv_impl.Fields.Count); - - var field = priv_impl.Fields [0]; - - Assert.IsNotNull (field); - Assert.AreNotEqual (0, field.RVA); - Assert.IsNotNull (field.InitialValue); - Assert.AreEqual (16, field.InitialValue.Length); - - var buffer = new ByteBuffer (field.InitialValue); - - Assert.AreEqual (1, buffer.ReadUInt32 ()); - Assert.AreEqual (2, buffer.ReadUInt32 ()); - Assert.AreEqual (3, buffer.ReadUInt32 ()); - Assert.AreEqual (4, buffer.ReadUInt32 ()); - } - - [TestCSharp ("Generics.cs")] - public void GenericFieldDefinition (ModuleDefinition module) - { - var bar = module.GetType ("Bar`1"); - Assert.IsNotNull (bar); - - Assert.IsTrue (bar.HasGenericParameters); - var t = bar.GenericParameters [0]; - - Assert.AreEqual ("T", t.Name); - Assert.AreEqual (t.Owner, bar); - - var bang = bar.GetField ("bang"); - - Assert.IsNotNull (bang); - - Assert.AreEqual (t, bang.FieldType); - } - - [TestIL ("types.il")] - public void ArrayFields (ModuleDefinition module) - { - var types = module.GetType ("Types"); - Assert.IsNotNull (types); - - var rank_two = types.GetField ("rank_two"); - - var array = rank_two.FieldType as ArrayType; - Assert.IsNotNull (array); - - Assert.AreEqual (2, array.Rank); - Assert.IsFalse (array.Dimensions [0].IsSized); - Assert.IsFalse (array.Dimensions [1].IsSized); - - var rank_two_low_bound_zero = types.GetField ("rank_two_low_bound_zero"); - - array = rank_two_low_bound_zero.FieldType as ArrayType; - Assert.IsNotNull (array); - - Assert.AreEqual (2, array.Rank); - Assert.IsTrue (array.Dimensions [0].IsSized); - Assert.AreEqual (0, array.Dimensions [0].LowerBound); - Assert.AreEqual (null, array.Dimensions [0].UpperBound); - Assert.IsTrue (array.Dimensions [1].IsSized); - Assert.AreEqual (0, array.Dimensions [1].LowerBound); - Assert.AreEqual (null, array.Dimensions [1].UpperBound); - - var rank_one_low_bound_m1 = types.GetField ("rank_one_low_bound_m1"); - array = rank_one_low_bound_m1.FieldType as ArrayType; - Assert.IsNotNull (array); - - Assert.AreEqual (1, array.Rank); - Assert.IsTrue (array.Dimensions [0].IsSized); - Assert.AreEqual (-1, array.Dimensions [0].LowerBound); - Assert.AreEqual (4, array.Dimensions [0].UpperBound); - } - - [TestCSharp ("Fields.cs")] - public void EnumFieldsConstant (ModuleDefinition module) - { - var pim = module.GetType ("Pim"); - Assert.IsNotNull (pim); - - var field = pim.GetField ("Pam"); - Assert.IsTrue (field.HasConstant); - Assert.AreEqual (1, (int) field.Constant); - - field = pim.GetField ("Poum"); - Assert.AreEqual (2, (int) field.Constant); - } - - [TestCSharp ("Fields.cs")] - public void StringAndClassConstant (ModuleDefinition module) - { - var panpan = module.GetType ("PanPan"); - Assert.IsNotNull (panpan); - - var field = panpan.GetField ("Peter"); - Assert.IsTrue (field.HasConstant); - Assert.IsNull (field.Constant); - - field = panpan.GetField ("QQ"); - Assert.AreEqual ("qq", (string) field.Constant); - - field = panpan.GetField ("nil"); - Assert.AreEqual (null, (string) field.Constant); - } - - [TestCSharp ("Fields.cs")] - public void ObjectConstant (ModuleDefinition module) - { - var panpan = module.GetType ("PanPan"); - Assert.IsNotNull (panpan); - - var field = panpan.GetField ("obj"); - Assert.IsTrue (field.HasConstant); - Assert.IsNull (field.Constant); - } - - [TestIL ("types.il")] - public void NullPrimitiveConstant (ModuleDefinition module) - { - var fields = module.GetType ("Fields"); - - var field = fields.GetField ("int32_nullref"); - Assert.IsTrue (field.HasConstant); - Assert.AreEqual (null, field.Constant); - } - - [TestCSharp ("Fields.cs")] - public void ArrayConstant (ModuleDefinition module) - { - var panpan = module.GetType ("PanPan"); - Assert.IsNotNull (panpan); - - var field = panpan.GetField ("ints"); - Assert.IsTrue (field.HasConstant); - Assert.IsNull (field.Constant); - } - - [TestIL ("types.il")] - public void ConstantCoalescing (ModuleDefinition module) - { - var fields = module.GetType ("Fields"); - - var field = fields.GetField ("int32_int16"); - Assert.AreEqual ("System.Int32", field.FieldType.FullName); - Assert.IsTrue (field.HasConstant); - Assert.IsInstanceOf (typeof (short), field.Constant); - Assert.AreEqual ((short) 1, field.Constant); - - field = fields.GetField ("int16_int32"); - Assert.AreEqual ("System.Int16", field.FieldType.FullName); - Assert.IsTrue (field.HasConstant); - Assert.IsInstanceOf (typeof (int), field.Constant); - Assert.AreEqual (1, field.Constant); - - field = fields.GetField ("char_int16"); - Assert.AreEqual ("System.Char", field.FieldType.FullName); - Assert.IsTrue (field.HasConstant); - Assert.IsInstanceOf (typeof (short), field.Constant); - Assert.AreEqual ((short) 1, field.Constant); - - field = fields.GetField ("int16_char"); - Assert.AreEqual ("System.Int16", field.FieldType.FullName); - Assert.IsTrue (field.HasConstant); - Assert.IsInstanceOf (typeof (char), field.Constant); - Assert.AreEqual ('s', field.Constant); - } - - [TestCSharp ("Generics.cs")] - public void NestedEnumOfGenericTypeDefinition (ModuleDefinition module) - { - var dang = module.GetType ("Bongo`1/Dang"); - Assert.IsNotNull (dang); - - var field = dang.GetField ("Ding"); - Assert.IsNotNull (field); - Assert.AreEqual (2, field.Constant); - - field = dang.GetField ("Dong"); - Assert.IsNotNull (field); - Assert.AreEqual (12, field.Constant); - } - - [TestModule ("marshal.dll")] - public void MarshalAsFixedStr (ModuleDefinition module) - { - var boc = module.GetType ("Boc"); - var field = boc.GetField ("a"); - - Assert.IsNotNull (field); - - Assert.IsTrue (field.HasMarshalInfo); - - var info = (FixedSysStringMarshalInfo) field.MarshalInfo; - - Assert.AreEqual (42, info.Size); - } - - [TestModule ("marshal.dll")] - public void MarshalAsFixedArray (ModuleDefinition module) - { - var boc = module.GetType ("Boc"); - var field = boc.GetField ("b"); - - Assert.IsNotNull (field); - - Assert.IsTrue (field.HasMarshalInfo); - - var info = (FixedArrayMarshalInfo) field.MarshalInfo; - - Assert.AreEqual (12, info.Size); - Assert.AreEqual (NativeType.Boolean, info.ElementType); - } - - static TypeDefinition GetPrivateImplementationType (ModuleDefinition module) - { - foreach (var type in module.Types) - if (type.FullName.Contains ("")) - return type; - - return null; - } - - static void AssertField (TypeDefinition type, string name, Type expected) - { - var field = type.GetField (name); - Assert.IsNotNull (field, name); - - Assert.AreEqual (expected.FullName, field.FieldType.FullName); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/Formatter.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/Formatter.cs deleted file mode 100644 index a7e1c8704..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/Formatter.cs +++ /dev/null @@ -1,179 +0,0 @@ -using System; -using System.IO; -using Mono.Cecil; -using Mono.Cecil.Cil; - -namespace Mono.Cecil.Tests { - - public static class Formatter { - - public static string FormatInstruction (Instruction instruction) - { - var writer = new StringWriter (); - WriteInstruction (writer, instruction); - return writer.ToString (); - } - - public static string FormatMethodBody (MethodDefinition method) - { - var writer = new StringWriter (); - WriteMethodBody (writer, method); - return writer.ToString (); - } - - public static void WriteMethodBody (TextWriter writer, MethodDefinition method) - { - var body = method.Body; - - WriteVariables (writer, body); - - foreach (Instruction instruction in body.Instructions) { - var sequence_point = instruction.SequencePoint; - if (sequence_point != null) { - writer.Write ('\t'); - WriteSequencePoint (writer, sequence_point); - writer.WriteLine (); - } - - writer.Write ('\t'); - WriteInstruction (writer, instruction); - writer.WriteLine (); - } - - WriteExceptionHandlers (writer, body); - } - - static void WriteVariables (TextWriter writer, MethodBody body) - { - var variables = body.Variables; - - writer.Write ('\t'); - writer.Write (".locals {0}(", body.InitLocals ? "init " : string.Empty); - - for (int i = 0; i < variables.Count; i++) { - if (i > 0) - writer.Write (", "); - - var variable = variables [i]; - - writer.Write ("{0} {1}", variable.VariableType, variable); - } - writer.WriteLine (")"); - } - - static void WriteInstruction (TextWriter writer, Instruction instruction) - { - writer.Write (FormatLabel (instruction.Offset)); - writer.Write (": "); - writer.Write (instruction.OpCode.Name); - if (null != instruction.Operand) { - writer.Write (' '); - WriteOperand (writer, instruction.Operand); - } - } - - static void WriteSequencePoint (TextWriter writer, SequencePoint sequence_point) - { - writer.Write (".line {0},{1}:{2},{3} '{4}'", - sequence_point.StartLine, - sequence_point.EndLine, - sequence_point.StartColumn, - sequence_point.EndColumn, - sequence_point.Document.Url); - } - - static string FormatLabel (int offset) - { - string label = "000" + offset.ToString ("x"); - return "IL_" + label.Substring (label.Length - 4); - } - - static string FormatLabel (Instruction instruction) - { - return FormatLabel (instruction.Offset); - } - - static void WriteOperand (TextWriter writer, object operand) - { - if (null == operand) throw new ArgumentNullException ("operand"); - - var target = operand as Instruction; - if (null != target) { - writer.Write (FormatLabel (target.Offset)); - return; - } - - var targets = operand as Instruction []; - if (null != targets) { - WriteLabelList (writer, targets); - return; - } - - string s = operand as string; - if (null != s) { - writer.Write ("\"" + s + "\""); - return; - } - - var parameter = operand as ParameterDefinition; - if (parameter != null) { - writer.Write (ToInvariantCultureString (parameter.Sequence)); - return; - } - - s = ToInvariantCultureString (operand); - writer.Write (s); - } - - static void WriteLabelList (TextWriter writer, Instruction [] instructions) - { - writer.Write ("("); - - for (int i = 0; i < instructions.Length; i++) { - if (i != 0) writer.Write (", "); - writer.Write (FormatLabel (instructions [i].Offset)); - } - - writer.Write (")"); - } - - static void WriteExceptionHandlers (TextWriter writer, MethodBody body) - { - if (!body.HasExceptionHandlers) - return; - - foreach (var handler in body.ExceptionHandlers) { - writer.Write ("\t"); - writer.WriteLine (".try {0} to {1} {2} handler {3} to {4}", - FormatLabel (handler.TryStart), - FormatLabel (handler.TryEnd), - FormatHandlerType (handler), - FormatLabel (handler.HandlerStart), - FormatLabel (handler.HandlerEnd)); - } - } - - static string FormatHandlerType (ExceptionHandler handler) - { - var handler_type = handler.HandlerType; - var type = handler_type.ToString ().ToLowerInvariant (); - - switch (handler_type) { - case ExceptionHandlerType.Catch: - return string.Format ("{0} {1}", type, handler.CatchType.FullName); - case ExceptionHandlerType.Filter: - throw new NotImplementedException (); - default: - return type; - } - } - - public static string ToInvariantCultureString (object value) - { - var convertible = value as IConvertible; - return (null != convertible) - ? convertible.ToString (System.Globalization.CultureInfo.InvariantCulture) - : value.ToString (); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/ILProcessorTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/ILProcessorTests.cs deleted file mode 100644 index 3d9d1751b..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/ILProcessorTests.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Linq; - -using Mono.Cecil; -using Mono.Cecil.Cil; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class ILProcessorTests : BaseTestFixture { - - [Test] - public void Append () - { - var method = CreateTestMethod (); - var il = method.GetILProcessor (); - - var ret = il.Create (OpCodes.Ret); - il.Append (ret); - - AssertOpCodeSequence (new [] { OpCodes.Ret }, method); - } - - [Test] - public void InsertBefore () - { - var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3); - var il = method.GetILProcessor (); - - var ldloc_2 = method.Instructions.Where (i => i.OpCode == OpCodes.Ldloc_2).First (); - - il.InsertBefore ( - ldloc_2, - il.Create (OpCodes.Ldloc_1)); - - AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method); - } - - [Test] - public void InsertAfter () - { - var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3); - var il = method.GetILProcessor (); - - var ldloc_0 = method.Instructions.First (); - - il.InsertAfter ( - ldloc_0, - il.Create (OpCodes.Ldloc_1)); - - AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method); - } - - static void AssertOpCodeSequence (OpCode [] expected, MethodBody body) - { - var opcodes = body.Instructions.Select (i => i.OpCode).ToArray (); - Assert.AreEqual (expected.Length, opcodes.Length); - - for (int i = 0; i < opcodes.Length; i++) - Assert.AreEqual (expected [i], opcodes [i]); - } - - static MethodBody CreateTestMethod (params OpCode [] opcodes) - { - var method = new MethodDefinition { - Name = "function", - }; - - var il = method.Body.GetILProcessor (); - - foreach (var opcode in opcodes) - il.Emit (opcode); - - return method.Body; - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/ImageReadTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/ImageReadTests.cs deleted file mode 100644 index 8f68e5fc8..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/ImageReadTests.cs +++ /dev/null @@ -1,144 +0,0 @@ -using System; -using System.IO; - -using Mono.Cecil; -using Mono.Cecil.PE; -using Mono.Cecil.Metadata; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class ImageReadTests : BaseTestFixture { - - [Test] - public void ImageSections () - { - var image = GetResourceImage ("hello.exe"); - - Assert.AreEqual (3, image.Sections.Length); - Assert.AreEqual (".text", image.Sections [0].Name); - Assert.AreEqual (".rsrc", image.Sections [1].Name); - Assert.AreEqual (".reloc", image.Sections [2].Name); - } - - [Test] - public void ImageMetadataVersion () - { - var image = GetResourceImage ("hello.exe"); - Assert.AreEqual (TargetRuntime.Net_2_0, image.Runtime); - - image = GetResourceImage ("hello1.exe"); - Assert.AreEqual (TargetRuntime.Net_1_1, image.Runtime); - } - - [Test] - public void ImageModuleKind () - { - var image = GetResourceImage ("hello.exe"); - Assert.AreEqual (ModuleKind.Console, image.Kind); - - image = GetResourceImage ("libhello.dll"); - Assert.AreEqual (ModuleKind.Dll, image.Kind); - - image = GetResourceImage ("hellow.exe"); - Assert.AreEqual (ModuleKind.Windows, image.Kind); - } - - [Test] - public void MetadataHeaps () - { - var image = GetResourceImage ("hello.exe"); - - Assert.IsNotNull (image.TableHeap); - - Assert.IsNotNull (image.StringHeap); - Assert.AreEqual (string.Empty, image.StringHeap.Read (0)); - Assert.AreEqual ("", image.StringHeap.Read (1)); - - Assert.IsNotNull (image.UserStringHeap); - Assert.AreEqual (string.Empty, image.UserStringHeap.Read (0)); - Assert.AreEqual ("Hello Cecil World !", image.UserStringHeap.Read (1)); - - Assert.IsNotNull (image.GuidHeap); - Assert.AreEqual (new Guid (), image.GuidHeap.Read (0)); - Assert.AreEqual (new Guid ("C3BC2BD3-2576-4D00-A80E-465B5632415F"), image.GuidHeap.Read (1)); - - Assert.IsNotNull (image.BlobHeap); - Assert.AreEqual (new byte [0], image.BlobHeap.Read (0)); - } - - [Test] - public void TablesHeap () - { - var image = GetResourceImage ("hello.exe"); - var heap = image.TableHeap; - - Assert.IsNotNull (heap); - - Assert.AreEqual (1, heap [Table.Module].Length); - Assert.AreEqual (4, heap [Table.TypeRef].Length); - Assert.AreEqual (2, heap [Table.TypeDef].Length); - Assert.AreEqual (0, heap [Table.Field].Length); - Assert.AreEqual (2, heap [Table.Method].Length); - Assert.AreEqual (4, heap [Table.MemberRef].Length); - Assert.AreEqual (2, heap [Table.CustomAttribute].Length); - Assert.AreEqual (1, heap [Table.Assembly].Length); - Assert.AreEqual (1, heap [Table.AssemblyRef].Length); - } - - [TestModule ("hello.x64.exe")] - public void X64Module (ModuleDefinition module) - { - Assert.AreEqual (TargetArchitecture.AMD64, module.Image.Architecture); - Assert.AreEqual (ModuleAttributes.ILOnly, module.Image.Attributes); - } - - [TestModule ("hello.ia64.exe")] - public void IA64Module (ModuleDefinition module) - { - Assert.AreEqual (TargetArchitecture.IA64, module.Image.Architecture); - Assert.AreEqual (ModuleAttributes.ILOnly, module.Image.Attributes); - } - - [TestModule ("hello.x86.exe")] - public void X86Module (ModuleDefinition module) - { - Assert.AreEqual (TargetArchitecture.I386, module.Image.Architecture); - Assert.AreEqual (ModuleAttributes.ILOnly | ModuleAttributes.Required32Bit, module.Image.Attributes); - } - - [TestModule ("hello.anycpu.exe")] - public void AnyCpuModule (ModuleDefinition module) - { - Assert.AreEqual (TargetArchitecture.I386, module.Image.Architecture); - Assert.AreEqual (ModuleAttributes.ILOnly, module.Image.Attributes); - } - - [TestModule ("delay-signed.dll")] - public void DelaySignedAssembly (ModuleDefinition module) - { - Assert.IsNotNull (module.Assembly.Name.PublicKey); - Assert.AreNotEqual (0, module.Assembly.Name.PublicKey.Length); - Assert.AreNotEqual (ModuleAttributes.StrongNameSigned, module.Attributes & ModuleAttributes.StrongNameSigned); - Assert.AreNotEqual (0, module.Image.StrongName.VirtualAddress); - Assert.AreNotEqual (0, module.Image.StrongName.Size); - } - - [TestModule ("wp7.dll", Verify = false)] - public void WindowsPhoneNonSignedAssembly (ModuleDefinition module) - { - Assert.AreEqual (0, module.Assembly.Name.PublicKey.Length); - Assert.AreNotEqual (ModuleAttributes.StrongNameSigned, module.Attributes & ModuleAttributes.StrongNameSigned); - Assert.AreEqual (0, module.Image.StrongName.VirtualAddress); - Assert.AreEqual (0, module.Image.StrongName.Size); - } - - [TestModule ("metro.exe", Verify = false)] - public void MetroAssembly (ModuleDefinition module) - { - Assert.AreEqual (ModuleCharacteristics.AppContainer, module.Characteristics & ModuleCharacteristics.AppContainer); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/ImportCecilTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/ImportCecilTests.cs deleted file mode 100644 index 3fa04068e..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/ImportCecilTests.cs +++ /dev/null @@ -1,310 +0,0 @@ -using System; -using System.Diagnostics; -using System.IO; -using System.Linq; -using SR = System.Reflection; -using System.Runtime.CompilerServices; - -using Mono.Cecil.Cil; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class ImportCecilTests : BaseTestFixture { - - [Test] - public void ImportStringByRef () - { - var get_string = Compile> ((module, body) => { - var type = module.Types [1]; - - var method_by_ref = new MethodDefinition { - Name = "ModifyString", - IsPrivate = true, - IsStatic = true, - }; - - type.Methods.Add (method_by_ref); - - method_by_ref.MethodReturnType.ReturnType = module.Import (typeof (void).ToDefinition ()); - - method_by_ref.Parameters.Add (new ParameterDefinition (module.Import (typeof (string).ToDefinition ()))); - method_by_ref.Parameters.Add (new ParameterDefinition (module.Import (new ByReferenceType (typeof (string).ToDefinition ())))); - - var m_il = method_by_ref.Body.GetILProcessor (); - m_il.Emit (OpCodes.Ldarg_1); - m_il.Emit (OpCodes.Ldarg_0); - m_il.Emit (OpCodes.Stind_Ref); - m_il.Emit (OpCodes.Ret); - - var v_0 = new VariableDefinition (module.Import (typeof (string).ToDefinition ())); - body.Variables.Add (v_0); - - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldnull); - il.Emit (OpCodes.Stloc, v_0); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ldloca, v_0); - il.Emit (OpCodes.Call, method_by_ref); - il.Emit (OpCodes.Ldloc_0); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual ("foo", get_string ("foo")); - } - - [Test] - public void ImportStringArray () - { - var identity = Compile> ((module, body) => { - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ret); - }); - - var array = new string [2, 2]; - - Assert.AreEqual (array, identity (array)); - } - - [Test] - public void ImportFieldStringEmpty () - { - var get_empty = Compile> ((module, body) => { - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldsfld, module.Import (typeof (string).GetField ("Empty").ToDefinition ())); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual ("", get_empty ()); - } - - [Test] - public void ImportStringConcat () - { - var concat = Compile> ((module, body) => { - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ldarg_1); - il.Emit (OpCodes.Call, module.Import (typeof (string).GetMethod ("Concat", new [] { typeof (string), typeof (string) }).ToDefinition ())); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual ("FooBar", concat ("Foo", "Bar")); - } - - public class Generic { - public T Field; - - public T Method (T t) - { - return t; - } - - public TS GenericMethod (T t, TS s) - { - return s; - } - - public Generic ComplexGenericMethod (T t, TS s) - { - return new Generic { Field = s }; - } - } - - [Test] - public void ImportGenericField () - { - var get_field = Compile, string>> ((module, body) => { - var generic_def = module.Import (typeof (Generic<>)).Resolve (); - var field_def = generic_def.Fields.Where (f => f.Name == "Field").First (); - - var field_string = field_def.MakeGeneric (module.Import (typeof (string))); - - var field_ref = module.Import (field_string); - - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ldfld, field_ref); - il.Emit (OpCodes.Ret); - }); - - var generic = new Generic { - Field = "foo", - }; - - Assert.AreEqual ("foo", get_field (generic)); - } - - [Test] - public void ImportGenericMethod () - { - var generic_identity = Compile, int, int>> ((module, body) => { - var generic_def = module.Import (typeof (Generic<>)).Resolve (); - var method_def = generic_def.Methods.Where (m => m.Name == "Method").First (); - - var method_int = method_def.MakeGeneric (module.Import (typeof (int))); - var method_ref = module.Import (method_int); - - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ldarg_1); - il.Emit (OpCodes.Callvirt, method_ref); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual (42, generic_identity (new Generic (), 42)); - } - - [Test] - public void ImportGenericMethodSpec () - { - var gen_spec_id = Compile, int, int>> ((module, body) => { - var generic_def = module.Import (typeof (Generic<>)).Resolve (); - var method_def = generic_def.Methods.Where (m => m.Name == "GenericMethod").First (); - - var method_string = method_def.MakeGeneric (module.Import (typeof (string))); - - var method_instance = method_string.MakeGenericMethod (module.Import (typeof (int))); - - var method_ref = module.Import (method_instance); - - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ldnull); - il.Emit (OpCodes.Ldarg_1); - il.Emit (OpCodes.Callvirt, method_ref); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual (42, gen_spec_id (new Generic (), 42)); - } - - [Test] - public void ImportComplexGenericMethodSpec () - { - var gen_spec_id = Compile, int, int>> ((module, body) => { - var generic_def = module.Import (typeof (Generic<>)).Resolve (); - var method_def = generic_def.Methods.Where (m => m.Name == "ComplexGenericMethod").First (); - - var method_string = method_def.MakeGeneric (module.Import (typeof (string))); - var method_instance = method_string.MakeGenericMethod (module.Import (typeof (int))); - var method_ref = module.Import (method_instance); - - var field_def = generic_def.Fields.Where (f => f.Name == "Field").First (); - var field_int = field_def.MakeGeneric (module.Import (typeof (int))); - var field_ref = module.Import (field_int); - - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ldnull); - il.Emit (OpCodes.Ldarg_1); - il.Emit (OpCodes.Callvirt, method_ref); - il.Emit (OpCodes.Ldfld, field_ref); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual (42, gen_spec_id (new Generic (), 42)); - } - - [Test] - public void ImportMethodOnOpenGeneric () - { - var generic = typeof (Generic<>).ToDefinition (); - var module = ModuleDefinition.CreateModule ("foo", ModuleKind.Dll); - - var method = module.Import (generic.GetMethod ("Method")); - - Assert.AreEqual ("T Mono.Cecil.Tests.ImportCecilTests/Generic`1::Method(T)", method.FullName); - } - - delegate void Emitter (ModuleDefinition module, MethodBody body); - - [MethodImpl (MethodImplOptions.NoInlining)] - static TDelegate Compile (Emitter emitter) - where TDelegate : class - { - var name = GetTestCaseName (); - - var module = CreateTestModule (name, emitter); - var assembly = LoadTestModule (module); - - return CreateRunDelegate (GetTestCase (name, assembly)); - } - - static TDelegate CreateRunDelegate (Type type) - where TDelegate : class - { - return (TDelegate) (object) Delegate.CreateDelegate (typeof (TDelegate), type.GetMethod ("Run")); - } - - static Type GetTestCase (string name, SR.Assembly assembly) - { - return assembly.GetType (name); - } - - static SR.Assembly LoadTestModule (ModuleDefinition module) - { - using (var stream = new MemoryStream ()) { - module.Write (stream); - File.WriteAllBytes (Path.Combine (Path.Combine (Path.GetTempPath (), "cecil"), module.Name + ".dll"), stream.ToArray ()); - return SR.Assembly.Load (stream.ToArray ()); - } - } - - static ModuleDefinition CreateTestModule (string name, Emitter emitter) - { - var module = CreateModule (name); - - var type = new TypeDefinition ( - "", - name, - TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Abstract, - module.Import (typeof (object))); - - module.Types.Add (type); - - var method = CreateMethod (type, typeof (TDelegate).GetMethod ("Invoke")); - - emitter (module, method.Body); - - return module; - } - - static MethodDefinition CreateMethod (TypeDefinition type, SR.MethodInfo pattern) - { - var module = type.Module; - - var method = new MethodDefinition { - Name = "Run", - IsPublic = true, - IsStatic = true, - }; - - type.Methods.Add (method); - - method.MethodReturnType.ReturnType = module.Import (pattern.ReturnType); - - foreach (var parameter_pattern in pattern.GetParameters ()) - method.Parameters.Add (new ParameterDefinition (module.Import (parameter_pattern.ParameterType))); - - return method; - } - - static ModuleDefinition CreateModule (string name) - { - return ModuleDefinition.CreateModule (name, ModuleKind.Dll); - } - - [MethodImpl (MethodImplOptions.NoInlining)] - static string GetTestCaseName () - { - var stack_trace = new StackTrace (); - var stack_frame = stack_trace.GetFrame (2); - - return "ImportCecil_" + stack_frame.GetMethod ().Name; - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/ImportReflectionTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/ImportReflectionTests.cs deleted file mode 100644 index dd1d28a12..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/ImportReflectionTests.cs +++ /dev/null @@ -1,409 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using SR = System.Reflection; -using System.Runtime.CompilerServices; - -using Mono.Cecil.Cil; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class ImportReflectionTests : BaseTestFixture { - - [Test] - public void ImportString () - { - var get_string = Compile> ((_, body) => { - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldstr, "yo dawg!"); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual ("yo dawg!", get_string ()); - } - - [Test] - public void ImportInt () - { - var add = Compile> ((_, body) => { - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ldarg_1); - il.Emit (OpCodes.Add); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual (42, add (40, 2)); - } - - [Test] - public void ImportStringByRef () - { - var get_string = Compile> ((module, body) => { - var type = module.Types [1]; - - var method_by_ref = new MethodDefinition { - Name = "ModifyString", - IsPrivate = true, - IsStatic = true, - }; - - type.Methods.Add (method_by_ref); - - method_by_ref.MethodReturnType.ReturnType = module.Import (typeof (void)); - - method_by_ref.Parameters.Add (new ParameterDefinition (module.Import (typeof (string)))); - method_by_ref.Parameters.Add (new ParameterDefinition (module.Import (typeof (string).MakeByRefType ()))); - - var m_il = method_by_ref.Body.GetILProcessor (); - m_il.Emit (OpCodes.Ldarg_1); - m_il.Emit (OpCodes.Ldarg_0); - m_il.Emit (OpCodes.Stind_Ref); - m_il.Emit (OpCodes.Ret); - - var v_0 = new VariableDefinition (module.Import (typeof (string))); - body.Variables.Add (v_0); - - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldnull); - il.Emit (OpCodes.Stloc, v_0); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ldloca, v_0); - il.Emit (OpCodes.Call, method_by_ref); - il.Emit (OpCodes.Ldloc_0); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual ("foo", get_string ("foo")); - } - - [Test] - public void ImportStringArray () - { - var identity = Compile> ((module, body) => { - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ret); - }); - - var array = new string [2, 2]; - - Assert.AreEqual (array, identity (array)); - } - - [Test] - public void ImportFieldStringEmpty () - { - var get_empty = Compile> ((module, body) => { - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldsfld, module.Import (typeof (string).GetField ("Empty"))); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual ("", get_empty ()); - } - - [Test] - public void ImportStringConcat () - { - var concat = Compile> ((module, body) => { - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ldarg_1); - il.Emit (OpCodes.Call, module.Import (typeof (string).GetMethod ("Concat", new [] { typeof (string), typeof (string) }))); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual ("FooBar", concat ("Foo", "Bar")); - } - - public class Generic { - public T Field; - - public T Method (T t) - { - return t; - } - - public TS GenericMethod (T t, TS s) - { - return s; - } - - public Generic ComplexGenericMethod (T t, TS s) - { - return new Generic { Field = s }; - } - } - - [Test] - public void ImportGenericField () - { - var get_field = Compile, string>> ((module, body) => { - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ldfld, module.Import (typeof (Generic).GetField ("Field"))); - il.Emit (OpCodes.Ret); - }); - - var generic = new Generic { - Field = "foo", - }; - - Assert.AreEqual ("foo", get_field (generic)); - } - - [Test] - public void ImportGenericMethod () - { - var generic_identity = Compile, int, int>> ((module, body) => { - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ldarg_1); - il.Emit (OpCodes.Callvirt, module.Import (typeof (Generic).GetMethod ("Method"))); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual (42, generic_identity (new Generic (), 42)); - } - - [Test] - public void ImportGenericMethodSpec () - { - var gen_spec_id = Compile, int, int>> ((module, body) => { - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ldnull); - il.Emit (OpCodes.Ldarg_1); - il.Emit (OpCodes.Callvirt, module.Import (typeof (Generic).GetMethod ("GenericMethod").MakeGenericMethod (typeof (int)))); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual (42, gen_spec_id (new Generic (), 42)); - } - - [Test] - public void ImportComplexGenericMethodSpec () - { - var gen_spec_id = Compile, int, int>> ((module, body) => { - var il = body.GetILProcessor (); - il.Emit (OpCodes.Ldarg_0); - il.Emit (OpCodes.Ldnull); - il.Emit (OpCodes.Ldarg_1); - il.Emit (OpCodes.Callvirt, module.Import (typeof (Generic).GetMethod ("ComplexGenericMethod").MakeGenericMethod (typeof (int)))); - il.Emit (OpCodes.Ldfld, module.Import (typeof (Generic).GetField ("Field"))); - il.Emit (OpCodes.Ret); - }); - - Assert.AreEqual (42, gen_spec_id (new Generic (), 42)); - } - - public class Foo { - public List list; - } - - [Test] - public void ImportGenericTypeDefOrOpen () - { - var module = typeof (Foo<>).ToDefinition ().Module; - - var foo_def = module.Import (typeof (Foo<>)); - var foo_open = module.Import (typeof (Foo<>), foo_def); - - Assert.AreEqual ("Mono.Cecil.Tests.ImportReflectionTests/Foo`1", foo_def.FullName); - Assert.AreEqual ("Mono.Cecil.Tests.ImportReflectionTests/Foo`1", foo_open.FullName); - } - - [Test] - public void ImportGenericTypeFromContext () - { - var list_foo = typeof (Foo<>).GetField ("list").FieldType; - var generic_list_foo_open = typeof (Generic<>).MakeGenericType (list_foo); - - var foo_def = typeof (Foo<>).ToDefinition (); - var module = foo_def.Module; - - var generic_foo = module.Import (generic_list_foo_open, foo_def); - - Assert.AreEqual ("Mono.Cecil.Tests.ImportReflectionTests/Generic`1>", - generic_foo.FullName); - } - - [Test] - public void ImportGenericTypeDefFromContext () - { - var foo_open = typeof (Foo<>).MakeGenericType (typeof (Foo<>).GetGenericArguments () [0]); - var generic_foo_open = typeof (Generic<>).MakeGenericType (foo_open); - - var foo_def = typeof (Foo<>).ToDefinition (); - var module = foo_def.Module; - - var generic_foo = module.Import (generic_foo_open, foo_def); - - Assert.AreEqual ("Mono.Cecil.Tests.ImportReflectionTests/Generic`1>", - generic_foo.FullName); - } - - [Test] - public void ImportArrayTypeDefFromContext () - { - var foo_open = typeof (Foo<>).MakeGenericType (typeof (Foo<>).GetGenericArguments () [0]); - var foo_open_array = foo_open.MakeArrayType (); - - var foo_def = typeof (Foo<>).ToDefinition (); - var module = foo_def.Module; - - var array_foo = module.Import (foo_open_array, foo_def); - - Assert.AreEqual ("Mono.Cecil.Tests.ImportReflectionTests/Foo`1[]", - array_foo.FullName); - } - - [Test] - public void ImportGenericFieldFromContext () - { - var list_foo = typeof (Foo<>).GetField ("list").FieldType; - var generic_list_foo_open = typeof (Generic<>).MakeGenericType (list_foo); - var generic_list_foo_open_field = generic_list_foo_open.GetField ("Field"); - - var foo_def = typeof (Foo<>).ToDefinition (); - var module = foo_def.Module; - - var generic_field = module.Import (generic_list_foo_open_field, foo_def); - - Assert.AreEqual ("TFoo Mono.Cecil.Tests.ImportReflectionTests/Generic`1>::Field", - generic_field.FullName); - } - - [Test] - public void ImportGenericMethodFromContext () - { - var list_foo = typeof (Foo<>).GetField ("list").FieldType; - var generic_list_foo_open = typeof (Generic<>).MakeGenericType (list_foo); - var generic_list_foo_open_method = generic_list_foo_open.GetMethod ("Method"); - - var foo_def = typeof (Foo<>).ToDefinition (); - var module = foo_def.Module; - - var generic_method = module.Import (generic_list_foo_open_method, foo_def); - - Assert.AreEqual ("TFoo Mono.Cecil.Tests.ImportReflectionTests/Generic`1>::Method(TFoo)", - generic_method.FullName); - } - - [Test] - public void ImportMethodOnOpenGenericType () - { - var module = typeof (Generic<>).ToDefinition ().Module; - - var method = module.Import (typeof (Generic<>).GetMethod ("Method")); - - Assert.AreEqual ("T Mono.Cecil.Tests.ImportReflectionTests/Generic`1::Method(T)", method.FullName); - } - - [Test] - public void ImportGenericMethodOnOpenGenericType () - { - var module = typeof (Generic<>).ToDefinition ().Module; - - var generic_method = module.Import (typeof (Generic<>).GetMethod ("GenericMethod")); - - Assert.AreEqual ("TS Mono.Cecil.Tests.ImportReflectionTests/Generic`1::GenericMethod(T,TS)", generic_method.FullName); - - generic_method = module.Import (typeof (Generic<>).GetMethod ("GenericMethod"), generic_method); - - Assert.AreEqual ("TS Mono.Cecil.Tests.ImportReflectionTests/Generic`1::GenericMethod(T,TS)", generic_method.FullName); - } - - delegate void Emitter (ModuleDefinition module, MethodBody body); - - [MethodImpl (MethodImplOptions.NoInlining)] - static TDelegate Compile (Emitter emitter) - where TDelegate : class - { - var name = GetTestCaseName (); - - var module = CreateTestModule (name, emitter); - var assembly = LoadTestModule (module); - - return CreateRunDelegate (GetTestCase (name, assembly)); - } - - static TDelegate CreateRunDelegate (Type type) - where TDelegate : class - { - return (TDelegate) (object) Delegate.CreateDelegate (typeof (TDelegate), type.GetMethod ("Run")); - } - - static Type GetTestCase (string name, SR.Assembly assembly) - { - return assembly.GetType (name); - } - - static SR.Assembly LoadTestModule (ModuleDefinition module) - { - using (var stream = new MemoryStream ()) { - module.Write (stream); - File.WriteAllBytes (Path.Combine (Path.Combine (Path.GetTempPath (), "cecil"), module.Name + ".dll"), stream.ToArray ()); - return SR.Assembly.Load (stream.ToArray ()); - } - } - - static ModuleDefinition CreateTestModule (string name, Emitter emitter) - { - var module = CreateModule (name); - - var type = new TypeDefinition ( - "", - name, - TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Abstract, - module.Import (typeof (object))); - - module.Types.Add (type); - - var method = CreateMethod (type, typeof (TDelegate).GetMethod ("Invoke")); - - emitter (module, method.Body); - - return module; - } - - static MethodDefinition CreateMethod (TypeDefinition type, SR.MethodInfo pattern) - { - var module = type.Module; - - var method = new MethodDefinition { - Name = "Run", - IsPublic = true, - IsStatic = true, - }; - - type.Methods.Add (method); - - method.MethodReturnType.ReturnType = module.Import (pattern.ReturnType); - - foreach (var parameter_pattern in pattern.GetParameters ()) - method.Parameters.Add (new ParameterDefinition (module.Import (parameter_pattern.ParameterType))); - - return method; - } - - static ModuleDefinition CreateModule (string name) - { - return ModuleDefinition.CreateModule (name, ModuleKind.Dll); - } - - [MethodImpl (MethodImplOptions.NoInlining)] - static string GetTestCaseName () - { - var stack_trace = new StackTrace (); - var stack_frame = stack_trace.GetFrame (2); - - return "ImportReflection_" + stack_frame.GetMethod ().Name; - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/Linq.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/Linq.cs deleted file mode 100644 index 4f870e004..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/Linq.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; - -using Mono; - -#if !NET_3_5 && !NET_4_0 - -namespace System.Linq { - - static class Enumerable { - - public static IEnumerable Select (this IEnumerable self, Func selector) - { - foreach (var item in self) - yield return selector (item); - } - - public static IEnumerable Where (this IEnumerable self, Func predicate) - { - foreach (var item in self) - if (predicate (item)) - yield return item; - } - - public static List ToList (this IEnumerable self) - { - return new List (self); - } - - public static T [] ToArray (this IEnumerable self) - { - return self.ToList ().ToArray (); - } - - public static T First (this IEnumerable self) - { - using (var enumerator = self.GetEnumerator ()) { - if (!enumerator.MoveNext ()) - throw new InvalidOperationException (); - - return enumerator.Current; - } - } - } -} - -#endif diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/MethodBodyTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/MethodBodyTests.cs deleted file mode 100644 index 5258305a9..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/MethodBodyTests.cs +++ /dev/null @@ -1,412 +0,0 @@ -using System; -using System.Linq; - -using Mono.Cecil; -using Mono.Cecil.Cil; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class MethodBodyTests : BaseTestFixture { - - [TestIL ("hello.il")] - public void MultiplyMethod (ModuleDefinition module) - { - var foo = module.GetType ("Foo"); - Assert.IsNotNull (foo); - - var bar = foo.GetMethod ("Bar"); - Assert.IsNotNull (bar); - Assert.IsTrue (bar.IsIL); - - AssertCode (@" - .locals init (System.Int32 V_0) - IL_0000: ldarg.0 - IL_0001: ldarg.1 - IL_0002: mul - IL_0003: stloc.0 - IL_0004: ldloc.0 - IL_0005: call System.Void Foo::Baz(System.Int32) - IL_000a: ret -", bar); - } - - [TestIL ("hello.il")] - public void PrintStringEmpty (ModuleDefinition module) - { - var foo = module.GetType ("Foo"); - Assert.IsNotNull (foo); - - var print_empty = foo.GetMethod ("PrintEmpty"); - Assert.IsNotNull (print_empty); - - AssertCode (@" - .locals () - IL_0000: ldsfld System.String System.String::Empty - IL_0005: call System.Void System.Console::WriteLine(System.String) - IL_000a: ret -", print_empty); - } - - [TestModule ("libhello.dll")] - public void Branch (ModuleDefinition module) - { - var lib = module.GetType ("Library"); - Assert.IsNotNull (lib); - - var method = lib.GetMethod ("GetHelloString"); - Assert.IsNotNull (method); - - AssertCode (@" - .locals init (System.String V_0) - IL_0000: nop - IL_0001: ldstr ""hello world of tomorrow"" - IL_0006: stloc.0 - IL_0007: br.s IL_0009 - IL_0009: ldloc.0 - IL_000a: ret -", method); - } - - [TestModule ("switch.exe")] - public void Switch (ModuleDefinition module) - { - var program = module.GetType ("Program"); - Assert.IsNotNull (program); - - var method = program.GetMethod ("Main"); - Assert.IsNotNull (method); - - AssertCode (@" - .locals init (System.Int32 V_0) - IL_0000: ldarg.0 - IL_0001: ldlen - IL_0002: conv.i4 - IL_0003: stloc.0 - IL_0004: ldloc.0 - IL_0005: ldc.i4.8 - IL_0006: bgt.s IL_0026 - IL_0008: ldloc.0 - IL_0009: ldc.i4.1 - IL_000a: sub - IL_000b: switch (IL_0032, IL_0034, IL_0038, IL_0034) - IL_0020: ldloc.0 - IL_0021: ldc.i4.8 - IL_0022: beq.s IL_0036 - IL_0024: br.s IL_0038 - IL_0026: ldloc.0 - IL_0027: ldc.i4.s 16 - IL_0029: beq.s IL_0036 - IL_002b: ldloc.0 - IL_002c: ldc.i4.s 32 - IL_002e: beq.s IL_0036 - IL_0030: br.s IL_0038 - IL_0032: ldc.i4.0 - IL_0033: ret - IL_0034: ldc.i4.1 - IL_0035: ret - IL_0036: ldc.i4.2 - IL_0037: ret - IL_0038: ldc.i4.s 42 - IL_003a: ret -", method); - } - - [TestIL ("methodspecs.il")] - public void MethodSpec (ModuleDefinition module) - { - var tamtam = module.GetType ("Tamtam"); - - var bar = tamtam.GetMethod ("Bar"); - Assert.IsNotNull (bar); - - AssertCode (@" - .locals () - IL_0000: ldc.i4.2 - IL_0001: call System.Void Tamtam::Foo(TFoo) - IL_0006: ret -", bar); - } - - [TestModule ("catch.exe")] - public void NestedTryCatchFinally (ModuleDefinition module) - { - var program = module.GetType ("Program"); - var main = program.GetMethod ("Main"); - Assert.IsNotNull (main); - - AssertCode (@" - .locals () - IL_0000: call System.Void Program::Foo() - IL_0005: leave.s IL_000d - IL_0007: call System.Void Program::Baz() - IL_000c: endfinally - IL_000d: leave.s IL_001f - IL_000f: pop - IL_0010: call System.Void Program::Bar() - IL_0015: leave.s IL_001f - IL_0017: pop - IL_0018: call System.Void Program::Bar() - IL_001d: leave.s IL_001f - IL_001f: leave.s IL_0027 - IL_0021: call System.Void Program::Baz() - IL_0026: endfinally - IL_0027: ret - .try IL_0000 to IL_0007 finally handler IL_0007 to IL_000d - .try IL_0000 to IL_000f catch System.ArgumentException handler IL_000f to IL_0017 - .try IL_0000 to IL_000f catch System.Exception handler IL_0017 to IL_001f - .try IL_0000 to IL_0021 finally handler IL_0021 to IL_0027 -", main); - } - - [TestModule ("fptr.exe", Verify = false)] - public void FunctionPointersAndCallSites (ModuleDefinition module) - { - var type = module.Types [0]; - var start = type.GetMethod ("Start"); - Assert.IsNotNull (start); - - AssertCode (@" - .locals init () - IL_0000: ldc.i4.1 - IL_0001: call method System.Int32 *(System.Int32) MakeDecision::Decide() - IL_0006: calli System.Int32(System.Int32) - IL_000b: call System.Void System.Console::WriteLine(System.Int32) - IL_0010: ldc.i4.1 - IL_0011: call method System.Int32 *(System.Int32) MakeDecision::Decide() - IL_0016: calli System.Int32(System.Int32) - IL_001b: call System.Void System.Console::WriteLine(System.Int32) - IL_0020: ldc.i4.1 - IL_0021: call method System.Int32 *(System.Int32) MakeDecision::Decide() - IL_0026: calli System.Int32(System.Int32) - IL_002b: call System.Void System.Console::WriteLine(System.Int32) - IL_0030: ret -", start); - } - - [TestIL ("hello.il")] - public void ThisParameter (ModuleDefinition module) - { - var type = module.GetType ("Foo"); - var method = type.GetMethod ("Gazonk"); - - Assert.IsNotNull (method); - - AssertCode (@" - .locals () - IL_0000: ldarg 0 - IL_0004: pop - IL_0005: ret -", method); - - Assert.AreEqual (method.Body.ThisParameter.ParameterType, type); - Assert.AreEqual (method.Body.ThisParameter, method.Body.Instructions [0].Operand); - } - - [Test] - public void ThisParameterStaticMethod () - { - var static_method = typeof (ModuleDefinition).ToDefinition ().Methods.Where (m => m.IsStatic).First (); - Assert.IsNull (static_method.Body.ThisParameter); - } - - [Test] - public void ThisParameterPrimitive () - { - var int32 = typeof (int).ToDefinition (); - var int_to_string = int32.Methods.Where (m => m.Name == "ToString" && m.Parameters.Count == 0).First(); - Assert.IsNotNull (int_to_string); - - var this_parameter_type = int_to_string.Body.ThisParameter.ParameterType; - Assert.IsTrue (this_parameter_type.IsPointer); - - var element_type = ((PointerType) this_parameter_type).ElementType; - Assert.AreEqual (int32, element_type); - } - - [Test] - public void ThisParameterValueType () - { - var token = typeof (MetadataToken).ToDefinition (); - var token_to_string = token.Methods.Where (m => m.Name == "ToString" && m.Parameters.Count == 0).First (); - Assert.IsNotNull (token_to_string); - - var this_parameter_type = token_to_string.Body.ThisParameter.ParameterType; - Assert.IsTrue (this_parameter_type.IsPointer); - - var element_type = ((PointerType) this_parameter_type).ElementType; - Assert.AreEqual (token, element_type); - } - - [Test] - public void ThisParameterObject () - { - var module = typeof (MethodBodyTests).ToDefinition ().Module; - var @object = module.TypeSystem.Object.Resolve (); - var method = @object.Methods.Where (m => m.HasBody).First (); - - var type = method.Body.ThisParameter.ParameterType; - Assert.IsFalse (type.IsValueType); - Assert.IsFalse (type.IsPrimitive); - Assert.IsFalse (type.IsPointer); - } - - [TestIL ("hello.il")] - public void FilterMaxStack (ModuleDefinition module) - { - var type = module.GetType ("Foo"); - var method = type.GetMethod ("TestFilter"); - - Assert.IsNotNull (method); - Assert.AreEqual (2, method.Body.MaxStackSize); - } - - [TestModule ("iterator.exe")] - public void Iterator (ModuleDefinition module) - { - var method = module.GetType ("Program").GetMethod ("GetLittleArgs"); - Assert.IsNotNull (method.Body); - } - - [TestCSharp ("CustomAttributes.cs")] - public void LoadString (ModuleDefinition module) - { - var type = module.GetType ("FooAttribute"); - var get_fiou = type.GetMethod ("get_Fiou"); - Assert.IsNotNull (get_fiou); - - var ldstr = get_fiou.Body.Instructions.Where (i => i.OpCode == OpCodes.Ldstr).First (); - Assert.AreEqual ("fiou", ldstr.Operand); - } - - static void AssertCode (string expected, MethodDefinition method) - { - Assert.IsTrue (method.HasBody); - Assert.IsNotNull (method.Body); - - Assert.AreEqual (Normalize (expected), Normalize (Formatter.FormatMethodBody (method))); - } - - static string Normalize (string str) - { - return str.Trim ().Replace ("\r\n", "\n"); - } - - [Test] - public void AddInstruction () - { - var object_ref = new TypeReference ("System", "Object", null, null, false); - var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); - var body = new MethodBody (method); - - var il = body.GetILProcessor (); - - var first = il.Create (OpCodes.Nop); - var second = il.Create (OpCodes.Nop); - - body.Instructions.Add (first); - body.Instructions.Add (second); - - Assert.IsNull (first.Previous); - Assert.AreEqual (second, first.Next); - Assert.AreEqual (first, second.Previous); - Assert.IsNull (second.Next); - } - - [Test] - public void InsertInstruction () - { - var object_ref = new TypeReference ("System", "Object", null, null, false); - var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); - var body = new MethodBody (method); - - var il = body.GetILProcessor (); - - var first = il.Create (OpCodes.Nop); - var second = il.Create (OpCodes.Nop); - var third = il.Create (OpCodes.Nop); - - body.Instructions.Add (first); - body.Instructions.Add (third); - - Assert.IsNull (first.Previous); - Assert.AreEqual (third, first.Next); - Assert.AreEqual (first, third.Previous); - Assert.IsNull (third.Next); - - body.Instructions.Insert (1, second); - - Assert.IsNull (first.Previous); - Assert.AreEqual (second, first.Next); - Assert.AreEqual (first, second.Previous); - Assert.AreEqual (third, second.Next); - Assert.AreEqual (second, third.Previous); - Assert.IsNull (third.Next); - } - - [Test] - public void InsertAfterLastInstruction () - { - var object_ref = new TypeReference ("System", "Object", null, null, false); - var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); - var body = new MethodBody (method); - - var il = body.GetILProcessor (); - - var first = il.Create (OpCodes.Nop); - var second = il.Create (OpCodes.Nop); - var third = il.Create (OpCodes.Nop); - - body.Instructions.Add (first); - body.Instructions.Add (second); - - Assert.IsNull (first.Previous); - Assert.AreEqual (second, first.Next); - Assert.AreEqual (first, second.Previous); - Assert.IsNull (second.Next); - - body.Instructions.Insert (2, third); - - Assert.IsNull (first.Previous); - Assert.AreEqual (second, first.Next); - Assert.AreEqual (first, second.Previous); - Assert.AreEqual (third, second.Next); - Assert.AreEqual (second, third.Previous); - Assert.IsNull (third.Next); - } - - [Test] - public void RemoveInstruction () - { - var object_ref = new TypeReference ("System", "Object", null, null, false); - var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); - var body = new MethodBody (method); - - var il = body.GetILProcessor (); - - var first = il.Create (OpCodes.Nop); - var second = il.Create (OpCodes.Nop); - var third = il.Create (OpCodes.Nop); - - body.Instructions.Add (first); - body.Instructions.Add (second); - body.Instructions.Add (third); - - Assert.IsNull (first.Previous); - Assert.AreEqual (second, first.Next); - Assert.AreEqual (first, second.Previous); - Assert.AreEqual (third, second.Next); - Assert.AreEqual (second, third.Previous); - Assert.IsNull (third.Next); - - body.Instructions.Remove (second); - - Assert.IsNull (first.Previous); - Assert.AreEqual (third, first.Next); - Assert.AreEqual (first, third.Previous); - Assert.IsNull (third.Next); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/MethodTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/MethodTests.cs deleted file mode 100644 index 5d4d3751a..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/MethodTests.cs +++ /dev/null @@ -1,201 +0,0 @@ -using System; -using System.Linq; - -using Mono.Cecil; -using Mono.Cecil.Metadata; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class MethodTests : BaseTestFixture { - - [TestCSharp ("Methods.cs")] - public void AbstractMethod (ModuleDefinition module) - { - var type = module.Types [1]; - Assert.AreEqual ("Foo", type.Name); - Assert.AreEqual (2, type.Methods.Count); - - var method = type.GetMethod ("Bar"); - Assert.AreEqual ("Bar", method.Name); - Assert.IsTrue (method.IsAbstract); - Assert.IsNotNull (method.ReturnType); - - Assert.AreEqual (1, method.Parameters.Count); - - var parameter = method.Parameters [0]; - - Assert.AreEqual ("a", parameter.Name); - Assert.AreEqual ("System.Int32", parameter.ParameterType.FullName); - } - - [TestCSharp ("Methods.cs")] - public void SimplePInvoke (ModuleDefinition module) - { - var bar = module.GetType ("Bar"); - var pan = bar.GetMethod ("Pan"); - - Assert.IsTrue (pan.IsPInvokeImpl); - Assert.IsNotNull (pan.PInvokeInfo); - - Assert.AreEqual ("Pan", pan.PInvokeInfo.EntryPoint); - Assert.IsNotNull (pan.PInvokeInfo.Module); - Assert.AreEqual ("foo.dll", pan.PInvokeInfo.Module.Name); - } - - [TestCSharp ("Generics.cs")] - public void GenericMethodDefinition (ModuleDefinition module) - { - var baz = module.GetType ("Baz"); - - var gazonk = baz.GetMethod ("Gazonk"); - - Assert.IsNotNull (gazonk); - - Assert.IsTrue (gazonk.HasGenericParameters); - Assert.AreEqual (1, gazonk.GenericParameters.Count); - Assert.AreEqual ("TBang", gazonk.GenericParameters [0].Name); - } - - [TestCSharp ("Generics.cs")] - public void ReturnGenericInstance (ModuleDefinition module) - { - var bar = module.GetType ("Bar`1"); - - var self = bar.GetMethod ("Self"); - Assert.IsNotNull (self); - - var bar_t = self.ReturnType; - - Assert.IsTrue (bar_t.IsGenericInstance); - - var bar_t_instance = (GenericInstanceType) bar_t; - - Assert.AreEqual (bar.GenericParameters [0], bar_t_instance.GenericArguments [0]); - - var self_str = bar.GetMethod ("SelfString"); - Assert.IsNotNull (self_str); - - var bar_str = self_str.ReturnType; - Assert.IsTrue (bar_str.IsGenericInstance); - - var bar_str_instance = (GenericInstanceType) bar_str; - - Assert.AreEqual ("System.String", bar_str_instance.GenericArguments [0].FullName); - } - - [TestCSharp ("Generics.cs")] - public void ReturnGenericInstanceWithMethodParameter (ModuleDefinition module) - { - var baz = module.GetType ("Baz"); - - var gazoo = baz.GetMethod ("Gazoo"); - Assert.IsNotNull (gazoo); - - var bar_bingo = gazoo.ReturnType; - - Assert.IsTrue (bar_bingo.IsGenericInstance); - - var bar_bingo_instance = (GenericInstanceType) bar_bingo; - - Assert.AreEqual (gazoo.GenericParameters [0], bar_bingo_instance.GenericArguments [0]); - } - - [TestCSharp ("Interfaces.cs")] - public void SimpleOverrides (ModuleDefinition module) - { - var ibingo = module.GetType ("IBingo"); - var ibingo_foo = ibingo.GetMethod ("Foo"); - Assert.IsNotNull (ibingo_foo); - - var ibingo_bar = ibingo.GetMethod ("Bar"); - Assert.IsNotNull (ibingo_bar); - - var bingo = module.GetType ("Bingo"); - - var foo = bingo.GetMethod ("IBingo.Foo"); - Assert.IsNotNull (foo); - - Assert.IsTrue (foo.HasOverrides); - Assert.AreEqual (ibingo_foo, foo.Overrides [0]); - - var bar = bingo.GetMethod ("IBingo.Bar"); - Assert.IsNotNull (bar); - - Assert.IsTrue (bar.HasOverrides); - Assert.AreEqual (ibingo_bar, bar.Overrides [0]); - } - - [TestModule ("varargs.exe")] - public void VarArgs (ModuleDefinition module) - { - var module_type = module.Types [0]; - - Assert.AreEqual (3, module_type.Methods.Count); - - var bar = module_type.GetMethod ("Bar"); - var baz = module_type.GetMethod ("Baz"); - var foo = module_type.GetMethod ("Foo"); - - Assert.IsTrue (bar.IsVarArg ()); - Assert.IsFalse (baz.IsVarArg ()); - - Assert.IsTrue(foo.IsVarArg ()); - - var bar_reference = (MethodReference) baz.Body.Instructions.Where (i => i.Offset == 0x000a).First ().Operand; - - Assert.IsTrue (bar_reference.IsVarArg ()); - Assert.AreEqual (0, bar_reference.GetSentinelPosition ()); - - var foo_reference = (MethodReference) baz.Body.Instructions.Where (i => i.Offset == 0x0023).First ().Operand; - - Assert.IsTrue (foo_reference.IsVarArg ()); - - Assert.AreEqual (1, foo_reference.GetSentinelPosition ()); - } - - [TestCSharp ("Generics.cs")] - public void GenericInstanceMethod (ModuleDefinition module) - { - var type = module.GetType ("It"); - var method = type.GetMethod ("ReadPwow"); - - GenericInstanceMethod instance = null; - - foreach (var instruction in method.Body.Instructions) { - instance = instruction.Operand as GenericInstanceMethod; - if (instance != null) - break; - } - - Assert.IsNotNull (instance); - - Assert.AreEqual (TokenType.MethodSpec, instance.MetadataToken.TokenType); - Assert.AreNotEqual (0, instance.MetadataToken.RID); - } - - [TestCSharp ("Generics.cs")] - public void MethodRefDeclaredOnGenerics (ModuleDefinition module) - { - var type = module.GetType ("Tamtam"); - var beta = type.GetMethod ("Beta"); - var charlie = type.GetMethod ("Charlie"); - - var new_list_beta = (MethodReference) beta.Body.Instructions [0].Operand; - var new_list_charlie = (MethodReference) charlie.Body.Instructions [0].Operand; - - Assert.AreEqual ("System.Collections.Generic.List`1", new_list_beta.DeclaringType.FullName); - Assert.AreEqual ("System.Collections.Generic.List`1", new_list_charlie.DeclaringType.FullName); - } - - [Test] - public void ReturnParameterMethod () - { - var method = typeof (MethodTests).ToDefinition ().GetMethod ("ReturnParameterMethod"); - Assert.IsNotNull (method); - Assert.AreEqual (method, method.MethodReturnType.Parameter.Method); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/ModuleTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/ModuleTests.cs deleted file mode 100644 index 00f9e1af6..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/ModuleTests.cs +++ /dev/null @@ -1,250 +0,0 @@ -using System; -using System.Diagnostics; -using System.IO; -using System.Linq; - -using Mono.Cecil; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class ModuleTests : BaseTestFixture { - - [Test] - public void CreateModuleEscapesAssemblyName () - { - var module = ModuleDefinition.CreateModule ("Test.dll", ModuleKind.Dll); - Assert.AreEqual ("Test", module.Assembly.Name.Name); - - module = ModuleDefinition.CreateModule ("Test.exe", ModuleKind.Console); - Assert.AreEqual ("Test", module.Assembly.Name.Name); - } - - [TestModule ("hello.exe")] - public void SingleModule (ModuleDefinition module) - { - var assembly = module.Assembly; - - Assert.AreEqual (1, assembly.Modules.Count); - Assert.IsNotNull (assembly.MainModule); - } - - [TestModule ("hello.exe")] - public void EntryPoint (ModuleDefinition module) - { - var entry_point = module.EntryPoint; - Assert.IsNotNull (entry_point); - - Assert.AreEqual ("System.Void Program::Main()", entry_point.ToString ()); - } - - [TestModule ("mma.exe")] - public void MultiModules (ModuleDefinition module) - { - var assembly = module.Assembly; - - Assert.AreEqual (3, assembly.Modules.Count); - - Assert.AreEqual ("mma.exe", assembly.Modules [0].Name); - Assert.AreEqual (ModuleKind.Console, assembly.Modules [0].Kind); - - Assert.AreEqual ("moda.netmodule", assembly.Modules [1].Name); - Assert.AreEqual ("eedb4721-6c3e-4d9a-be30-49021121dd92", assembly.Modules [1].Mvid.ToString ()); - Assert.AreEqual (ModuleKind.NetModule, assembly.Modules [1].Kind); - - Assert.AreEqual ("modb.netmodule", assembly.Modules [2].Name); - Assert.AreEqual ("46c5c577-11b2-4ea0-bb3c-3c71f1331dd0", assembly.Modules [2].Mvid.ToString ()); - Assert.AreEqual (ModuleKind.NetModule, assembly.Modules [2].Kind); - } - - [TestModule ("hello.exe")] - public void ModuleInformation (ModuleDefinition module) - { - Assert.IsNotNull (module); - - Assert.AreEqual ("hello.exe", module.Name); - Assert.AreEqual (new Guid ("C3BC2BD3-2576-4D00-A80E-465B5632415F"), module.Mvid); - } - - [TestModule ("hello.exe")] - public void AssemblyReferences (ModuleDefinition module) - { - Assert.AreEqual (1, module.AssemblyReferences.Count); - - var reference = module.AssemblyReferences [0]; - - Assert.AreEqual ("mscorlib", reference.Name); - Assert.AreEqual (new Version (2, 0, 0, 0), reference.Version); - Assert.AreEqual (new byte [] { 0xB7, 0x7A, 0x5C, 0x56, 0x19, 0x34, 0xE0, 0x89 }, reference.PublicKeyToken); - } - - [TestModule ("pinvoke.exe")] - public void ModuleReferences (ModuleDefinition module) - { - Assert.AreEqual (2, module.ModuleReferences.Count); - Assert.AreEqual ("kernel32.dll", module.ModuleReferences [0].Name); - Assert.AreEqual ("shell32.dll", module.ModuleReferences [1].Name); - } - - [TestModule ("hello.exe")] - public void Types (ModuleDefinition module) - { - Assert.AreEqual (2, module.Types.Count); - Assert.AreEqual ("", module.Types [0].FullName); - Assert.AreEqual ("", module.GetType ("").FullName); - Assert.AreEqual ("Program", module.Types [1].FullName); - Assert.AreEqual ("Program", module.GetType ("Program").FullName); - } - - [TestModule ("libres.dll")] - public void LinkedResource (ModuleDefinition module) - { - var resource = module.Resources.Where (res => res.Name == "linked.txt").First () as LinkedResource; - Assert.IsNotNull (resource); - - Assert.AreEqual ("linked.txt", resource.Name); - Assert.AreEqual ("linked.txt", resource.File); - Assert.AreEqual (ResourceType.Linked, resource.ResourceType); - Assert.IsTrue (resource.IsPublic); - } - - [TestModule ("libres.dll")] - public void EmbeddedResource (ModuleDefinition module) - { - var resource = module.Resources.Where (res => res.Name == "embedded1.txt").First () as EmbeddedResource; - Assert.IsNotNull (resource); - - Assert.AreEqual ("embedded1.txt", resource.Name); - Assert.AreEqual (ResourceType.Embedded, resource.ResourceType); - Assert.IsTrue (resource.IsPublic); - - using (var reader = new StreamReader (resource.GetResourceStream ())) - Assert.AreEqual ("Hello", reader.ReadToEnd ()); - - resource = module.Resources.Where (res => res.Name == "embedded2.txt").First () as EmbeddedResource; - Assert.IsNotNull (resource); - - Assert.AreEqual ("embedded2.txt", resource.Name); - Assert.AreEqual (ResourceType.Embedded, resource.ResourceType); - Assert.IsTrue (resource.IsPublic); - - using (var reader = new StreamReader (resource.GetResourceStream ())) - Assert.AreEqual ("World", reader.ReadToEnd ()); - } - - [TestModule ("mma.exe")] - public void ExportedTypeFromNetModule (ModuleDefinition module) - { - Assert.IsTrue (module.HasExportedTypes); - Assert.AreEqual (2, module.ExportedTypes.Count); - - var exported_type = module.ExportedTypes [0]; - - Assert.AreEqual ("Module.A.Foo", exported_type.FullName); - Assert.AreEqual ("moda.netmodule", exported_type.Scope.Name); - - exported_type = module.ExportedTypes [1]; - - Assert.AreEqual ("Module.B.Baz", exported_type.FullName); - Assert.AreEqual ("modb.netmodule", exported_type.Scope.Name); - } - - [TestCSharp ("CustomAttributes.cs")] - public void NestedTypeForwarder (ModuleDefinition module) - { - Assert.IsTrue (module.HasExportedTypes); - Assert.AreEqual (2, module.ExportedTypes.Count); - - var exported_type = module.ExportedTypes [0]; - - Assert.AreEqual ("System.Diagnostics.DebuggableAttribute", exported_type.FullName); - Assert.AreEqual ("mscorlib", exported_type.Scope.Name); - Assert.IsTrue (exported_type.IsForwarder); - - var nested_exported_type = module.ExportedTypes [1]; - - Assert.AreEqual ("System.Diagnostics.DebuggableAttribute/DebuggingModes", nested_exported_type.FullName); - Assert.AreEqual (exported_type, nested_exported_type.DeclaringType); - Assert.AreEqual ("mscorlib", nested_exported_type.Scope.Name); - } - - [TestCSharp ("CustomAttributes.cs")] - public void HasTypeReference (ModuleDefinition module) - { - Assert.IsTrue (module.HasTypeReference ("System.Attribute")); - Assert.IsTrue (module.HasTypeReference ("mscorlib", "System.Attribute")); - - Assert.IsFalse (module.HasTypeReference ("System.Core", "System.Attribute")); - Assert.IsFalse (module.HasTypeReference ("System.Linq.Enumerable")); - } - - [TestModule ("libhello.dll")] - public void Win32FileVersion (ModuleDefinition module) - { - var version = FileVersionInfo.GetVersionInfo (module.FullyQualifiedName); - - Assert.AreEqual ("0.0.0.0", version.FileVersion); - } - - [TestModule ("noblob.dll")] - public void ModuleWithoutBlob (ModuleDefinition module) - { - Assert.IsNull (module.Image.BlobHeap); - } - - [Test] - public void MixedModeModule () - { - var module = GetResourceModule ("cppcli.dll"); - - Assert.AreEqual (1, module.ModuleReferences.Count); - Assert.AreEqual (string.Empty, module.ModuleReferences [0].Name); - } - - [Test] - [ExpectedException (typeof (BadImageFormatException))] - public void OpenIrrelevantFile () - { - GetResourceModule ("text_file.txt"); - } - - [Test] - public void WriteModuleTwice () - { - var module = GetResourceModule ("iterator.exe"); - - var path = Path.Combine (Path.GetTempPath (), "cecil"); - var file = Path.Combine (path, "iteratorrt.exe"); - - module.Write (file); - module.Write (file); - } - - [Test] - public void GetTypeNamespacePlusName () - { - var module = GetResourceModule ("moda.netmodule"); - - var type = module.GetType ("Module.A", "Foo"); - Assert.IsNotNull (type); - } - - [Test] - public void OpenModuleImmediate () - { - var module = GetResourceModule ("hello.exe", ReadingMode.Immediate); - - Assert.AreEqual (ReadingMode.Immediate, module.ReadingMode); - } - - [Test] - public void OpenModuleDeferred () - { - var module = GetResourceModule ("hello.exe", ReadingMode.Deferred); - - Assert.AreEqual (ReadingMode.Deferred, module.ReadingMode); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/NestedTypesTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/NestedTypesTests.cs deleted file mode 100644 index a8392928b..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/NestedTypesTests.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; - -using Mono.Cecil; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class NestedTypesTests : BaseTestFixture { - - [TestCSharp ("NestedTypes.cs")] - public void NestedTypes (ModuleDefinition module) - { - var foo = module.GetType ("Foo"); - - Assert.AreEqual ("Foo", foo.Name); - Assert.AreEqual ("Foo", foo.FullName); - Assert.AreEqual (module, foo.Module); - Assert.AreEqual (1, foo.NestedTypes.Count); - - var bar = foo.NestedTypes [0]; - - Assert.AreEqual ("Bar", bar.Name); - Assert.AreEqual ("Foo/Bar", bar.FullName); - Assert.AreEqual (module, bar.Module); - Assert.AreEqual (1, bar.NestedTypes.Count); - - var baz = bar.NestedTypes [0]; - - Assert.AreEqual ("Baz", baz.Name); - Assert.AreEqual ("Foo/Bar/Baz", baz.FullName); - Assert.AreEqual (module, baz.Module); - } - - [TestCSharp ("NestedTypes.cs")] - public void DirectNestedType (ModuleDefinition module) - { - var bingo = module.GetType ("Bingo"); - var get_fuel = bingo.GetMethod ("GetFuel"); - - Assert.AreEqual ("Bingo/Fuel", get_fuel.ReturnType.FullName); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/ParameterTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/ParameterTests.cs deleted file mode 100644 index 124d7e1bd..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/ParameterTests.cs +++ /dev/null @@ -1,224 +0,0 @@ -using System; -using System.Linq; - -using Mono.Cecil; -using Mono.Cecil.Metadata; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class ParameterTests : BaseTestFixture { - - [TestModule ("marshal.dll")] - public void MarshalAsI4 (ModuleDefinition module) - { - var bar = module.GetType ("Bar"); - var pan = bar.GetMethod ("Pan"); - - Assert.AreEqual (1, pan.Parameters.Count); - - var parameter = pan.Parameters [0]; - - Assert.IsTrue (parameter.HasMarshalInfo); - var info = parameter.MarshalInfo; - - Assert.AreEqual (typeof (MarshalInfo), info.GetType ()); - Assert.AreEqual (NativeType.I4, info.NativeType); - } - - [TestModule ("marshal.dll")] - public void CustomMarshaler (ModuleDefinition module) - { - var bar = module.GetType ("Bar"); - var pan = bar.GetMethod ("PanPan"); - - var parameter = pan.Parameters [0]; - - Assert.IsTrue (parameter.HasMarshalInfo); - - var info = (CustomMarshalInfo) parameter.MarshalInfo; - - Assert.AreEqual (Guid.Empty, info.Guid); - Assert.AreEqual (string.Empty, info.UnmanagedType); - Assert.AreEqual (NativeType.CustomMarshaler, info.NativeType); - Assert.AreEqual ("nomnom", info.Cookie); - - Assert.AreEqual ("Boc", info.ManagedType.FullName); - Assert.AreEqual (module, info.ManagedType.Scope); - } - - [TestModule ("marshal.dll")] - public void SafeArrayMarshaler (ModuleDefinition module) - { - var bar = module.GetType ("Bar"); - var pan = bar.GetMethod ("PanPan"); - - Assert.IsTrue (pan.MethodReturnType.HasMarshalInfo); - - var info = (SafeArrayMarshalInfo) pan.MethodReturnType.MarshalInfo; - - Assert.AreEqual (VariantType.Dispatch, info.ElementType); - } - - [TestModule ("marshal.dll")] - public void ArrayMarshaler (ModuleDefinition module) - { - var bar = module.GetType ("Bar"); - var pan = bar.GetMethod ("PanPan"); - - var parameter = pan.Parameters [1]; - - Assert.IsTrue (parameter.HasMarshalInfo); - - var info = (ArrayMarshalInfo) parameter.MarshalInfo; - - Assert.AreEqual (NativeType.I8, info.ElementType); - Assert.AreEqual (66, info.Size); - Assert.AreEqual (2, info.SizeParameterIndex); - - parameter = pan.Parameters [3]; - - Assert.IsTrue (parameter.HasMarshalInfo); - - info = (ArrayMarshalInfo) parameter.MarshalInfo; - - Assert.AreEqual (NativeType.I2, info.ElementType); - Assert.AreEqual (-1, info.Size); - Assert.AreEqual (-1, info.SizeParameterIndex); - } - - [TestModule ("marshal.dll")] - public void ArrayMarshalerSized (ModuleDefinition module) - { - var delegate_type = module.GetType ("SomeMethod"); - var parameter = delegate_type.GetMethod ("Invoke").Parameters [1]; - - Assert.IsTrue (parameter.HasMarshalInfo); - var array_info = (ArrayMarshalInfo) parameter.MarshalInfo; - - Assert.IsNotNull (array_info); - - Assert.AreEqual (0, array_info.SizeParameterMultiplier); - } - - [TestModule ("boxedoptarg.dll")] - public void BoxedDefaultArgumentValue (ModuleDefinition module) - { - var foo = module.GetType ("Foo"); - var bar = foo.GetMethod ("Bar"); - var baz = bar.Parameters [0]; - - Assert.IsTrue (baz.HasConstant); - Assert.AreEqual (-1, baz.Constant); - } - - [Test] - public void AddParameterIndex () - { - var object_ref = new TypeReference ("System", "Object", null, null, false); - var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); - - var x = new ParameterDefinition ("x", ParameterAttributes.None, object_ref); - var y = new ParameterDefinition ("y", ParameterAttributes.None, object_ref); - - method.Parameters.Add (x); - method.Parameters.Add (y); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (1, y.Index); - - Assert.AreEqual (method, x.Method); - Assert.AreEqual (method, y.Method); - } - - [Test] - public void RemoveAtParameterIndex () - { - var object_ref = new TypeReference ("System", "Object", null, null, false); - var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); - - var x = new ParameterDefinition ("x", ParameterAttributes.None, object_ref); - var y = new ParameterDefinition ("y", ParameterAttributes.None, object_ref); - var z = new ParameterDefinition ("y", ParameterAttributes.None, object_ref); - - method.Parameters.Add (x); - method.Parameters.Add (y); - method.Parameters.Add (z); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (1, y.Index); - Assert.AreEqual (2, z.Index); - - method.Parameters.RemoveAt (1); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (-1, y.Index); - Assert.AreEqual (1, z.Index); - } - - [Test] - public void RemoveParameterIndex () - { - var object_ref = new TypeReference ("System", "Object", null, null, false); - var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); - - var x = new ParameterDefinition ("x", ParameterAttributes.None, object_ref); - var y = new ParameterDefinition ("y", ParameterAttributes.None, object_ref); - var z = new ParameterDefinition ("y", ParameterAttributes.None, object_ref); - - method.Parameters.Add (x); - method.Parameters.Add (y); - method.Parameters.Add (z); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (1, y.Index); - Assert.AreEqual (2, z.Index); - - method.Parameters.Remove (y); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (-1, y.Index); - Assert.AreEqual (1, z.Index); - } - - [Test] - public void InsertParameterIndex () - { - var object_ref = new TypeReference ("System", "Object", null, null, false); - var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); - - var x = new ParameterDefinition ("x", ParameterAttributes.None, object_ref); - var y = new ParameterDefinition ("y", ParameterAttributes.None, object_ref); - var z = new ParameterDefinition ("y", ParameterAttributes.None, object_ref); - - method.Parameters.Add (x); - method.Parameters.Add (z); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (-1, y.Index); - Assert.AreEqual (1, z.Index); - - method.Parameters.Insert (1, y); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (1, y.Index); - Assert.AreEqual (2, z.Index); - } - - [TestIL ("hello.il")] - public void GenericParameterConstant (ModuleDefinition module) - { - var foo = module.GetType ("Foo"); - var method = foo.GetMethod ("GetState"); - - Assert.IsNotNull (method); - - var parameter = method.Parameters [1]; - - Assert.IsTrue (parameter.HasConstant); - Assert.IsNull (parameter.Constant); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/PropertyTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/PropertyTests.cs deleted file mode 100644 index 2ff9c9285..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/PropertyTests.cs +++ /dev/null @@ -1,112 +0,0 @@ -using System.Linq; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class PropertyTests : BaseTestFixture { - - [TestCSharp ("Properties.cs")] - public void AbstractMethod (ModuleDefinition module) - { - var type = module.GetType ("Foo"); - - Assert.IsTrue (type.HasProperties); - - var properties = type.Properties; - - Assert.AreEqual (3, properties.Count); - - var property = properties [0]; - - Assert.IsNotNull (property); - Assert.AreEqual ("Bar", property.Name); - Assert.IsNotNull (property.PropertyType); - Assert.AreEqual ("System.Int32", property.PropertyType.FullName); - - Assert.IsNotNull (property.GetMethod); - Assert.AreEqual (MethodSemanticsAttributes.Getter, property.GetMethod.SemanticsAttributes); - Assert.IsNull (property.SetMethod); - - property = properties [1]; - - Assert.IsNotNull (property); - Assert.AreEqual ("Baz", property.Name); - Assert.IsNotNull (property.PropertyType); - Assert.AreEqual ("System.String", property.PropertyType.FullName); - - Assert.IsNotNull (property.GetMethod); - Assert.AreEqual (MethodSemanticsAttributes.Getter, property.GetMethod.SemanticsAttributes); - Assert.IsNotNull (property.SetMethod); - Assert.AreEqual (MethodSemanticsAttributes.Setter, property.SetMethod.SemanticsAttributes); - - property = properties [2]; - - Assert.IsNotNull (property); - Assert.AreEqual ("Gazonk", property.Name); - Assert.IsNotNull (property.PropertyType); - Assert.AreEqual ("System.String", property.PropertyType.FullName); - - Assert.IsNull (property.GetMethod); - Assert.IsNotNull (property.SetMethod); - Assert.AreEqual (MethodSemanticsAttributes.Setter, property.SetMethod.SemanticsAttributes); - } - - [TestIL ("others.il")] - public void OtherMethod (ModuleDefinition module) - { - var type = module.GetType ("Others"); - - Assert.IsTrue (type.HasProperties); - - var properties = type.Properties; - - Assert.AreEqual (1, properties.Count); - - var property = properties [0]; - - Assert.IsNotNull (property); - Assert.AreEqual ("Context", property.Name); - Assert.IsNotNull (property.PropertyType); - Assert.AreEqual ("System.String", property.PropertyType.FullName); - - Assert.IsTrue (property.HasOtherMethods); - - Assert.AreEqual (2, property.OtherMethods.Count); - - var other = property.OtherMethods [0]; - Assert.AreEqual ("let_Context", other.Name); - - other = property.OtherMethods [1]; - Assert.AreEqual ("bet_Context", other.Name); - } - - [TestCSharp ("Properties.cs")] - public void SetOnlyIndexer (ModuleDefinition module) - { - var type = module.GetType ("Bar"); - var indexer = type.Properties.Where (property => property.Name == "Item").First (); - - var parameters = indexer.Parameters; - - Assert.AreEqual (2, parameters.Count); - Assert.AreEqual ("System.Int32", parameters [0].ParameterType.FullName); - Assert.AreEqual ("System.String", parameters [1].ParameterType.FullName); - } - - [TestCSharp ("Properties.cs")] - public void ReadSemanticsFirst (ModuleDefinition module) - { - var type = module.GetType ("Baz"); - var setter = type.GetMethod ("set_Bingo"); - - Assert.AreEqual (MethodSemanticsAttributes.Setter, setter.SemanticsAttributes); - - var property = type.Properties.Where (p => p.Name == "Bingo").First (); - - Assert.AreEqual (setter, property.SetMethod); - Assert.AreEqual (type.GetMethod ("get_Bingo"), property.GetMethod); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/ResolveTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/ResolveTests.cs deleted file mode 100644 index 9ec1be8f2..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/ResolveTests.cs +++ /dev/null @@ -1,262 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -using Mono.Cecil; -using Mono.Cecil.Cil; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class ResolveTests : BaseTestFixture { - - [Test] - public void StringEmpty () - { - var string_empty = GetReference, FieldReference> ( - () => string.Empty); - - Assert.AreEqual ("System.String System.String::Empty", string_empty.FullName); - - var definition = string_empty.Resolve (); - - Assert.IsNotNull (definition); - - Assert.AreEqual ("System.String System.String::Empty", definition.FullName); - Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); - } - - delegate string GetSubstring (string str, int start, int length); - - [Test] - public void StringSubstring () - { - var string_substring = GetReference ( - (s, start, length) => s.Substring (start, length)); - - var definition = string_substring.Resolve (); - - Assert.IsNotNull (definition); - - Assert.AreEqual ("System.String System.String::Substring(System.Int32,System.Int32)", definition.FullName); - Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); - } - - [Test] - public void StringLength () - { - var string_length = GetReference, MethodReference> (s => s.Length); - - var definition = string_length.Resolve (); - - Assert.IsNotNull (definition); - - Assert.AreEqual ("get_Length", definition.Name); - Assert.AreEqual ("System.String", definition.DeclaringType.FullName); - Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); - } - - [Test] - public void ListOfStringAdd () - { - var list_add = GetReference>, MethodReference> ( - list => list.Add ("coucou")); - - Assert.AreEqual ("System.Void System.Collections.Generic.List`1::Add(!0)", list_add.FullName); - - var definition = list_add.Resolve (); - - Assert.IsNotNull (definition); - - Assert.AreEqual ("System.Void System.Collections.Generic.List`1::Add(T)", definition.FullName); - Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); - } - - [Test] - public void DictionaryOfStringTypeDefinitionTryGetValue () - { - var try_get_value = GetReference, string, bool>, MethodReference> ( - (d, s) => { - TypeDefinition type; - return d.TryGetValue (s, out type); - }); - - Assert.AreEqual ("System.Boolean System.Collections.Generic.Dictionary`2::TryGetValue(!0,!1&)", - try_get_value.FullName); - - var definition = try_get_value.Resolve (); - - Assert.IsNotNull (definition); - - Assert.AreEqual ("System.Boolean System.Collections.Generic.Dictionary`2::TryGetValue(TKey,TValue&)", definition.FullName); - Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); - } - - class CustomResolver : DefaultAssemblyResolver { - - public void Register (AssemblyDefinition assembly) - { - this.RegisterAssembly (assembly); - this.AddSearchDirectory (Path.GetDirectoryName (assembly.MainModule.FullyQualifiedName)); - } - } - - [Test] - public void ExportedTypeFromModule () - { - var resolver = new CustomResolver (); - var parameters = new ReaderParameters { AssemblyResolver = resolver }; - var mma = GetResourceModule ("mma.exe", parameters); - - resolver.Register (mma.Assembly); - - var current_module = GetCurrentModule (parameters); - var reference = new TypeReference ("Module.A", "Foo", current_module, AssemblyNameReference.Parse (mma.Assembly.FullName), false); - - var definition = reference.Resolve (); - Assert.IsNotNull (definition); - Assert.AreEqual ("Module.A.Foo", definition.FullName); - } - - [Test] - public void TypeForwarder () - { - var resolver = new CustomResolver (); - var parameters = new ReaderParameters { AssemblyResolver = resolver }; - - var types = ModuleDefinition.ReadModule ( - CompilationService.CompileResource (GetCSharpResourcePath ("CustomAttributes.cs", typeof (ResolveTests).Assembly)), - parameters); - - resolver.Register (types.Assembly); - - var current_module = GetCurrentModule (parameters); - var reference = new TypeReference ("System.Diagnostics", "DebuggableAttribute", current_module, AssemblyNameReference.Parse (types.Assembly.FullName), false); - - var definition = reference.Resolve (); - Assert.IsNotNull (definition); - Assert.AreEqual ("System.Diagnostics.DebuggableAttribute", definition.FullName); - Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); - } - - [Test] - public void NestedTypeForwarder () - { - var resolver = new CustomResolver (); - var parameters = new ReaderParameters { AssemblyResolver = resolver }; - - var types = ModuleDefinition.ReadModule ( - CompilationService.CompileResource (GetCSharpResourcePath ("CustomAttributes.cs", typeof (ResolveTests).Assembly)), - parameters); - - resolver.Register (types.Assembly); - - var current_module = GetCurrentModule (parameters); - var reference = new TypeReference ("", "DebuggingModes", current_module, null, true); - reference.DeclaringType = new TypeReference ("System.Diagnostics", "DebuggableAttribute", current_module, AssemblyNameReference.Parse (types.Assembly.FullName), false); - - var definition = reference.Resolve (); - Assert.IsNotNull (definition); - Assert.AreEqual ("System.Diagnostics.DebuggableAttribute/DebuggingModes", definition.FullName); - Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); - } - - [Test] - public void RectangularArrayResolveGetMethod () - { - var get_a_b = GetReference, MethodReference> (matrix => matrix [2, 2]); - - Assert.AreEqual ("Get", get_a_b.Name); - Assert.IsNotNull (get_a_b.Module); - Assert.IsNull (get_a_b.Resolve ()); - } - - [Test] - public void ResolveFunctionPointer () - { - var module = GetResourceModule ("cppcli.dll"); - var global = module.GetType (""); - var field = global.GetField ("__onexitbegin_app_domain"); - - var type = field.FieldType as PointerType; - Assert.IsNotNull(type); - - var fnptr = type.ElementType as FunctionPointerType; - Assert.IsNotNull (fnptr); - - Assert.IsNull (fnptr.Resolve ()); - } - - [Test] - public void ResolveGenericParameter () - { - var collection = typeof (Mono.Collections.Generic.Collection<>).ToDefinition (); - var parameter = collection.GenericParameters [0]; - - Assert.IsNotNull (parameter); - - Assert.IsNull (parameter.Resolve ()); - } - - [Test] - public void ResolveNullVersionAssembly () - { - var reference = AssemblyNameReference.Parse ("System.Core"); - reference.Version = null; - - var resolver = new DefaultAssemblyResolver (); - Assert.IsNotNull (resolver.Resolve (reference)); - } - - static TRet GetReference (TDel code) - { - var @delegate = code as Delegate; - if (@delegate == null) - throw new InvalidOperationException (); - - var reference = (TRet) GetReturnee (GetMethodFromDelegate (@delegate)); - - Assert.IsNotNull (reference); - - return reference; - } - - static object GetReturnee (MethodDefinition method) - { - Assert.IsTrue (method.HasBody); - - var instruction = method.Body.Instructions [method.Body.Instructions.Count - 1]; - - Assert.IsNotNull (instruction); - - while (instruction != null) { - var opcode = instruction.OpCode; - switch (opcode.OperandType) { - case OperandType.InlineField: - case OperandType.InlineTok: - case OperandType.InlineType: - case OperandType.InlineMethod: - return instruction.Operand; - default: - instruction = instruction.Previous; - break; - } - } - - throw new InvalidOperationException (); - } - - static MethodDefinition GetMethodFromDelegate (Delegate @delegate) - { - var method = @delegate.Method; - var type = (TypeDefinition) TypeParser.ParseType (GetCurrentModule (), method.DeclaringType.FullName); - - Assert.IsNotNull (type); - - return type.Methods.Where (m => m.Name == method.Name).First (); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/SecurityDeclarationTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/SecurityDeclarationTests.cs deleted file mode 100644 index 2cc8d5b43..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/SecurityDeclarationTests.cs +++ /dev/null @@ -1,290 +0,0 @@ -using System; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; - -using Mono.Cecil; -using Mono.Cecil.Metadata; -using Mono.Cecil.PE; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class SecurityDeclarationTests : BaseTestFixture { - - [TestModule ("decsec-xml.dll")] - public void XmlSecurityDeclaration (ModuleDefinition module) - { - var type = module.GetType ("SubLibrary"); - - Assert.IsTrue (type.HasSecurityDeclarations); - - Assert.AreEqual (1, type.SecurityDeclarations.Count); - - var declaration = type.SecurityDeclarations [0]; - Assert.AreEqual (SecurityAction.Deny, declaration.Action); - - Assert.AreEqual (1, declaration.SecurityAttributes.Count); - - var attribute = declaration.SecurityAttributes [0]; - - Assert.AreEqual ("System.Security.Permissions.PermissionSetAttribute", attribute.AttributeType.FullName); - - Assert.AreEqual (1, attribute.Properties.Count); - - var named_argument = attribute.Properties [0]; - - Assert.AreEqual ("XML", named_argument.Name); - - var argument = named_argument.Argument; - - Assert.AreEqual ("System.String", argument.Type.FullName); - - const string permission_set = "\r\n\r\n\r\n"; - - Assert.AreEqual (permission_set, argument.Value); - } - - [TestModule ("decsec1-xml.dll")] - public void XmlNet_1_1SecurityDeclaration (ModuleDefinition module) - { - var type = module.GetType ("SubLibrary"); - - Assert.IsTrue (type.HasSecurityDeclarations); - - Assert.AreEqual (1, type.SecurityDeclarations.Count); - - var declaration = type.SecurityDeclarations [0]; - Assert.AreEqual (SecurityAction.Deny, declaration.Action); - - Assert.AreEqual (1, declaration.SecurityAttributes.Count); - - var attribute = declaration.SecurityAttributes [0]; - - Assert.AreEqual ("System.Security.Permissions.PermissionSetAttribute", attribute.AttributeType.FullName); - - Assert.AreEqual (1, attribute.Properties.Count); - - var named_argument = attribute.Properties [0]; - - Assert.AreEqual ("XML", named_argument.Name); - - var argument = named_argument.Argument; - - Assert.AreEqual ("System.String", argument.Type.FullName); - - const string permission_set = "\r\n\r\n\r\n"; - - Assert.AreEqual (permission_set, argument.Value); - } - - [Test] - public void DefineSecurityDeclarationByBlob () - { - var file = Path.Combine(Path.GetTempPath(), "SecDecBlob.dll"); - var module = ModuleDefinition.CreateModule ("SecDecBlob.dll", new ModuleParameters { Kind = ModuleKind.Dll, Runtime = TargetRuntime.Net_2_0 }); - - const string permission_set = "\r\n\r\n\r\n"; - - var declaration = new SecurityDeclaration (SecurityAction.Deny, Encoding.Unicode.GetBytes (permission_set)); - module.Assembly.SecurityDeclarations.Add (declaration); - - module.Write (file); - module = ModuleDefinition.ReadModule (file); - - declaration = module.Assembly.SecurityDeclarations [0]; - Assert.AreEqual (SecurityAction.Deny, declaration.Action); - Assert.AreEqual (1, declaration.SecurityAttributes.Count); - - var attribute = declaration.SecurityAttributes [0]; - Assert.AreEqual ("System.Security.Permissions.PermissionSetAttribute", attribute.AttributeType.FullName); - Assert.AreEqual (1, attribute.Properties.Count); - - var named_argument = attribute.Properties [0]; - Assert.AreEqual ("XML", named_argument.Name); - var argument = named_argument.Argument; - Assert.AreEqual ("System.String", argument.Type.FullName); - Assert.AreEqual (permission_set, argument.Value); - } - - [TestModule ("empty-decsec-att.dll")] - public void SecurityDeclarationWithoutAttributes (ModuleDefinition module) - { - var type = module.GetType ("TestSecurityAction.ModalUITypeEditor"); - var method = type.GetMethod ("GetEditStyle"); - - Assert.IsNotNull (method); - - Assert.AreEqual (1, method.SecurityDeclarations.Count); - - var declaration = method.SecurityDeclarations [0]; - Assert.AreEqual (SecurityAction.LinkDemand, declaration.Action); - Assert.AreEqual (1, declaration.SecurityAttributes.Count); - - var attribute = declaration.SecurityAttributes [0]; - Assert.AreEqual ("System.Security.Permissions.SecurityPermissionAttribute", attribute.AttributeType.FullName); - Assert.AreEqual (0, attribute.Fields.Count); - Assert.AreEqual (0, attribute.Properties.Count); - } - - [TestModule ("decsec-att.dll")] - public void AttributeSecurityDeclaration (ModuleDefinition module) - { - var type = module.GetType ("SubLibrary"); - - Assert.IsTrue (type.HasSecurityDeclarations); - - Assert.AreEqual (1, type.SecurityDeclarations.Count); - - var declaration = type.SecurityDeclarations [0]; - Assert.AreEqual (SecurityAction.Deny, declaration.Action); - - Assert.AreEqual (1, declaration.SecurityAttributes.Count); - - var attribute = declaration.SecurityAttributes [0]; - - Assert.AreEqual ("System.Security.Permissions.SecurityPermissionAttribute", attribute.AttributeType.FullName); - - Assert.AreEqual (1, attribute.Properties.Count); - - var named_argument = attribute.Properties [0]; - - Assert.AreEqual ("UnmanagedCode", named_argument.Name); - - var argument = named_argument.Argument; - - Assert.AreEqual ("System.Boolean", argument.Type.FullName); - - Assert.AreEqual (true, argument.Value); - } - - static void AssertCustomAttributeArgument (string expected, CustomAttributeNamedArgument named_argument) - { - AssertCustomAttributeArgument (expected, named_argument.Argument); - } - - static void AssertCustomAttributeArgument (string expected, CustomAttributeArgument argument) - { - var result = new StringBuilder (); - PrettyPrint (argument, result); - - Assert.AreEqual (expected, result.ToString ()); - } - - static string PrettyPrint (CustomAttribute attribute) - { - var signature = new StringBuilder (); - signature.Append (".ctor ("); - - for (int i = 0; i < attribute.ConstructorArguments.Count; i++) { - if (i > 0) - signature.Append (", "); - - PrettyPrint (attribute.ConstructorArguments [i], signature); - } - - signature.Append (")"); - return signature.ToString (); - } - - static void PrettyPrint (CustomAttributeArgument argument, StringBuilder signature) - { - var value = argument.Value; - - signature.Append ("("); - - PrettyPrint (argument.Type, signature); - - signature.Append (":"); - - PrettyPrintValue (argument.Value, signature); - - signature.Append (")"); - } - - static void PrettyPrintValue (object value, StringBuilder signature) - { - if (value == null) { - signature.Append ("null"); - return; - } - - var arguments = value as CustomAttributeArgument []; - if (arguments != null) { - signature.Append ("{"); - for (int i = 0; i < arguments.Length; i++) { - if (i > 0) - signature.Append (", "); - - PrettyPrint (arguments [i], signature); - } - signature.Append ("}"); - - return; - } - - switch (Type.GetTypeCode (value.GetType ())) { - case TypeCode.String: - signature.AppendFormat ("\"{0}\"", value); - break; - case TypeCode.Char: - signature.AppendFormat ("'{0}'", (char) value); - break; - default: - var formattable = value as IFormattable; - if (formattable != null) { - signature.Append (formattable.ToString (null, CultureInfo.InvariantCulture)); - return; - } - - if (value is CustomAttributeArgument) { - PrettyPrint ((CustomAttributeArgument) value, signature); - return; - } - break; - } - } - - static void PrettyPrint (TypeReference type, StringBuilder signature) - { - if (type.IsArray) { - ArrayType array = (ArrayType) type; - signature.AppendFormat ("{0}[]", array.ElementType.etype.ToString ()); - } else if (type.etype == ElementType.None) { - signature.Append (type.FullName); - } else - signature.Append (type.etype.ToString ()); - } - - static void AssertArgument (T value, CustomAttributeNamedArgument named_argument) - { - AssertArgument (value, named_argument.Argument); - } - - static void AssertArgument (T value, CustomAttributeArgument argument) - { - AssertArgument (typeof (T).FullName, (object) value, argument); - } - - static void AssertArgument (string type, object value, CustomAttributeArgument argument) - { - Assert.AreEqual (type, argument.Type.FullName); - Assert.AreEqual (value, argument.Value); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/TypeParserTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/TypeParserTests.cs deleted file mode 100644 index 6b52e98a9..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/TypeParserTests.cs +++ /dev/null @@ -1,394 +0,0 @@ -using System; -using System.Linq; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class TypeParserTests : BaseTestFixture { - - [Test] - public void SimpleStringReference () - { - var module = GetCurrentModule (); - var corlib = module.TypeSystem.Corlib; - - const string fullname = "System.String"; - - var type = TypeParser.ParseType (module, fullname); - Assert.IsNotNull (type); - Assert.AreEqual (corlib, type.Scope); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("System", type.Namespace); - Assert.AreEqual ("String", type.Name); - Assert.AreEqual (MetadataType.String, type.MetadataType); - Assert.IsFalse (type.IsValueType); - Assert.IsInstanceOf (typeof (TypeReference), type); - } - - [Test] - public void SimpleInt32Reference () - { - var module = GetCurrentModule (); - var corlib = module.TypeSystem.Corlib; - - const string fullname = "System.Int32"; - - var type = TypeParser.ParseType (module, fullname); - Assert.IsNotNull (type); - Assert.AreEqual (corlib, type.Scope); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("System", type.Namespace); - Assert.AreEqual ("Int32", type.Name); - Assert.AreEqual (MetadataType.Int32, type.MetadataType); - Assert.IsTrue (type.IsValueType); - Assert.IsInstanceOf (typeof (TypeReference), type); - } - - [Test] - public void SimpleTypeDefinition () - { - var module = GetCurrentModule (); - - const string fullname = "Mono.Cecil.Tests.TypeParserTests"; - - var type = TypeParser.ParseType (module, fullname); - Assert.IsNotNull (type); - Assert.AreEqual (module, type.Scope); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("Mono.Cecil.Tests", type.Namespace); - Assert.AreEqual ("TypeParserTests", type.Name); - Assert.IsInstanceOf (typeof (TypeDefinition), type); - } - - [Test] - public void ByRefTypeReference () - { - var module = GetCurrentModule (); - var corlib = module.TypeSystem.Corlib; - - const string fullname = "System.String&"; - - var type = TypeParser.ParseType (module, fullname); - - Assert.IsInstanceOf (typeof (ByReferenceType), type); - - type = ((ByReferenceType) type).ElementType; - - Assert.IsNotNull (type); - Assert.AreEqual (corlib, type.Scope); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("System", type.Namespace); - Assert.AreEqual ("String", type.Name); - Assert.IsInstanceOf (typeof (TypeReference), type); - } - - [Test] - public void FullyQualifiedTypeReference () - { - var module = GetCurrentModule (); - var cecil = module.AssemblyReferences.Where (reference => reference.Name == "Mono.Cecil").First (); - - var fullname = "Mono.Cecil.TypeDefinition, " + cecil.FullName; - - var type = TypeParser.ParseType (module, fullname); - Assert.IsNotNull (type); - Assert.AreEqual (cecil, type.Scope); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("Mono.Cecil", type.Namespace); - Assert.AreEqual ("TypeDefinition", type.Name); - Assert.IsInstanceOf (typeof (TypeReference), type); - } - - [Test] - public void OpenGenericType () - { - var module = GetCurrentModule (); - var corlib = module.TypeSystem.Corlib; - - const string fullname = "System.Collections.Generic.Dictionary`2"; - - var type = TypeParser.ParseType (module, fullname); - Assert.IsNotNull (type); - Assert.AreEqual (corlib, type.Scope); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("System.Collections.Generic", type.Namespace); - Assert.AreEqual ("Dictionary`2", type.Name); - Assert.IsInstanceOf (typeof (TypeReference), type); - Assert.AreEqual (2, type.GenericParameters.Count); - } - - public class ID {} - - [Test] - public void SimpleNestedType () - { - var module = GetCurrentModule (); - - const string fullname = "Mono.Cecil.Tests.TypeParserTests+ID"; - - var type = TypeParser.ParseType (module, fullname); - - Assert.IsNotNull (type); - Assert.AreEqual (module, type.Module); - Assert.AreEqual (module, type.Scope); - Assert.AreEqual ("", type.Namespace); - Assert.AreEqual ("ID", type.Name); - - Assert.AreEqual ("Mono.Cecil.Tests.TypeParserTests/ID", type.FullName); - Assert.AreEqual (fullname, TypeParser.ToParseable (type)); - } - - [Test] - public void TripleNestedTypeWithScope () - { - var module = GetCurrentModule (); - - const string fullname = "Bingo.Foo`1+Bar`1+Baz`1, Bingo"; - - var type = TypeParser.ParseType (module, fullname); - - Assert.AreEqual ("Bingo.Foo`1+Bar`1+Baz`1, Bingo, Culture=neutral, PublicKeyToken=null", TypeParser.ToParseable (type)); - - Assert.IsNotNull (type); - Assert.AreEqual ("Bingo", type.Scope.Name); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("", type.Namespace); - Assert.AreEqual ("Baz`1", type.Name); - Assert.IsInstanceOf (typeof (TypeReference), type); - Assert.AreEqual (1, type.GenericParameters.Count); - - type = type.DeclaringType; - - Assert.IsNotNull (type); - Assert.AreEqual ("Bingo", type.Scope.Name); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("", type.Namespace); - Assert.AreEqual ("Bar`1", type.Name); - Assert.IsInstanceOf (typeof (TypeReference), type); - Assert.AreEqual (1, type.GenericParameters.Count); - - type = type.DeclaringType; - - Assert.IsNotNull (type); - Assert.AreEqual ("Bingo", type.Scope.Name); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("Bingo", type.Namespace); - Assert.AreEqual ("Foo`1", type.Name); - Assert.IsInstanceOf (typeof (TypeReference), type); - Assert.AreEqual (1, type.GenericParameters.Count); - } - - [Test] - public void Vector () - { - var module = GetCurrentModule (); - - const string fullname = "Bingo.Gazonk[], Bingo"; - - var type = TypeParser.ParseType (module, fullname); - - Assert.AreEqual ("Bingo.Gazonk[], Bingo, Culture=neutral, PublicKeyToken=null", TypeParser.ToParseable (type)); - - var array = type as ArrayType; - Assert.IsNotNull (array); - Assert.AreEqual (1, array.Rank); - Assert.IsTrue (array.IsVector); - - type = array.ElementType; - - Assert.IsNotNull (type); - Assert.AreEqual ("Bingo", type.Scope.Name); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("Bingo", type.Namespace); - Assert.AreEqual ("Gazonk", type.Name); - Assert.IsInstanceOf (typeof (TypeReference), type); - } - - [Test] - public void ThreeDimensionalArray () - { - var module = GetCurrentModule (); - - const string fullname = "Bingo.Gazonk[,,], Bingo"; - - var type = TypeParser.ParseType (module, fullname); - - var array = type as ArrayType; - Assert.IsNotNull (array); - Assert.AreEqual (3, array.Rank); - Assert.IsFalse (array.IsVector); - - type = array.ElementType; - - Assert.IsNotNull (type); - Assert.AreEqual ("Bingo", type.Scope.Name); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("Bingo", type.Namespace); - Assert.AreEqual ("Gazonk", type.Name); - Assert.IsInstanceOf (typeof (TypeReference), type); - } - - [Test] - public void GenericInstanceExternArguments () - { - var module = GetCurrentModule (); - - var fullname = string.Format ("System.Collections.Generic.Dictionary`2[[System.Int32, {0}],[System.String, {0}]]", - typeof (object).Assembly.FullName); - - var type = TypeParser.ParseType (module, fullname); - - Assert.AreEqual (fullname, TypeParser.ToParseable (type)); - - var instance = type as GenericInstanceType; - Assert.IsNotNull (instance); - Assert.AreEqual (2, instance.GenericArguments.Count); - Assert.AreEqual ("mscorlib", type.Scope.Name); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("System.Collections.Generic", type.Namespace); - Assert.AreEqual ("Dictionary`2", type.Name); - - type = instance.ElementType; - - Assert.AreEqual (2, type.GenericParameters.Count); - - var argument = instance.GenericArguments [0]; - Assert.AreEqual ("mscorlib", argument.Scope.Name); - Assert.AreEqual (module, argument.Module); - Assert.AreEqual ("System", argument.Namespace); - Assert.AreEqual ("Int32", argument.Name); - - argument = instance.GenericArguments [1]; - Assert.AreEqual ("mscorlib", argument.Scope.Name); - Assert.AreEqual (module, argument.Module); - Assert.AreEqual ("System", argument.Namespace); - Assert.AreEqual ("String", argument.Name); - } - - [Test] - public void GenericInstanceMixedArguments () - { - var module = GetCurrentModule (); - - var fullname = string.Format ("System.Collections.Generic.Dictionary`2[Mono.Cecil.Tests.TypeParserTests,[System.String, {0}]]", - typeof (object).Assembly.FullName); - - var type = TypeParser.ParseType (module, fullname); - - var instance = type as GenericInstanceType; - Assert.IsNotNull (instance); - Assert.AreEqual (2, instance.GenericArguments.Count); - Assert.AreEqual ("mscorlib", type.Scope.Name); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("System.Collections.Generic", type.Namespace); - Assert.AreEqual ("Dictionary`2", type.Name); - - type = instance.ElementType; - - Assert.AreEqual (2, type.GenericParameters.Count); - - var argument = instance.GenericArguments [0]; - Assert.IsInstanceOf (typeof (TypeDefinition), argument); - Assert.AreEqual (module, argument.Module); - Assert.AreEqual ("Mono.Cecil.Tests", argument.Namespace); - Assert.AreEqual ("TypeParserTests", argument.Name); - - argument = instance.GenericArguments [1]; - Assert.AreEqual ("mscorlib", argument.Scope.Name); - Assert.AreEqual (module, argument.Module); - Assert.AreEqual ("System", argument.Namespace); - Assert.AreEqual ("String", argument.Name); - } - - public class Foo { - } - - public class Bar {} - - [Test] - public void GenericInstanceTwoNonFqArguments () - { - var module = GetCurrentModule (); - - var fullname = string.Format ("System.Collections.Generic.Dictionary`2[Mono.Cecil.Tests.TypeParserTests+Bar,Mono.Cecil.Tests.TypeParserTests+Bar], {0}", typeof (object).Assembly.FullName); - - var type = TypeParser.ParseType (module, fullname); - - var instance = type as GenericInstanceType; - Assert.IsNotNull (instance); - Assert.AreEqual (2, instance.GenericArguments.Count); - Assert.AreEqual ("mscorlib", type.Scope.Name); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("System.Collections.Generic", type.Namespace); - Assert.AreEqual ("Dictionary`2", type.Name); - - type = instance.ElementType; - - Assert.AreEqual (2, type.GenericParameters.Count); - - var argument = instance.GenericArguments [0]; - Assert.AreEqual (module, argument.Module); - Assert.AreEqual ("", argument.Namespace); - Assert.AreEqual ("Bar", argument.Name); - Assert.IsInstanceOf (typeof (TypeDefinition), argument); - - argument = instance.GenericArguments [1]; - Assert.AreEqual (module, argument.Module); - Assert.AreEqual ("", argument.Namespace); - Assert.AreEqual ("Bar", argument.Name); - Assert.IsInstanceOf (typeof (TypeDefinition), argument); - } - - [Test] - public void ComplexGenericInstanceMixedArguments () - { - var module = GetCurrentModule (); - - var fullname = string.Format ("System.Collections.Generic.Dictionary`2[[System.String, {0}],Mono.Cecil.Tests.TypeParserTests+Foo`2[Mono.Cecil.Tests.TypeParserTests,[System.Int32, {0}]]]", - typeof (object).Assembly.FullName); - - var type = TypeParser.ParseType (module, fullname); - - var instance = type as GenericInstanceType; - Assert.IsNotNull (instance); - Assert.AreEqual (2, instance.GenericArguments.Count); - Assert.AreEqual ("mscorlib", type.Scope.Name); - Assert.AreEqual (module, type.Module); - Assert.AreEqual ("System.Collections.Generic", type.Namespace); - Assert.AreEqual ("Dictionary`2", type.Name); - - type = instance.ElementType; - - Assert.AreEqual (2, type.GenericParameters.Count); - - var argument = instance.GenericArguments [0]; - Assert.AreEqual ("mscorlib", argument.Scope.Name); - Assert.AreEqual (module, argument.Module); - Assert.AreEqual ("System", argument.Namespace); - Assert.AreEqual ("String", argument.Name); - - argument = instance.GenericArguments [1]; - - instance = argument as GenericInstanceType; - Assert.IsNotNull (instance); - Assert.AreEqual (2, instance.GenericArguments.Count); - Assert.AreEqual (module, instance.Module); - Assert.AreEqual ("Mono.Cecil.Tests.TypeParserTests/Foo`2", instance.ElementType.FullName); - Assert.IsInstanceOf (typeof (TypeDefinition), instance.ElementType); - - argument = instance.GenericArguments [0]; - Assert.AreEqual (module, argument.Module); - Assert.AreEqual ("Mono.Cecil.Tests", argument.Namespace); - Assert.AreEqual ("TypeParserTests", argument.Name); - Assert.IsInstanceOf (typeof (TypeDefinition), argument); - - argument = instance.GenericArguments [1]; - Assert.AreEqual ("mscorlib", argument.Scope.Name); - Assert.AreEqual (module, argument.Module); - Assert.AreEqual ("System", argument.Namespace); - Assert.AreEqual ("Int32", argument.Name); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/TypeTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/TypeTests.cs deleted file mode 100644 index 3ceb0aa4d..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/TypeTests.cs +++ /dev/null @@ -1,228 +0,0 @@ -using System; -using System.Linq; - -using Mono.Cecil; -using Mono.Cecil.Cil; -using Mono.Cecil.Metadata; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class TypeTests : BaseTestFixture { - - [TestCSharp ("Layouts.cs")] - public void TypeLayout (ModuleDefinition module) - { - var foo = module.GetType ("Foo"); - Assert.IsNotNull (foo); - Assert.IsTrue (foo.IsValueType); - - Assert.IsTrue (foo.HasLayoutInfo); - Assert.AreEqual (16, foo.ClassSize); - - var babar = module.GetType ("Babar"); - Assert.IsNotNull (babar); - Assert.IsFalse (babar.IsValueType); - Assert.IsFalse (babar.HasLayoutInfo); - } - - [TestIL ("types.il")] - public void SimpleInterfaces (ModuleDefinition module) - { - var ibaz = module.GetType ("IBaz"); - Assert.IsNotNull (ibaz); - - Assert.IsTrue (ibaz.HasInterfaces); - - var interfaces = ibaz.Interfaces; - - Assert.AreEqual (2, interfaces.Count); - - Assert.AreEqual ("IBar", interfaces [0].FullName); - Assert.AreEqual ("IFoo", interfaces [1].FullName); - } - - [TestCSharp ("Generics.cs")] - public void GenericTypeDefinition (ModuleDefinition module) - { - var foo = module.GetType ("Foo`2"); - Assert.IsNotNull (foo); - - Assert.IsTrue (foo.HasGenericParameters); - Assert.AreEqual (2, foo.GenericParameters.Count); - - var tbar = foo.GenericParameters [0]; - - Assert.AreEqual ("TBar", tbar.Name); - Assert.AreEqual (foo, tbar.Owner); - - var tbaz = foo.GenericParameters [1]; - - Assert.AreEqual ("TBaz", tbaz.Name); - Assert.AreEqual (foo, tbaz.Owner); - } - - [TestCSharp ("Generics.cs")] - public void ConstrainedGenericType (ModuleDefinition module) - { - var bongo_t = module.GetType ("Bongo`1"); - Assert.IsNotNull (bongo_t); - - var t = bongo_t.GenericParameters [0]; - Assert.IsNotNull (t); - Assert.AreEqual ("T", t.Name); - - Assert.IsTrue (t.HasConstraints); - Assert.AreEqual (2, t.Constraints.Count); - - Assert.AreEqual ("Zap", t.Constraints [0].FullName); - Assert.AreEqual ("IZoom", t.Constraints [1].FullName); - } - - [TestCSharp ("Generics.cs")] - public void GenericBaseType (ModuleDefinition module) - { - var child = module.GetType ("Child`1"); - - var child_t = child.GenericParameters [0]; - Assert.IsNotNull (child_t); - - var instance = child.BaseType as GenericInstanceType; - Assert.IsNotNull (instance); - Assert.AreNotEqual (0, instance.MetadataToken.RID); - - Assert.AreEqual (child_t, instance.GenericArguments [0]); - } - - [TestCSharp ("Generics.cs")] - public void GenericConstraintOnGenericParameter (ModuleDefinition module) - { - var duel = module.GetType ("Duel`3"); - - Assert.AreEqual (3, duel.GenericParameters.Count); - - var t1 = duel.GenericParameters [0]; - var t2 = duel.GenericParameters [1]; - var t3 = duel.GenericParameters [2]; - - Assert.AreEqual (t1, t2.Constraints [0]); - Assert.AreEqual (t2, t3.Constraints [0]); - } - - [TestCSharp ("Generics.cs")] - public void GenericForwardBaseType (ModuleDefinition module) - { - var tamchild = module.GetType ("TamChild"); - - Assert.IsNotNull (tamchild); - Assert.IsNotNull (tamchild.BaseType); - - var generic_instance = tamchild.BaseType as GenericInstanceType; - - Assert.IsNotNull (generic_instance); - - Assert.AreEqual (1, generic_instance.GenericArguments.Count); - Assert.AreEqual (module.GetType ("Tamtam"), generic_instance.GenericArguments [0]); - } - - [TestCSharp ("Generics.cs")] - public void TypeExtentingGenericOfSelf (ModuleDefinition module) - { - var rec_child = module.GetType ("RecChild"); - - Assert.IsNotNull (rec_child); - Assert.IsNotNull (rec_child.BaseType); - - var generic_instance = rec_child.BaseType as GenericInstanceType; - - Assert.IsNotNull (generic_instance); - - Assert.AreEqual (1, generic_instance.GenericArguments.Count); - Assert.AreEqual (rec_child, generic_instance.GenericArguments [0]); - } - - [TestCSharp ("Methods.cs")] - public void TypeReferenceValueType (ModuleDefinition module) - { - var baz = module.GetType ("Baz"); - var method = baz.GetMethod ("PrintAnswer"); - - var box = method.Body.Instructions.Where (i => i.OpCode == OpCodes.Box).First (); - var int32 = (TypeReference) box.Operand; - - Assert.IsTrue (int32.IsValueType); - } - - [TestModule ("gifaceref.exe")] - public void GenericInterfaceReference (ModuleDefinition module) - { - var type = module.GetType ("Program"); - var iface = type.Interfaces [0]; - - var instance = (GenericInstanceType) iface; - var owner = instance.ElementType; - - Assert.AreEqual (1, instance.GenericArguments.Count); - Assert.AreEqual (1, owner.GenericParameters.Count); - } - - [TestModule ("cscgpbug.dll", Verify = false)] - public void UnboundGenericParameter (ModuleDefinition module) - { - var type = module.GetType ("ListViewModel"); - var method = type.GetMethod ("<>n__FabricatedMethod1"); - - var parameter = method.ReturnType as GenericParameter; - - Assert.IsNotNull (parameter); - Assert.AreEqual (0, parameter.Position); - Assert.IsNull (parameter.Owner); - } - - [TestCSharp ("Generics.cs")] - public void GenericMultidimensionalArray (ModuleDefinition module) - { - var type = module.GetType ("LaMatrix"); - var method = type.GetMethod ("At"); - - var call = method.Body.Instructions.Where (i => i.Operand is MethodReference).First (); - var get = (MethodReference) call.Operand; - - Assert.IsNotNull (get); - Assert.AreEqual (0, get.GenericParameters.Count); - Assert.AreEqual (MethodCallingConvention.Default, get.CallingConvention); - Assert.AreEqual (method.GenericParameters [0], get.ReturnType); - } - - [Test] - public void CorlibPrimitive () - { - var module = typeof (TypeTests).ToDefinition ().Module; - - var int32 = module.TypeSystem.Int32; - Assert.IsTrue (int32.IsPrimitive); - Assert.AreEqual (MetadataType.Int32, int32.MetadataType); - - var int32_def = int32.Resolve (); - Assert.IsTrue (int32_def.IsPrimitive); - Assert.AreEqual (MetadataType.Int32, int32_def.MetadataType); - } - - [TestIL ("explicitthis.il", Verify = false)] - public void ExplicitThis (ModuleDefinition module) - { - var type = module.GetType ("MakeDecision"); - var method = type.GetMethod ("Decide"); - var fptr = method.ReturnType as FunctionPointerType; - - Assert.IsNotNull (fptr); - Assert.IsTrue (fptr.HasThis); - Assert.IsTrue (fptr.ExplicitThis); - - Assert.AreEqual (0, fptr.Parameters [0].Sequence); - Assert.AreEqual (1, fptr.Parameters [1].Sequence); - } - } -} diff --git a/Mono.Cecil/Test/Mono.Cecil.Tests/VariableTests.cs b/Mono.Cecil/Test/Mono.Cecil.Tests/VariableTests.cs deleted file mode 100644 index 9f6c54c67..000000000 --- a/Mono.Cecil/Test/Mono.Cecil.Tests/VariableTests.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System; -using System.Linq; - -using Mono.Cecil; -using Mono.Cecil.Cil; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class VariableTests : BaseTestFixture { - - [Test] - public void AddVariableIndex () - { - var object_ref = new TypeReference ("System", "Object", null, null, false); - var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); - var body = new MethodBody (method); - - var x = new VariableDefinition ("x", object_ref); - var y = new VariableDefinition ("y", object_ref); - - body.Variables.Add (x); - body.Variables.Add (y); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (1, y.Index); - } - - [Test] - public void RemoveAtVariableIndex () - { - var object_ref = new TypeReference ("System", "Object", null, null, false); - var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); - var body = new MethodBody (method); - - var x = new VariableDefinition ("x", object_ref); - var y = new VariableDefinition ("y", object_ref); - var z = new VariableDefinition ("z", object_ref); - - body.Variables.Add (x); - body.Variables.Add (y); - body.Variables.Add (z); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (1, y.Index); - Assert.AreEqual (2, z.Index); - - body.Variables.RemoveAt (1); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (-1, y.Index); - Assert.AreEqual (1, z.Index); - } - - [Test] - public void RemoveVariableIndex () - { - var object_ref = new TypeReference ("System", "Object", null, null, false); - var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); - var body = new MethodBody (method); - - var x = new VariableDefinition ("x", object_ref); - var y = new VariableDefinition ("y", object_ref); - var z = new VariableDefinition ("z", object_ref); - - body.Variables.Add (x); - body.Variables.Add (y); - body.Variables.Add (z); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (1, y.Index); - Assert.AreEqual (2, z.Index); - - body.Variables.Remove (y); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (-1, y.Index); - Assert.AreEqual (1, z.Index); - } - - [Test] - public void InsertVariableIndex () - { - var object_ref = new TypeReference ("System", "Object", null, null, false); - var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref); - var body = new MethodBody (method); - - var x = new VariableDefinition ("x", object_ref); - var y = new VariableDefinition ("y", object_ref); - var z = new VariableDefinition ("z", object_ref); - - body.Variables.Add (x); - body.Variables.Add (z); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (-1, y.Index); - Assert.AreEqual (1, z.Index); - - body.Variables.Insert (1, y); - - Assert.AreEqual (0, x.Index); - Assert.AreEqual (1, y.Index); - Assert.AreEqual (2, z.Index); - } - } -} diff --git a/Mono.Cecil/Test/Resources/assemblies/boxedoptarg.dll b/Mono.Cecil/Test/Resources/assemblies/boxedoptarg.dll deleted file mode 100644 index 23edd61bb885effcb95ae501ed93d10716729b94..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3072 zcmeHJ&2Jk;6#uR3L~fu_P^FLx5+-$ms)81y_&^1sZa&%uk|xA%8da5=wY@lt);rej zx;Qxm4obKcEsvBo2h%n_b6tRne;I0inL+eZP70-kX_C zR&U@B*(GhS!E>JS`-^m``qi_8*iu)%Irw^=^!|BS77pYdL8==!wH75vktg5aG z+kx@|wYXMROR8|($woqz>0MOfBy2|)9!8$k(qwQ$|Xe&C)TMvxgwT`LKImh z387@_7mht5?E)E;z6Qq3Z;z*H5`tgP0yji10sHB?)RnMp;MD=cGb##T2gi`3e)U)b z?AYzZ)MsS)^qB@8+n?rbJB-2_-KMru8kf$5nt>9lw?o(03^cWF(=540h<#83=KIt{ zl(`b5whV@FO94AvYl-nWU@CKtOGnNRpXX-fPv)&Olhk#mXcz3c!rc28B=Hb@(nrMn zSHKom?TcKFLoaAV6p>>cGQ<4!GR7$LB$2;zeR+{wQJ0$Y^S-W<3(#a;nFLOX^4IJf z#*;o|#Pk`IzC;%;HsON64=EqU6kf+L%9taKNClD@=|-f}#33WED~cGNnB}l7Y#D7F z?_iYL*qDX)SdI8zBb~q*Bj>pGG;HD|=^J<(**!c4-%^)1*#)crFh5$=^|tSRjAm5R zq3>03S!QFWd)}(^uA5v%}vf zSH5q4_~63Li@zcF>q!3 zUzahYkM_nBGTk#V1$2Lks8R;rWkuF;{33UcP&0X21N$h(7I=$$v73wy8QrU;z%M`# zff7%^GTp=`Hel^O=jEVD9jrj3L#a+KyU7e1%u#2QJhpSDwiQM+%*q85w`;0vV23MU zp2t&&BBLz{Dmc`}1t_WF}vfe*}@OPoW*$R>O8vCFES cwvJ0*!i%1OO8#e1$)C9wo&9CL|M&#{0YH8KWdHyG diff --git a/Mono.Cecil/Test/Resources/assemblies/catch.exe b/Mono.Cecil/Test/Resources/assemblies/catch.exe deleted file mode 100644 index d7ef04afb22c37d1d9c7b15929a40e012140d921..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3584 zcmeHJ&uL1wszk!GQ)PB#J{&t4Oe3Pn@N@JMPTd zbvRVHv{I{9qIW8B>o|^}4N^}PFPS&*y?O7= z_hx2aGX35S>LH?DjHgeD?qJqbF#Mm{Dwg}-xZ6+PZhJUz$C`RLFu&|6R+pkCoq)Mc z7>bBhIFpT#c_Ay!lvyCE+}^pf?@*F@c7kZi>Y<0l#S87-9#hKNZe?Onm^9rV1Y;Nl z49ys(RO|xD;MX&)V!*DchYBAP?KZ!iIZ(}%E;t`hCoXxog=h!W_= zI|Kclb#ZpYTM_i1_2Fa96p-MCW{448wWX3SG=r@GA)O3NZ7Kl0Ex9k?Xs}+ziq5qG zIQ+(8?V?+#Uz5g`qAm0bBf5!L3p$40?S*K2&Z40tVhDNCkJ3Xp*7Wa>cE34j-aseg>fr(H)S`E z+d2E~+==5SbcQYDgYQ7L!HUe_A87HwFuw=IHedXhzmWm_n#8nbY(Z9Y!J7=mPj>hTk@p z2jH4w|G1*vgpE*x)@GSr{gOsZt~-f#(r9-REpN0R60Kmg`$qd@e~J2$d%lTVe?XSid5_Tq;(Mxbi-K4*53t1hK$m5|$aO4bWiG*=HL^^67 zs}8IR>kdWm6VPJ%ruQb2TEG;+%Y(i4j7+-USd?4)8KnwjLJvs6-rl){-4(eePrYj& z2HzasTE}+*z7pOYEIE9;ok28ezIt6vWPC$l_iu?-nKQ;=)M z`z$K0(~3b1)S+wA?@-rX zM7;{00Zz{cD)z5&2&E_Ye#)O|1wLzXsqn#%WsljpEaRaos_6Y=*-P{1j-Jdi6**zm z@kPkTvMXF=&z#=bmv@xnLB(HTND!*AY(s{pl)KCWM;#43R|+MTqNA<|PB|*Do5!*& za6)g1t7u{UZb-%0TC&M18W4I@7b5(z0;JH(v0nE*bS&Vtoq9bx9A}7RLq(I} zlGr4k<5?4jy%l#G5_={(ERuiF08U<=m0lBlw#L;avyQa0GEgTET9n(+h^Kgy`^?vT zEbFMruqoc>GRqoX(M2D}F)lg2;z>~^$?!AKw4o1oVb2e*9ReKk!|fY_qHp^pz3>UJ S_}|0_BQG5JGT?u30)GRb5V>#w diff --git a/Mono.Cecil/Test/Resources/assemblies/cppcli.dll b/Mono.Cecil/Test/Resources/assemblies/cppcli.dll deleted file mode 100644 index f216fde980cbdbb8194a82cd151c07dad8c7cc2e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 50176 zcmeIb34EMY^*4TJduB38noRbVF4HC{Q<8>k-IpwrNs~5PlSxUjI87(hCXkJpNohga zz<^Ri6$KSsi-QUZS`Y*QB``pX7AS~Xwbn|i23r-iO8trC{hssOnaoVnLY3e9dH?^9 zPkWc|Ip^Mc?z!jQ=RV6kX}tV4p%X&r5hf;tcnm2Wl^mZx8V7sYoX4k$hZA0$`k>2&zJ)x&KeJJ!8%N-2e&iuyEqe%C;uVDV8^&OnH_PD#L zu6WH`96~f`4C3yNFRcsnjtlMFL`{Ma^FjHnN`1W?X(~b`<5bRTg)lIjOoh;}(SGUF z2(73DKp`p@NhOr!3ZD~V2j!0oaj#Jlqmws+`xn$3;d)s{hXu@(;TaN?gS1}-qqtw)6ecO zMH7tKsK&T-Egx(~X zY?!!8x?Zv9O=*dc18)JQs%5^(l2~TQPFD(aS?P*Jv7x_a2=)6eLMA=Il3;_e%|7(e zoNlt11~81~bc022!(yQnBzj+jGU`wro1+vaDN)u-C`?L-f=4ZebhE{Li3r=Y5q6|$ zYk&XGT*p%VUp2SOOCko=g>AQU0(om zW_P6PEqdeHs>eY~OEJ#qu)rlR@0gSHPIgwhIc-{&Gs|3{SF$_IN?OW{j{-TS8l zT%m%p(UIR=5sI`QI8`3FK1mGC39LH!3eH-)QtqZSFs=zwdeT@n`o_;t??`eNv>37M z$@Fu}Nt%?K$x#nDPIIF$t{AD*?{SCl3Zz?LZOXPr7o>cpVl)=zr3Fz(7Qj?mhyk?!$=2 z^O$S8dDKrzmP3K=L&Q8tOpVG^3zA*fSjkrksZlwE0;_J}rsj52I{u_;Ak>#S;z(_| zQajRUT0fCVyel;mnSLtqtbQbu?emOg4`<$Z6k3r5Q*M5M%`r}$AK#BWo8#002c2r! z92o3qbBqVBA7^unuV_C-=6I7jcycOpX#FWL$1->kGX4aGdaFk2D?$EEE3ZiOdh7J+PN)hqNap+owJ0g}{iVHLAsd2JvcPd_}Yrb!$YQ#_Twws5BYOO9EbNfUITScLwnkfk2sF+ zaU6N03Nw_3=LGsV%my&2%>}8>kxYvBaEt2rQ=bCYzbS@d$Dd~oX2UZ{A~GMk?#7BP zc!Kc!#L#Mn4C9A!5+SD;X-rx_(r#)U$I^qbND7yYl)v(w?t{<53HQ$ysa#NAEhL#W?Gn#t-h%^OFaMSwn@BDLOBCG&BBefOuNb}SI)>1cA8PmitO5Hp< zWRzW^M*OqG)lA(FX`+*bBaNpt zOgvy9;{s2FMjR(b8sF^NLz@?|(e=R(gjYoxN%i3I?>>xGaQq^!U$3s4F?@{on`e#p zsdJ3?l#_O1C{0~x>eQ+H#%G|>m8S9U;-rh&E<1Ae1Uhln1UkC6@#y-!?I+~;Z&vGT z8SmkmlGtE0Wh6sApR^yvtPE3V;>4N^isY$^z+^D^c}&LkqOl);9X5yRZymX4^sOT} zm4weX8@~S-Y&G)yDoT9mBMR19?Zn~0^ZFa!A(HnGALKJr*!~;7KdQ=85+_e2lAp*Y z}fxJG7YT-Mm4O+>A=%AZj*$RWsWnx+!0bCX~p^^Zx-4fsY`-Fy0xZd zjY&QO2q*O?pPD?8ONV6p!yi+hi(h|^oWmd0^#}UVptGKi6D{MfsiTMKnRUSN8j+<- zj5uCn=S1%c8c*zLJURmB!9;2q*I-Iv{=vfn*B=){>5LifS>K*xq2!${OFsNKRx55X&5=L7d3Ui^|&~`MvGqC|t;ePnS8y z!{tw*{0-NiCIx6uaJm_pliB2tFx|w&5Zw3l)5lX2xpK6)hxG#gtylMCl4`t=P2_Jv z&C)TV{e#XML+Ns*9Wtv+^-RdJA4i|gRDT|EWZX*!%^Lze=0hqZDTzp?KD76fZhV z@v1|Jx89n0hLhw|oXk4NiQ!pJ@<%yY_#~3gf86jUk`adpp5Rm;97np>VG5omeDiUf z{tg(5k=NkX(%r-ip1?AHz;Fa{f?kXsFdRjWv{Z+E&)y>_Gs5=W^QoiAPh^_VwV(}U zuhfiJuqpIcVi%hPa`&w`^-g4_A{$smB4Wr4DO@ztir!5vOk`$&i?ehN5*o6J{9BOI z6>9~q5Cojg@=p4$rMS4uEYf8cXtKMuQ)P80cgk@|~J|9tep1{*31_1Wfvxi*|eltRj8*|bDWq>(3PVu3a* z(Rfw|C-QAvU%1D-zKw7AI|ibXPQ`Rxg$p)eLp!)?oY<{i@h-px7F%l~zc8XdR&u(< zX4#bs?Q_bCcEiAW^KJ!kl42^)P}UZjGlz)@ZDuJmI?M&*S&Xw13zE51rfSnfV|W}U z@{1$&_k`=mg*)nR-CfT0FOIFBn5e%>t$%kJ%alwh6VZXnunv@o(P1LLJYw%l(S8Bh z8Y>nO<#DC4HrR5Vd^g2yU;I8fIlrFvK|-U+HA8j*%Q^m6ZuOc^`Rj9;I0`c zAxCB+e`Tb3fgzK+~l(&OV<7R`>W*bJv>^-T7 zLEAEdu$q!JOkLQOM+&FgoJ4sieVFvm8YW`aFm);0M(sZ)qrR|UH_WQfwk?5n3uo`131EXNW;t!>mXM+p z8t7(GxU*be3)h!etmpe>7-&m|IU^~)d?J@O%JRoD%sR!k9yJ{^C+RZO9N!+Uf=|(b zc_gd|FoQt%#6sL-KoX(T+#`Ax=&I$_80&MSf7#%pkCqG@q|G*{W;Scn1mBQ!YSjV5 zsvePt$pm_ANfX+&Hq0HfV#Dn?b7Gpt2G=udvz(W}ew!llu!O)cTGBL9-pKMvXA|HXq+?GwhkFN@3PAhB%xq~BrR;r9>#^FK3lpruNu2yH@$5&3Kk}6ZJ1w*tr-!o z7P~P}dRqlxjx3VRvmuA82`@}?(6Rf8=uh*F4pskSq_nF4<%Y2S*~4%OJ^8pYpO;5o z9i3v@KRNM-Y2>*3g%~CHo8H!f z@>z+twMf$SS;<-EtRx#IlUZ4~=Gfva8l@IZ5- zkxy+25GvDWCuf_FDhth4x|?Og&0MA6J6apMtf;L{)7mltv^MyrQjlPSpDKmg?4)Be z5*B93)(mPR23i7ffBC4X5c2S9#25kSZGjG2TMqKLZ;bT-CsLX>oWfo-=L9Bh`qLfzl!Xgn30raW-DmD>y2T%{{=K1KW)`lfoIaZp8 z6OPts!*&pAlD`^lO~jaY%;9GmuzG7l*rW|(pmDM9s~KCROx1kwfL7U^GDhl%{#Wcyk=*9c4u z%PveLec_BW4QF_zHPSiMd@Dv)gY$OA~a1#d=J(tXgOy|H(*s@(tL?LR$r;aH`!ZwKp2E2W%l6kl%&s^;spf>(pYi z;Qa)-G_8Eh$lf?ie9kY-uwhwIyuS%c(9#jTyrBMPBl?gZ(!u)JDp4Vw{|=sm4{ex# zD8k2_7PZh1bB$UpG}38QiQSY<Zy-_i4oUy5jmJ{9D8JAnhxyy}| zO)gLvC8s42Oz5CR-<)PLvIFDsN&=m;%;||~i8d=TN{4ZyS>_Y1v;gSVmYX<}RG`zX zP15DBHFY?Tt(u?4_0N_SVr797n0XQA3e9Qes0!75A_~tyVXQ_@+GuOj4F;pF9i4IN z6*WDkn}1AOpgopw%t-#L%*V61g}O{!WzoYcn*Fps(SbEzbR&ET0qdi{RD_+>wdYqz z&mia!h)(MmtySX)^x%xvlm*C6&iA8oe6->acv!=t&QFv3-(65ZztFJs8<5!r@6f9w zu?wdrHET9zuGj;naajPdvg~@qcv@*pH{d*$UAP6OvLt23MzdmEf@hny%OF#xE%<|C zEY}t|K%jw5R}^MAEy{vQnkbQmk|!HVvKSJ|@Nm;ql$3ynoQ6ab*~eV)xiq632_tP( z%r-33w4XaJ`=_V9rD!@w|Fk>^yQ!DEsZYDPX`HQaMKZa%(R@B3{Z%U-L49PeT{aYe zZSDo$1>=TogSk3s8$X!F!mE|S{{Pr2ktULNMVdILRgPs&WtXGuPdL$$f8gvOXt>Cq zG7)0^V?1KNIpC4~q^+peyGeoFtkBuEA|IQ`KPAg+_?bMa5bDaRwV_ye83?;06rF-ea3()TuJmus!dMhpNX`$9&I(B z!#}Vl!hMwNvP-SQq!Q*GUTo0XtfW&rIK$*H?6AY+KXa_Z7Mn|eB_-*_J z{X~9Jq&#+ye4un1iW*V04Mo+GzgN3Fk)JB%HG{E&EB&X@LHk^HV)Nt01Y&W8e%jI(-<;mYSkwUui8PG39yOtWoK4yUv z)cLBOuSbT4%me$(kjH%!xO7hLgPbWDak^^0_*Jnn~~KHT-eeM0yW$Hg2M zatzypp2xA^*vj!tj&nH9;5e1zB#uoSujKevj&I}m4vz2S`12f(a{MI6k8ylI$NM>c znB#j8^WY$ge(xcRuUsyPqu~sRi@;d9q$z0FEuAHoG6fA@dzPG;Y3lgi!RtX-zlr=i z@V+>FPaM8C4&M)qfjY-wJt)NE2ZVSD>3)Pe5QY(Y5n2!yBbX8X2QtSIo@h}8fuAbV5HLClOrbz;TpUHV zqtQhdM+_vjeqSk%5O7mzRxHyOsWRJn+JP8_EFAswR}i(0FiMqyYF$0*05mey4| zMmfeMLtOi+^dw&!$DbdE!|oZbFDZ_n5Qj02e1zpkulmwo=C-_K`8qZ)J(>j-w9lnu zlw(m_yxf;G^OBb=5BvtN2G(4&3O>QdsG8K$I!4DR$D%e-O($_&edc%^C$Ed+(<@1I zjB+e$;d^|Hs!4519KR(F=f~moad=uB=4V8xJ6wO3+D-&-zUps3Ua@gT>LWdPH*(=q z*B&lu-Z*{tVatPeha&)+3Ro4o}OVsQ%#_D~{xrEpINrGPb_A0 z!T_T|1U8Cc-AX5Kn1WZ*P&COHwnmR?~W}N1zA2^Zv3S6VCkm z@kR=@Q{A?mk`AudJ#X2j^*wW!ir0|UN~iLo8Q~hzs*My zw|3*4Yyz#lP24l6p8ImwwAW)NEglBGBLTeX-hnM7j062jz3gw=l?l|r|Iw83gCAr` z{!a*}5U{rvG&kxI%3uUqhe<=auGuW}gmJzWg%TT(s_XOmGPO5ZqSjJw$r2w#tcabK zPauBKl7;v?mRAw~k>h_cB|YupGzAN=3-Q$)f0W~|a6HQK&p7@I$Ch-GEaKRaPBnj! zNBXeq>LFEikQ#&g&fyr zw1IL3$3Bj)g^XDQGWLM}`3&wC$KPZ5pK$y;j{m~+w^?#}=Hg66T+Z=Uj<3w5vVP8g zjPsw%Bpn{lB%6eo@;t|fnf|NHlc?csrdYB_W_lJ;=4MenMI2XiyoTeAS!AotSs%$# z#AmYhV0#?CvSGi|q~iHsCdP7^*a$|d$Yr!#A}medt&j-UX+SF_!bKs_Dv7RSv|6GM zF{+U0vy3Vw`YNL;iJoLsEzyq|*(LfdqZ*0+#>gQN?LI8n|gJ53Aj2dJom zQJX{^jGPknF>04+n9&A_zQpJXhB|WLBWi*;QCrcS&Tj)(K1GxByuvk zLZV(qACzdAkxQc68Euy6Ym7Q2`W~Y#5*=aWmgskkx+MA=BacJ|EUgx?Riacz+a#LF zs9U0o8TCk1&FD&rE@yO=L|#U{5(OCbN%TcV{SrOOXh5Rp84XJGD@IpK^cO~6iT=gN zCs87nJ&W*5G?&qkL?w*2OSFQ~H4-@(?U1OI(N2jrF}hZwZbsKhG|1>f5?#mWdWk;5 zXqQAEXS7?QyBG~i^Z=t9BzlU`jS|u8ycQ9VXq?ea5=}6=S)!Q=Nq$(OMT|ZoQ3In} zB-+Yok3>5deN>`b8I4G^kI}6XeT&gviJoBeF^LW_`nW_#8Qmt)?-+eTqQ5cvq(o^( z()xCZE@gCwL=HxulBk){rzN_a(Pt#;W^|`SS2MaxqU#xbR-z9x`kX|cV)S{5?q>7_ ziSA?cMTs6_^d*VD$7r8KFEF}WqMtJQvP8dS6qM*RqkANxeS!r~c-57mlF?Ts>Spvc ziLPUGuS6eXbe}|DWb}23zQ*Vq676SnzeJBSdO)HOqi;&|BSznnXpGT*iT=vyL5cL( z!C1sY5~VTvwnVv%9+s$x(IXNqXY?J3)-ZZhA}6EAByuzQu0(^39+&7tjGmBaFQX?V zx|7lOB)W&u_a)lT=qZVwWHc(#4;Vcy(T^EDBhl-OLK6Ln(X$f$lhJb$8O>yu=Os#G zbU>onj1Edv$mj)$RxtX3MC%y+P@*nIha|d*(Tft@!{{Z6o@Mm1L?;*>mPn6{par+X zRX@vP^r}RqjD951I!3Qaw29G=CF*1J6N#>4^izp$VRS^II~n~k{3X+a}UrJ!USZCK}9iWNd(;j$;ueC zE`q3*%VN+K5k%#>W6)p>+7W|ph#;!-_6VX{z7#>kyDtVk89`~_y%IrYpw}aa%KbG4 z{WAucakFdEE|wUS6N6^Qp!qRqMFeG{z1j#$2I`6+;@ucQ#M>7^r04e|h$LT(Ad);8 zLBvbIEwo9kFHWgQnM9YzAaBZtqIjQ)L0^eMkH(+_F)bXAL8oHSTQTifa5HdHmyFbK z>sn|%3p`822Xj+N>yy$WS4I$BTeP!enAgX(oPy+JEriHsL)_jUB)W-f38OE>phsiS zD_mz-@@Pyge~jV%Bf?A96wKeGP1mg8cpb+Z=et32Yk>=}K%NyhcEG0MsY-<`8hY@ zg|v=&s^mtX1aYrKp9V6EgA)BX=XTuJe3Nf2r;CK?cLC{fAC_9!%qT~q?=mWsD02o$ zR!Vd;Bd0{C8Ffpv?IMz_%UA0>deIkvZjosEOhS)I4yDpZzf2O1;yjmiy!E zFNhTJ*aAj5d2{Xp>Q<2`m=glJQ=%*8kmN0SYPpZk`7xD~=v#As2Q)6x%X9t?lp}k4 zYEA<70Xdhb!HxQ%0sjwHEEX8&PhlM6-Z0#1UENa-dAnEqNc9cROyd z-y+ejd6#IigsDia<=J_6;f)OwKZHsbKblvmnIU#a^y_&wK;u&KZ}XZp7m3FtZvv7t z#nMaFTC#HQ!h6vsesq;C7Ub4|N57sRFIbh^teGX2O5Xb1%QUma4vDVH?a^4py%G)O zUZq6hL913e_s z>s)TbMXD}us3Q6@z(Wix@{*R?RamC!k3tc~N@@4|)5=VsH>o-cF!D~^AU7pF90H)`h? zDUP#aaQ9-Z(27qY)`@!%>&3SbYs5*8i5r{00&9d;co1vEx$^YdphnC^j5p-Z%3s0s zt%!BvO2m3GfY`wD8nGU}uN5xD8gVtppDsxdWGxHg-)g6GegWc>+GU9UtgYg>9`WC` z>p9-YaVN(;9AC}xPL6Njcn`;a=J-Lxuj5-nUoZKmHc5QDWCHm|OAI=VhUiJmwQzpA z=2^&0M?P6sqIsz#TQ?W^S-NGKpO)n5UJ=Ji7U-%#`Mb7WbE;&a?rHJYk}}=ZpuDc# ziFm2*F3#V_@zbce8Z!SXspGhb<2K!QH3_A2HBW2OOE>DC*32)xLU%Xh-MSYvOH1z( z4{BOVdvp(KI!a&HKB)Ou$sqFoD!B&n6{WincbDF%dqv|b{RragIsQoLUgSSgdI#d$ zNXnDQ09pq z;(9_%2{HHAB3IL59OL{L)5lmwr=hlV8Y-p38r)*cWlFBh6TM19W$jF{v!tD6+)Q!H zJW1Zbk^!a!m>XdEAm@Wj4>Bdhln_%wO!+mJ9b@_!Q^uI9!<8Cz(~@pFEonPfOZwz8 zC6~FmOt043VaaMO*|u6sHm}x_{j0Sr#G8o8!qr-`Kj;{vYAuaXwU)-ET1%r)t)&sM zb8U96+0LzO)+VCGEm}M|G*SFdqnqh&mc(@{^_{f}a6Z8F0L$#-vO%T{c8iH>ceBb!)t>6#jomASdh&1HHn%h;J>mwA$R zbKcD|ZsrC!ACP&fd7thgw6%|G4zhfZxj~j3<+etd8)8a`xgnN3&h+CfGscuLmKkFi zq32%cxfi&ZiXQ3N_hd|zT;|%DVwZWMZ|1UYrn{N$<{E~X9$ewiV|tJ&LFNXT z9^!n6=^>^ZXUQ?nk1>6WWrTsW)fmX@bOyG$fps>J{#NGBWo|BWbD5sYGL_7=bKcH$ zJIicldMB51GsVqZH%ksPH^BJ-(*rECkLf|q2bmjW?kLlr=GsEc4KX*w+~dssHFL+9 zJI35G=Hhn-)Gvj5q;T&P?ibT@nUc%gT&7nt-OhPCbM4IC%yc(X+{|?|eVFM1&Igzq zU~Z5pL7As^L(B~^CB)q0Ty~7}V@w}o8J&^!G_uY{(l(bVxiU}mN+b2l&N6o9+L`O- zyqoE6rUaN0ka;S*kIM#`5@g9B%ZxHT#Q6}@Lo9Qg>0?YEWBM4=g^6uzVm(c)vx#lX z^jxOoG9{N~Dw%F)ik&HTmf38g+3jYEn<;LV8D@HbDFLPgSY{v7gG>)HCCJ=SlU)lt zb3VlM5X&5A`WVy4m_EjIkwEgg1lBx(dy&BUGd-8{xlGSxnM$VHnPO+Io#~sI?&iFk zxo+kTGd;lc08;|Y-N*DGQ-Vwhvdk#cL!1vWH^kiIOdn(V7}Lj?F3haIne{i5<~lR= z!pihqrspyxm${Wpw{zakTsw0&Gu_Q}H&fiq9cFrf=>et$n7fbZL8b(m8)W(@(?gsO zF+IdG$C*CH^f9K4F;^tA{)w!4BHKTa`jX4}T&CwT#m*EvQ|wG}%a}^JnI2%7fXq`p zL8b(m5@h)hQ$kD$F=dSNV=~V=B(Xh{)I8~y%aq(CHBWRqbL~vAGuJI+l5sOPAY-a6 zz>-0h3CcXx6Jkn;B|}UflQD6}n5#=>`y{hI$!s4P6D60qcBa@_#?BPCj7i?j^Z-)= zGEej%Q-Vwhat$FFQ;Q*{kFm@c)5n;io5uP~V|}KvKAg{GdM;D!GA2nobKOjFvy7W5 z0U1*b0j39;5|nwOhd3YNvLWV<$(U*$W4bPdHA!KuQdl3(=gK^B?VPu>q@B5LrnqIE zWCENIFg?JMK^arcL8gb85@N{^Q^q(yCiARGD(Rq0Rr6FfH&u;UH>TTJ#xC>3b+e3{ z>29V6m=a)0fGI(y1ZAG>!;}!qgqS`iW2$qE={gJRV@(paA~%IC^FaqUd8v!tEr zZW$BT&D;QU156JvCCK?8(}PS2F(t&55L3oDKPL0kx-MOfS*vu`B%SiPGEZDPQ|wH! zv%FiztPj%zObM`LfGI)F2W6h>32{Eek|E}fF=b5VS(6ObBty-!K1|7FN^S;G>`bvU z#m*ErQ`|C7WdocKFg?JML8b(m5@bqxsF{Y0(MVHB%WKz4jOtuW?b7h{m zcBa^wVrO|b=iM?-WdocKuw;O_LCyzdp6Us)Oo%BV=8iFCj45MG!MA!zlPtDU7M057 zd@j>-nPTU>UFJzL!1(~^rKSMO2W3n(1VLY63b9Ox=^>_!$(Urun6AqvNnJL#p3SW@ zC6_6=OtH(DB<1?s-tlM;=rn#N06%Q@djy9Fs9?#WG_oqq~Sb{36mycM)-OWz2dq*UntK%#)0pW!y}0 zGdFwd4(=ri;S^egn6^gjI_ z{U`Ky>A$4^ivC{xH}&7vKd(Qee^q}(e^mb~{R#aW`akMFs?9dcGUOT-7>W#w49g7_ zh8n|8!?58d!yVc^hT9CEGJMH!kKt>E9oqX1-!VL42pL{9ykhu?;g^P!hPMn82EF3O zkK1z;tCFwWB?^?qN`ai#tG{FYZKqv8aRFULq08!+H=B&mn$EyeM8q zd>HX7h<_wr6|W)wG2+)Tn|>!~=7^Pz16@PCp4DQb$JaE_*tv6yM{IYyI{o+!)RrN? z$0w@XZjaCB+&SnGE=Pym(c-LcZgSPsx3x64)l*)$+UjduO;wE!S9_a7xT@?8uKK3h z=GMk47PU82wY7oVUQ_RMIW{<&oG#}^e9za_=CHT7);l-4>Kj`et!>Rss(b@v8idQ) zyw1@iCDptG992XuuTrOIs-AQGo zdJWBM>g`nxu9ntjyQ8hGxz*L`XyDe`>groW6y08BuXBXEu(8eQXmqtSU*>3awK>s- zaMd_A)Z5Wk6s^9oYK;RH=y0`dY^-i>P)noR&8<$Cs>)O(wkh|u)ic=JiE*$GckM?Tx~<#^H3;);BmD9jdw62{8j|>ziuM zL2GkVwc6`k%`FgXbE4A5*rKps3+iuGrtQR@TvkDeR)QgsZj1?y7S-TVRr!`c}*wcmhUn zjYANps-^~}YIE741N>Yy5HZfO8@k5@+BP=X)wMwQJGVJ@_&xnyo-T*iJK$~U#9z^( z<;F*>)s|& zL31lD8jUb`mDD9nt8QX?ttfQ@%sN7Cu$Xgw2;0!c=SY+WVO_W9ZHLi$A<2p<(A~&wXBx<)y z4_M>eNJKg5+Z>K{1RLO&tSjl~w z)Hk7aoM|UvW7`@+j%KVBRqf6?8g;p>*{fQrs_PqIQ3pEeY9z;(NsoW4YhcTjJzc%7 zVjPId7gMg}J<63*n>AR&-~tT|7%nbp)*xTdo^!E((hv#uy_mID9;2IUXs#=`t zh&k(O!acD!*EiMkj6#KNY>+l*P0R$eH(yqTy+*|J*sR#AT5H(g{!nYc!dZz33el@kVWkc&Dcb!)nMAzM5<_S!N`O;4R9iI01~7WvsxWJ zR7U4e9#Z5nWYy~VgCyH(Ro_LH8eb>TCG-i2TOF8oFB!e1O2KzMC?WM%K7Mj)w7sj%sUOFj(=KAWIHBlJr8@2`NDVl}b+M^J!`06sm zRq?vi6v6HjjJAi}PY*XMg85k2hA$^9W6j!Fhzr$WZOA z4VO1J@f<)FTjLh&p|Lbe-v}4Ke4yWRUM1oLpn$9y3$19W$8@jfWdtX}4OI>8+#p!& zr>-{aNTSaJz_jE{o;0!bz}Z%vY1o>#)OmUbJzmi~m}LMvH>T` z)`4pf!-qS)*jEs2^Y{gou6K5B>Gi1D+JW9K)a2q%M8F=@E>8TS9^aJkboPn*D!;$e z-7V_d`>*Q9G6#m|>LF}ddOCZhh^vjJ&W6t3Az3Fuv`7g8n(C|adOM*6wqvv~R9D&8 zp+g($TX8M6a;U$*v(MAD(2pI|!lBi11m9}m>h0>;?&3WZT@f@o;EwjoXz=LdPjzg0?Ec|`O}HH8 z(ZsaC&h)aglq+7pxUr?WqvLYn?-OvcZM4@Gv{-x2lC7$2SzJY;@jYZl9T+Z`r=NT2 z!t&_#4-Ha^nw;LAYJ4Y#hHcXGs?Ms%UL#Ev-++A`Ghp|4PEA#qQ{{K;=%EXMs|5bQ zYG<#fr+@1J+V>8*{eu2ZuX?{D`c_5@HWb*?wTV8Td%)Y-%w|-UDSBC3~j4NL-qYFHPx8n>b(<4`rMx0-p+o{z>u%H$M2hD zscr!G;W;x&m+iC;VM*xo6xj#*277uv-ZqbSdk?Pvg`8uLE zB1Mxj7*M(XlS2*k3%Yzk{k=V%{r<@cKtjKIu+B`<;D$t~bA!h_ zr82Fat-T(#&9JB)?mgsVdON#3eVyK`CR-1)>;r>4y*=Byqm&J^;ImyA;i<~> z4R-eLoQl!EwP)Lqm*>^l>>7{H?d=&PJDtsR_V}Z%6ILQ3=vy;T=ka>PxfpGYf-hDF z`nR|FyWpk05p3`BxO+wOmMdW|QSYlB*x~6Cuy>2!EBKtidoQ@8#|i%s4Lv^p=8~{? z+6Q{2oqa`XJpFW!h{~3git3%1e>EQXH%fLj;S3Q`7Oh}e@%b^`>9a@GLp^*7lSA&L z<)+@(FwnnEwDDxmrCKId52(`ew-Y@kXPo(bG5J-Kk1ZGjt|&^t%VT z(4IPZ!li0@I=A%?`20O?A2i?I+1u0Aj8iiYl4FP4!vi8Ug<7Y z*eh&Yn(u7gdfx_|)cu%AVzL&Vwb%x=`8|WqZtuX*w(iL;wR$iuw)FI3w?vDsw=>$g z;-&+e&x@5BcQAHfim8(eHpSpTp`F4GvpBZn6j9~f=EM5x!T-Tducy)D?;hxyY?Ni{ zI{UjY<3()`hF;$Gn8N03?5d!^T?Jf6$y0?~H`JXAnGhR4tb*zPoM zRflHMD2<(7Uw0=KIqc&7174(bdssFlYgg5lH1Dxh&U1c^D}cp=ZgHb2+M2!Rc4RR+<6lUz z4Q_WYHsSBJoiX_C3IukE>jl69RvoH%3;-+O~7 zrjEsXFVf`kbYakXXb0SLEl>0dEZpAT^KTZ9H0u!+RmD5DlynxCdzLINs;F?e92Jw? zu1fom7i){$kX4@BMJllmSzlULRav>Qk@iSaR2!wP=Y6fX-WN0a7pODtET2c|C|hjs z)4cRuVD*=k^KP;dF2$S6%F@dB*q-W8|JRzEbo>9CO-5Gm_p#A)dudVJ^+VC*@XFCW z-xNG|Vd;O7&is3|y!#4rZVe_!@84@1<^MzNqo=p`LX>b#4#I^Li*E1VQr#6@L(B^D z@2c@{SE6oW+WUJ4I=h5#V94wCh)(Y|JniiF`z}Nqd#|Une`rwj^kWk|xw-kbW`rnm zQ=0>@_gD) zUSt=!x_P_$UZrU->QeX1bU}^{KJIdzXIP?J;<9wp?Ly?&T%bIz`_y{{@2wHqZ_2F; zw%G5j4EFT6AbyX+t+;gB?s@O>4%+d*$GYiG3GYyrF6!!Xmo6$Pa=EtQTeh9OF0%DG zSVNeeXESjPJK#QF=`PRNB6!Wj107u5>iyTPL;Y^tJQ`$LFD{;3zMgA6M8WN1$l)2W zD++G$Z0qSK0?X5N9z9bKt{#ktthi6O)S@orYEeC3nuVJMElRd?aM0DI-f(kKKCaeq zJ;aNMsp|Jd)2K!aK_3(w+{!8AJu+TjA6w=2eSDpPJ7*t7`^m+^XUKxc-f~dF*nNBV&@# z{T2_VQV*{XF5G8|!79JY)jx#0Q7%_4Uc&IGeo))f3xz~Ip7!(O4*86Ov3ku+=jTa2 zw)l8n;i{~3wYa<6cJ{d{i;FAU2YUyu-Pzi^bsO$c4YtdaiT&4J<@IeJxN3V(`!(Bl zZuPf!Z@cE&A$N1{&Z{eBt++bJ-R{_{DVJ-9+toMdx>i&~o9V(YsbZ^*tt^kGGhdl{ zym=S6H*Z-?mw;8V)kEtZ*LJ_FQ$$~1MsGVWu$8GUtYVuyS3~bh-~Qu^&Ujs8FJj*p z9iuPpRj=ucv;X^cjTzsYi1*;0D?RslU;0x&S?dKlOI@5dM!UxQqS{oZ#srPh`2D+m zaBf@6HvTty#FIC+N0Zl_7dRRhJay&$xc8-BQ9}~dftYhg<+=B>m6fHqVI(SeyNTOa z7g{c=bvgGgv<5qEB`T|Wd)13Z-}#j#$CuVqPg#{}vpB(@w_tI7wWz?^9JkCbyj*wq zZs-M=r#S2s@?k06CyS`A-fF&Z)i1o9v=tuc^=$3&crT<$^!nd&sHuB?mZQ{q2m0*v z{^A}?^%i=n7%7`pQubzK)*1GJsIq&jyYRYtA4kC)r18Ye3Ni!T@} zC$HAurElwtVKn%)3lHtEh3ABCcQ zX45!h<3)*-ihVVKxlwh5xqPV`Dbv;4OD|-EYv#Kbc(DTaB-*e8riZd(Kz)ZuKEUnr zi`K}}!MkM1kJ>lm4n>Wp*Mmz1ET-O_^)&{@?~gh z!8zc-B_^(#T3Mda*;n zQ&qVXqY-s&<$7bDfY38cdVm@ArA`hS~x~3y_oVb673p!lXg|qejZZE$t zBk(+0=5RTN`$*W~)B6ahH-c%l%ctK?yj{VM!MTOHHGHFj8w%%JJuxgkH{p3Nu6|%+ zdNxV5$;)ceO+KRpGkj|xY?+u#=(9>l0?I`$BV|F~Io=^Fg69a)*Dm@+r`UqOI^@Bx zlKf%-@zr7o$SZatzZDcO(t7-T-75UOlX?U%XoF1aM+uVLiaOlLEeExm+MT+WRjAL;z3CQx(2ROWy}!Vo;-hs_wYe>(uT|)k6IQk3*OxB*Jto3c z$W^1grVH=of~j?gW|+D6M+K1=^$ieAaNIZnZwu z+GKy#Bj06Qlf&LsO5U~83Ev|xwu=J%vts-Ppz)COZSv6`&Ub;QdU`J;Iw50aIWPGA zu#i=3XCDa93ZnLa(gWFE#MdGvL|PZ&_i|$RzW=1@YoNBOn3XH0DbeWr$Mi073rME$P0LG?{`GEUS-pA#)Fn_8x z$y`JyBTn6RbgS>@u+UOPR#A07TerAjxvm9$@ZtxPgNO%sf%0)L|Mz>Xx$Zyl2y)s< zXN=eWUHiTJ{cHPdFH*<;{L|s~_fG*YhHx8(oSf1tho9!%`H1~@ow+t2|?$?3v~91f4}FvlC-s=&8-O3Z_<$_DXovBF-_}u zO}DWmIlj6wlQlXaYsD%>lmYxmxPhJjswqmJ?Ml>RA+kU7sdC%Kk~MoD_{c-{#MSt5 z^rP2q+AzKR_@0bYf8Nvc{W~}50=lo}yz=%-Ya4%e{VN$?yM5amgO~oMdPuBkUU2j5 z-DN#TznS5@=$=pB+5M98#H$ToJF|aY=eH|PzMAoitABROk3agC56}3?TQirXet+@f zPyG2aru`MJ-IgDlmuJkkJoeYqMcYT8?0jM8Iq^DH??(ObJNV!`3$^B)~H5 znrSer%EBkMhyaZLCYDYceueDUuDJ-qAjb?<5|8Spy3lJ&;7LV+EpHsxDkjbaK4icr z4TVOpSOT|b6|ElZ1OlJeD=8@^t&*T9s!f#?7P{4-%o%==MQ$@v))KfQfl~ZOOXLMt zSUb}^hkgz2phf=4AV$~|qC3&owE~`Eh(_#WVLZHQfDKk=&6?2e_rNBoO zb+|aia2gcUWiluzq1P&A%G`K{yhWrL4a6dbnTQ}U_f0O6!1>cUCB>jsrsE2(Kz-6; z5E6{&5Y2k6k~7_yq^_KV6KK7{EZ`&Gh-DJ!oDqwXF-!)d&Sc8rm4s{thKcAo23l;f zp7Aouz+}R5!b@;CqoIxr|HDMf5Us4KMtt>_bFjs~z)4g-?c@Zerq#6DKbwZW<`FtV70jySSPvG(&Cb0d;>%y z3?=xp#FyZsCK~>xhekNH$uX}?Yi3SzQroWT8C37gs=uAppmWuvGxf5HGx%HbSaRe? zLlkrieY#;uk#_i|xL2*Ce;-m5e*YTxZ{vSgQfLkTI;PMnf9A1@{+2TS676qDyiE7W^d6bsE7SXBx?iRb%k(js zJ}J{tnLaDigEBoN)59`-O{Pa=dQ_&zWqLxU<1#%Z(>G;$TBc`Y`nF8*c^w{4y-ZCq zO_FJv=>X5n-!t_IN za*xbV<-+{OqWBADiBvnn_;Zs@Zasj%WnL-7JyEpR=@Vn19gm{D3EE1~TAl|_9_9Gt z*!`9G`dJjM1+;rWo9eKlj>pm7OGx)4+<`ER(2LN5uo%IN@IR0_j_?e^JqUDIAWEqp zcoTvXp%!5!LJoq0&z_#J_y=jMk;T@8s&*vQ7L#0 zwd!kw9Xk1NNi?=?u(vKNu2FA)-;2KSPq^eequz2n`swS#BbwbBm)q+{Pw_L#ZTMY! zH-4>xFXCx&!$17BIvXVEJ%Eeb9>+&cxTFsPb7T$jww%J%Q4%@2Y&^$1C`nUQLgWeixxu(a^KS zi{FXUJ6S%lQ17JkDV{swcVGNVBO&fPyMD1+-`Ao%guH^{f_gw4S3-U*jMzJ4b@fRW($#l#mdwr9Tt zCIlXop5s-s^FFuRSk=+8SUxK)#^X|a4UV3xpXV*Pcdd?IT8=z`iM+Q=mFr~PQ@nfk zo@$MI6&f{aMa6mE%zICjM*p}kqAgiMLpH^W2yu^xC*L%Dx9agbBmMi^2~6#?fl1z*)vE=E{@a0x;ILLovC!leks2qg%m z2;~U)!*|MJgk=aT5LO}B5EdeoA>bQ@3ci@BEJwhXLKWO`R4NcE5vmcY5bOvw2o408 z<^Q(_#u$f=FP31VVc4F&&N_@S5}T1C;X{?vl7HYis~9FaeVN zR;_pxTE-kS)rMmz?*U-FQ0FPhYH(h(TJh*Z;4i^qrO=4fR29*>q7^MwD?8=qKdd|Y zdi#B=<_&rKm;2n^_=<;bVPE)TDGRaJU*75KE81Q%&x##+&sO|AB77%l9`1k5Tb*pS zT36!NS3W;|OXWS*R;HFi$?y+DxE?Exm0tR`68#9H#oMzTZ$fSJ_#(_`cI2xK4W8|u zUTZJKtLAm$w_W&Ig2y}0I@F_n1$WiFt)0C-&%D(uFOAe4TR2jGl*C!Bue>xy*Oiw> zI<4BE%R{es(WfJ1bt}UZfB2IklkJ49UylNQe6GSuS8l83;TJq*rSq(G@wRGS)F*4~ z%ZiKmTEX7xoM+vxez9fMyk)qPS6WhBT3WPpo^?>YOd0T2dEMRk-Ibd@)v{{dj-`vi zi@misuVkxx>6WrB%Q{OuB}+YJTgW!?DusJ->D1j=8KHBBC(EyHX~CyO@v*dy4w-qs zFirlY@ZXu`3(A+3SCy|RZ!GUCzqWi|`Mu@)%bzMgQ2w{_f0kPp*%qx@RJ&*$ZeDgT z+P>%`i}o(MebMI@J-X-F9zanwP>=orJR;*}R(Xrx#E4o%( zxngj|_7&YL`&RB=dFM+1s%uvbuex{Dw^xm>I=Jemt4^&tvr4}@V|B-B_v-%DdslyU z_4BKLxccbo*H@3P{^RP?tF;v~E9O<$DvBz~E0$MORn%29S8S-bqN1zfstRAlbrpe% zk5}AT@r8wMt-trygyUK4W|7iJb<)1G9eEF9# zp5H8gxcu?*(emfZ50$@Kex&?Z`HAuy7kzTkm!Z`&i(XyyIyTI-;h{a>YsI%NxoycE lOYU59bjfjSlxfq3{ku3`K3;yR+_WeU9s&5@qZCa3e45i9J}ON%4-Hn2ngwZ=$nK#->2g77)u{b*ifY7Fzh);7gI6ik2> zthY|eXVxVk6RPEq@>?AwwCOrG#ix2c;|G43W}RD(jBM0K#}ui~Wqjp$1nOMpsT5zE z5+^QCZCjg{b!C&>V(7pRCNRqwhA96<>&+VI<~+{tiM>uosnnB54m}o&zahfVzF3+S zr-lUAMI6)YK`hN(PNs$^_h#dGgd@)+_4kr2H5t&F(o?s{RAM&7NE5LhBTbj7p?u-_ zyb)C(ORzMO$!3mbj}9NBz#1LWRVFxim1mC$EDK)MNCgM-lRB9H!sTUpR>n?n= zvkuM6!8nZ^>G!xv`m3h94B=lja-7kaBUFAn&`V9ny7V}uB)uo7S;BtIm{j0S*A$Tk zs*zMgAEmmMuJzZkhcm7>Bz&l)8*R2*T6z=1#ttICiKH_|AEo6;DjMQN^7@2ZSw|YX zN%vqt(?@kSU7CM_G|$5-)~%4twn8#8DIX?YXohvok#=K}t09^%HC@#djCB~tFvfEn zV?^LR3~DY;DaO@K;Rq5dG_| zIA^QNG%9C)7;Q3UQ47kR@7N_2t^}c~VY>8+Du<}5uvkzISyeeJ`e3snQw}{JqZ>hE zmx{%_RldaIdCFE!1sjbR_X=K3g$uM|$#ND|6f$#e(GBgI%AD|Ob=y&XLHSE|Sp{e) ztkCw{bIP%nH5VKYc>zj`p+YoKU^JC%#}2Qwtg;M|3+10yuJSDw)3T3_xy9lstK{2d zF-$TwuQH7Ls*hlFL;7Q-Vlj*3Wl4+|#MC?SQt8@I_s3sP+XyY0NJ8-sM2N%tY^`B;^Wk3irp>d{0}J;t9_mcbrMf zb{oe+DSeCtv33wF2t!vBYOKrL9j=#!8fDPGL<>2qLcM&+z?W6> znV_Yr(I;4G9anTlRV)wV|JB`_Al>h($ diff --git a/Mono.Cecil/Test/Resources/assemblies/decsec-att.dll b/Mono.Cecil/Test/Resources/assemblies/decsec-att.dll deleted file mode 100644 index e9ac355408f5423bfea500f79051791f4d204aed..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4096 zcmeHKPiz!b82`<7w^^#KfXbg3aGIh)QZ_5J6cW&-e<(;xE4!^mjdXVQu^pM6X=Y}z zRikU7Mh+$%jF=dE;^4s;4oxH^CMJ5tvnNBmdhkXJ2kY;9v(u%}D4HHH;oH9N|NGwe zeecb@>G&%b(FP#RvAhgiB^4-W{P(CqbJvsCy0En2diPah?0R=;)(OqIz^?{Y&9p7g z^CPpY%%JX>j%N-}6wR7nQMt~}j$O^rlOw>G(S|R7x^yyG?FLfa4;fj2e`t@j-#krf zauhfOnIx$=Z*n?+p=fYWFVKdV*rymFB#rDJC<(!>bhcD422j ziFcOr@kAiaMQT1GU6T4t4ypBy^{Jl81z}**q;o5fk&Wu$xD5(yNG?#WPe+~W42=@2 zi{myZ0E4%Qn!PA}B}i^5WH4(2e`Ekdl>Y%bw(i-P+RY?8_H=ApVYzVeg+ZekRdPJP zFPG2t=Lhx;$RZiI#D}?P&%3}^q-o)cQQ&yhP&~e7J<_6{sUnuhb63$bI(1^0^he5l zJj6YNu3x4sK$S6C0yc8FpF)GI@p8`E|iMn7#eyhwaO#J;=FpABL zGm33^hPaEh2+rYATqAx0Kj-!3gd6G?gX(m7eW*+eq^?>_EDKJK!c|sXGA! zy$Q=r822l6S3QS{vO{I>wW26jab1i#<-iISP^^~|wieoc;5ua#7s5!@Fj0O(*%6NU zK5};C2N<-1rY%=gc0F*Sh1{eHYEBqBz84}s0kueq=lt~pWMXev7{b7@&ywdzK+nVJm#l6mL*%c-%; zx!-OzZe|ye{r0WbrnmRqxWL1frIV2{4P#ShnmF6|B4;!{h&!=nwJXXss_iwCUiO;P zDv<6Rkq3moUUR7KM)g1)@l-tuEVtL3te0KKKB*Q;{yF6xDGv--{dWI>XAkY~Q~863 zHXEf>=ag5oJgcfILww;HSwlZOz)m@rGH0E*c*v8^HXO0Kh zIqTT^2{b-#-Y@b%EedZ6cQ+*W5O8M54~AWL+;TkVr$QB&U#h4z>!q@g)`Xi}Ct3_={yM>5;KBXA0q?dSk z8_X%9mqUGZjYt=@Paesy4`uS;ZJFZSWaVM59>Ugf=2op^(l^f+Z_9U@z5%^kx#W41 zw+2waBlMSQBJJxjcbEOL_#L7cuR?4yg5bTnu80vT^pP(pV7Ja~jP|OYImD{xu%NT6 zVwO>%AHm~#or$JiIw0#LHHma@>-FjSCK<JANyZ%^Lxh}FGt!v+RP|K@A<{)3AQni zO*@|jnuV|sQYl((orI#uBahOGr$Mzc4h%+`HlhW`(1@$Jq3AEGTI|rc;yGdss;{8~ z(-BsO-*sX8q_b0v{i(3q=`6!a!(V&G&@G&|aaoNuLuMRPbrR1am1yGH^NAMLA2v3# zw(1kK<~UED)b)%;)|(Wu2fB!fT``D`3RL(wb`JBocP%qOrd$lHJd$SM`B<^cqGg`m z$U7LF^;Sxbb+(G8LT<*+`G#Lcrj(1jQ=W%0!^fqP8`ybk+{+h?z|Pr@9hA=n+`n8Y zu%d;M5mQpQY{&95mcMSBmfB!Zuug~8^zDtSOD_y>XJa=-#v|s`3pn&!7*OS2U5nK>3mtl+@AQo8y3d)j5vnBtDcpBG1hhy~^~0 zLCgwOQhE!|Ub*{uPBL@WFvD4^ob4!y1%=~pAfM!QvPyvx!z@?$be0obDYi}Qku~F-Ii-9R%h~Ux z2mN$G={+CWV@G<&^TmqLV~^HfblUY(7!5K@GCQA#F4j=2c#1)f{`DY%eF#sT2mS%T C7c;Qq*U3o%5m=se0}yxP4|L^GKPkVuVtne=YV-Fhhq~zE_A$YAU8Uw<$>oY$)(a?k8{>JsvLrJ zPSi=<0-YH*$Yjs-q52JQF!_5lXRJI#n5EroDcKuW(=d7~caZ7;Gw4E|{Dm$D7_nN5 z$=@9$qHb%ha#d7hba+e$_Gr-!VX)UuV+qzmYD#ql*$&-nX18_Ny&}r!_;1=g!$d_ty==jT# zEYWFI>RDQtqV^Y76K98PnhyxZ?WOP&MS zoaTHzi*f*E6scRnW$HT>ksLI7Z&6Z6Xbp$(WybYkQ74ISM=m6~4-)R@>UZ2S4IgdO z*{Ke<6J3Ejpy7oC8yLi`y!gJzx9x8IGq8&)e;Fzh%8 zGaI;KeX8sj4P{5luDr44xkkfv;YD^3x{if;#|q7`jatj)2dcJ)8fn5^0mjCmM>sMc%-1wd+RsQBHQ&@yT2oDY-{u~7GQKKw|4x7DX zCh{{FqqI#rrp|+rtg*RwA)kqsN6{H#pXIMc+IwogQE-MzvTZv5@?@`-E zonAg8<#WA-xA-%0ioQ?bP1faYOkk4QahxW-Q~ji}=V;l)GGmvjF43k(-cMu-4aOG` zE9y>k>wThUz0;jf_vGftes?^2C!XH!kbaQ9ly_I&R-3bQh4hL@TD$LzvHi|?7CK}5 zxl!YJckvXjKw2<%qlXb-rx$@O>hp&ZZ^K#(N zt=Xy>JAq$c34_lg4Q_UamJ7@eLhC~PA3AsK?V68gf^gP#7fgp=K)E$3mE53Y)#g#? Y)$Pmon$y$&Eq;4vuMO|pdm1Y6AFNgto&W#< diff --git a/Mono.Cecil/Test/Resources/assemblies/delay-signed.dll b/Mono.Cecil/Test/Resources/assemblies/delay-signed.dll deleted file mode 100644 index 3571ccfd4bf14322385363d56c2d96863c1a1902..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3584 zcmeHJU2GIp6#izrZAyU#l@tg`JJ4bf?WVLPN+PoT#bW=`Efuv|_GjD$(FYJ#bI+kj532NHPgC~q^=~v7D6$mb>J6{)xMM;v16hK4+{)J=i5Bw5 z$%XtFKZ_MuOG`0r8ot!U`vSJA@l#40U%d_G^xc4MxDji}%ZWvJ1WR#({3d*ia2~TH zv#-LdRoGe)Gv&g4wXaAJnD-%J`Vd_&wb?Q9>{7*##D$>T;O zMmz(-KnbHOVOpj)Hs_rWOHdc-3j4nF^!VvZ15M+PO+0(?<=k5+eeco1fi;b1pXP38 z4AR27rj_Q8fd?R*2aa-BiR=vZzF5;{sfZN%vm;fPKONfHcciSg{`G@z-~P(?Z6&p< zX3m7Sbiee(;pd%;$@uiI`2z>Po$QUflHQJ$y@%dho8OMA$)j)F*XSk(KYF+2s}uD&fAXijmF`1>+Em3e zr%s={WzD6UW2IVf+$#l5f2iVKC!XuJvu&eEBPTWMA9n0VT-nJB)noycGY#kk?J6n0 zSsH4womR{0ikn$~FAYO&uLNA#06jVzx!C!yS3pyD-0DAF_5S@+cMZE#M7|xnqrjjX zpMVBKjqD8|h9UAc^s(2$FKsvV4)S*YtBViAKmT613H}99vF?7JVu$cr>`;7iz=oLg{Kh- z_JP}oNSlps%*Ybv(Uuu>*{C7(Iujj<@n$<9CR+x2Cf3RBV>mE!HcJ z40RwyF8Pe1R?U+pc7xUko5e?Hqr%rods>ZdVdgoG5QJ$A6C>2s(5cqy3G7k@S*uV{ z(XM~ZMwMqT=dy`pg!S;aLkqK=%Tsa&?oeZzn1{>A46ADqrT(|$B*#Vihbo}^e-m{% Ku8Z`)tH2*VMnt** diff --git a/Mono.Cecil/Test/Resources/assemblies/empty-decsec-att.dll b/Mono.Cecil/Test/Resources/assemblies/empty-decsec-att.dll deleted file mode 100644 index 2dcd9418ba0585ee059055dd45f804ffd8251ed0..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3584 zcmeHJ-ES0C6#vb33+-yFrIA2PU@901l*zWV77WO?-3n-1D!VPjXv*yLx=fs%S!ZT} z@}M=M27Tcl@SVg5nxK)GXiQ9eFp~J7@s&Tok0)cI3HUpAXLq}$F@Z6yD~v)%ILR%S%xfLj#W^cfUO+{i>sboL*Sf@Wzyzgj zaGUiDNNy=~A~t~$#xg|s0MMUJp@(*~??b9%59dr~A2#i!Y)5Jjv&!t9D7-jfBoQRV z^TSrw8qJOkk4eBZ&JpKmxa%$88t1D*7vj+M%aLdtiA4bCal*n;-CRnO@>UnUsz4;Tx z<*J%ma^oOGQAKfk5VWngd$#f_a?5_3ia097%bvn96}K22gz8S{RvBnA@bycV_?rwW z)xcMN%#0LkN>(jLa>}bxtz5QCo*Iw2@k+H=H7j)OvL8gT>qLnf>lGgn#HH)m(x+3( zvoC5Yy2rz*njgCrW!2SHSWw}4*P(r~Aaa_PTu<8GjF0QDednJ3sC)eV-qrBkKet># z*Xq&5xBGs|JlFO4rB@fWkKDeJ-fZ-BZ!(Ft^sIbn87r5QY8wr<=2Td5qlhU+Rzuj5 zHKPrhjVCy0E~rrSkH~Av-=H~J^Ws{lj`*q;hqgCp&ecku>%63vi@_VpKT;YSvqzoL zXNL|Q7*W}ShYWO>Fgi`c=zF5ez-Il1q{()Xs~=`NTKXoU364c`dB;{ z1{Wd&KP2arY|Gz-Hifzu8s}MSWpOeH^PV?jyMBFFDy28EXxx1oX0E0Bzo!g+u5JTX z+FMaS1G5{*MNjUIGdUn$bFjpz5lR<$w=NP-;S{M8ILS+Xk@GBGAT97^`u98a(^j)h zbTpyToY%P3(mb(2uQo#Zap6JHr;pbW==I(DvMh4drZnQZjhK1?xjL+-f8-uCm{UwG zm-6xko>sL^7LDHsN~D27W@I$=^Nb$B(SE9JaZKuFxxZVw3)Bs%-O44)Q@k~RIejlk zHL=$9nY+h+*{G1`kxc7hTI^@;id;>{jj@bza*Zl2EYZrN{vMs{GMt6mKu=pdo{yF*$m{U#XxV{Um`lT1V-?hy+D~*_Ug6#vY)yRDl_OQ4X4zPbvwhhft~gph4rDbsa@T~oT~xbsz~W@na}*;paO zLw`WmE*-mcivsBqbnD4}ExY`A(|)O6c+e6c2l+q8vgi(W(3`?(Wo3wDiI>FsG<^_4+wkA$>uQa#2Z!O{t-8K0{g%=ZRSeQWWF9nc5nw1fm)` z7r8G5|6e+STtu`#2$VzfbeRXbPLG`J6#$*!h?0cw9w9*UWy>dA<;$m7aDb?9LIDY2 zRdc1~)S@2pf+=iXGr@kszfw1+~NTKjFMF!wBZITy!;DB++J z=v&T$eeH$VC$k`*itABc-w5rNx<(>BLR+W)gtOb*lp7mf-(fYu+Z`mxOk@udRG*;b zQK;N2D8VVhyL&vU<+Pi*@zHVKG!Bd8K5=Fn*reL0Y*&2Ov^P95@r``^{4$Fbd?%Zx z2$?&JGey!d+C(reSk4-0CUPlDaWzTD1AZuD=ne0X{J|rmC5|33`xqZ*;6~JK0%@e^ zz6MD$aTZJZkvU6toa`8N#?tq7@;F;vIM!p?<36p;NFD$u6)j zjVv**a+02$a248~TP4S6T5=MVEzg&A+}Ew9tZp?Vin3-J5>t-tIhMqdYx;7|v?bOX zzPsW}&(~y2qVClk*D}{o(jQ5#@l40YZNn&2>WtlJ`k0p+x-U`jb=ODPtC^O?xJpX| zZFGo06+e9ZnwhB2z86w|`0~YPsOcmPM?aKgG8PFXNoQA7o)Zj3v(LqoYzwwdQu`eV tBP&ymJKd5c-L%8rrPK_I=ZU_c!w~tvIyXXu@5jQ}x#{?SqyO**egd>jjL!f7 diff --git a/Mono.Cecil/Test/Resources/assemblies/gifaceref.exe b/Mono.Cecil/Test/Resources/assemblies/gifaceref.exe deleted file mode 100644 index c8e2ed12315baaa9bf645032bb2d111de1cba5f5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5120 zcmeHK-ESOM6+d%#v%6k9CUN3?l+cXVi7<9EUdNV5!`fLp>!b^|hgQG~eIWeKomubN zxJmj7x$ArGIrpBA-#K???)ChQS1CqBarB1|iQd4-EwAXK$u^dIPyecy?smO1@P;<` z&cO1zerGZ?r{4T0$Bd2}W^1`*;0r||Pg+vu3*7Nh+4i4Lj1_85tw3Vrl>A{97K z^d1*sZ@WpHBC^^jWxQ+*~PGSfF6Uq-FJsY|jrkSNL&uFSjVa+!tjI1%99UprhhOo3jzlQ_| zzf1HH#-ngQxD_`Z53Vdx4|v8tcy*;%z<3JsYb?*$ZW$vtxX@lY{(5&8 z82b3^I2{Z3h;hQT>c~VP0&ayriII6Epi0lCaIJWrYjuA3nCI0IIs-aS=RqC%D(G#+ z|3vX0(+8M&Mq~P-#+ttqzZ41jyq7ILo|s+mbkBJ z6QI3f0v-yYK>yU){Lk9UsEI~L2Uz-p_Bx$_^qi7@Oz+a?AdM>N2PfXA0Z5B_sQGm* z3+d;f)a7emg!E>#_Ljz)zm257De3J<^Q6dQ?T<=gpJyR)je3OuGC>DX<1~6d`T(7z zmw{-ESnqkz0r~=QEnhFDlxlsHv!d%G@G@K8re6@LQp` z@I6|g2a4(%^La%V=>~m+%6PJ33fY3-clH%A2W$z<3F<;U1)k~{em!_&7;hJ7ufl$a zJ_EiFk2JqA@ogCIY8Q}h=Lb*&CT{E*EjRC0o3@;yK>C3pHzh5G-+8M071y(^GA(WS zfvnTD@;7BAh$Q2(YugYl*YS<3(vhB3q2jF5tV_=<+w$hvK8l?RJAB}JP`)aI$QW|x z+CFZKjyQ_HEL(a@(%Y~q(x-637ks+&LschL+u+?7WYEf=i@TqF4l%-<9@*A$tHK2KSLoV=nkefPRDpi`EC!I$X za3?X~&qer)PB4Cc%BabpbUAX+$wyk9yV0r+oEX=oF9Ql`%V8U!5wen6V{U4!RPqB8 z=|9GCCx+bAM5z?uim;zi^lUsLwN_e>iMU6tV3{??^#iNoQ$d!SwVL!^u&Pz*v^QzN z4VIdXhU*2gI=fks4c=^06^*uEdI}#BuC~o6rt_OY_wW5B@$lC-uKe`=>3e6h{zFRL zyZyD*lM@eqc%Z+pOG_nn>hC+OrQ$mE_2Xl$!A^_onwG*k<{=7^;DJ?+u-j9yL|-a4 zMBGoslR~88{56Utp`FxDbtOe#Pv|qL_4TK;=$iB_e_)rzv6novvEVv8xh$`H?zesR za3VVI8Mnc_&fI^u*1dqJblLT0H>G-G)T=I~QMLJe!;SGQ>3PLHCI1T*5b7SH6K$VB zIu|hR&Wax|qQy^`U*Bh*?YEiiYV3vRRrH_bakL1Q!uDW>=&#|jn#kc^K(tCrR05r) z>)?uXjTRsmL9c-4c0c~%zxlM@+b%^De6sCbEvUIwGRcD<3n#0DPlwjXRaR$+t(LKB zV%EpHNdfd+NMZX${53e$fGL2Mh56b(o;Ht%aOhXco-%rrgcqF-5;b<;mrw<@0NyKBL@id(;E z`gLPtETh*=$6CXYzuFlMu5^9JSrJE1fIGr2MEK_cs2sD7@bg>KjfQPi)J4NE8;#6p z=ppc$eo%DQ+$Y3yKBMdq+n2ahAZ8?E#*??2z$vSXp0$DdPEGnx=ykm1RYz<4!4Xku z^0_%DH>9oGOeZs@UvxIyZ%HqsH?8Rk?o%k^nrZtoN=i8y-3Ltz`sgm~xzU{>Kp{8U b+93$M+fUo4u7Do?ub9Wj{%QOFtH6H%HU-QJ diff --git a/Mono.Cecil/Test/Resources/assemblies/hello.anycpu.exe b/Mono.Cecil/Test/Resources/assemblies/hello.anycpu.exe deleted file mode 100644 index 44ef8db84c0d42a418b1ad6dcf4cd46be22c58d5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3584 zcmeHJ&vO(-6n?W=s1PItN+F1aoe5M?luQ;9g`yI&AqlvckS#U|RTd@8&UUhcGt*=D z?7HiL$_1;u;mxBz&Q@`-N=mUj=r#X=2M(URz}d3IuX|?MO^6z=%G>no_g=q#{k=ES zZ!-VRUFsvEJjRnJME5akDjNRxYz@nUuYEg6U+-EUx^K;`4=vVx#bPN|r5iHOjUth- zDrd40F+XB63l$cM8h7^W8917SF3%FpS$%Yi|6b~x_K2=9~JKq?KOYhIa5;?`q?I0&~lOJu`a@9x=HlHX4`gjMwCG}-u=+u z>e=Tcyp=#7)5XV{Ng%@w%@8BH=}09#Xa-vm!p>}9>QE8r9mxX$M}zeyR&=aQz~OfR z)(x~**A=9(Ei6gn=sOi8799+44!7@=(Sk2Q; z!Fi)_=JXjIeg_5MzhDgCCMqMsPg<@d(vMaZMA{EbI-TLA3Ngrdsx*9QsWgMR0A0_+ z7XnemtO+LT(te^{TKUZyr2}bB`E<>crz2;%Vr3vhxRXZdbtKPe7W|Ik_h8Yay*1bK zUOEiE!)Rp&kv^ewCd#`;`{>{#4Ptd4P11{W2z-!+aK~N-E-gE>n_dNfiH=czjW*Gj z(2>VevM764+A=;bYK?%Or#cS;;kZ%TiyIDaaVn?xk3!`M8TeJIv{k}GTBzRQUPAM( zACcoFLS_rj)kc)~A$O)l82bU26)u~;#}%apH}OSul?QIiNNOs z_({9F+6xS!A|(P&*QB5DIX~h$hg~Zq@Ed~o`TU{V>t7tceD}v!zPk4I<9pQq&4<^Q z4~;$i7;lo*$H>Yv%j(aQWexUQ+0{CtpTc79z%}W{S41@1@_4MlF4m>^Kw0^oavjk! z!`Om4cOYH5F)ie5i<>f;5_0a;0{woXLmnemG}3>Q<;=Ze=%NRa;MugB_N1D=_2s{? z*SE0i&1*doQZc$x$^%T%Eo;IniUQVAXV3iJ~A#k70V z_xVSEbnd3vn6b%h)_1)ptg+4*+cLQ%5ywXl;)ofMek(N{CB17At1hex>nh0uxW-~oOD`*e0~oE%dF8mE@=AUbaF%|Tl=yQkqD z!&7IviU|7qrLoPKvlcSDu7W+l+D?8^VB)(_f*$r3iVLH z8lt)ZP_lpAhpqJJyC23UTVcSOTq?AV3Hy{&uo;g$QNy=q!d_auc=D{xRN_W8HxLn@ zu-jbOljrvgjJrzluo|=(0z_)UZpi4I^6ETv)ydHJq)=idIq8Y;oU1~odCF#?8~H0- zCCk01ArxazgOzF=?Ko*~K!lGaP(^NtBf#5$M#4XA(0K0l%f@}O+2S< zvkzx0?lsVu+nElFG9?4<8+ram5W3&yq4hMz%oHfj+VU`}oMyBEVsMr1ONJ=%@Xho~Zy!|F0^H MKC|-N@IR=)pMJ)$UH||9 diff --git a/Mono.Cecil/Test/Resources/assemblies/hello.exe b/Mono.Cecil/Test/Resources/assemblies/hello.exe deleted file mode 100644 index efd7c7da9bd1e4cedb3d50b2d1c963352f2fb4b0..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3584 zcmeHJO>7%Q6n^VCRhkm3(5kc&Dw9nsszNtz5@=L8sq@a_<3gLYz2MqT)v!I9EdA${`0%2&s1tly7F&aS~c+uT@_=Z{BJh7zu6X+bFY4vqq_(158ksD?+>ole8uWgY)Us|o*P9X zW);q4BVvBUW|zw>6jkmF4D_E$Q1wlr5Ypp1hE!$487Y^(OV=DRzHKX`swV+%o&_%|5n2XT$ zJTx7M3T90(S(lFz9n{KS)+ilIY62X+W=2O&YlXExMR)*voksE3X%hUF;a|d{NqcLq z=fi|8fL?1Q29Z9eQIqAm(LOysPC2Z-NaOSpodD0#Abm|Q1DBQ^Iz+F4A3^Ty7VV=u z&^6W$S@7MV!jh;q0zOGK9t6VSEl#E6;ZdkOAp^fc<+h4>NXwP?xfj!t>qq2xv5@J4 zv(kuSKjhAg2 zxr)Mpl+tR$rDZE7xbGPwk}s4y&1C*Q8s&Dx$fT$LqR=)tVF^ zDeGu@*YyUDmYJ6RO`SK9tlXFpa<0YA>6w$|+^GiozM^BECRQ}kv%xavT`_dg<0xo6 z>886%OKyGXG4|Rc>^gXBSB6Bi%yb+4iy~2B*CpScCi){;Ha>;S80K{<(+%)BT7k5H zj(rvS0{DE=z3Ip7gTFg((*&mMQabCmzALS<&Klb~xww1t<|cCFjA#S5QPU~XQL9*W zVO6-FF2(Q@&=UG4dk0A^V2a`8!@l{5OfBP+r_R4IszBELEQ8q2&a-$A3NJ$Esqfi` z!8ea9-t}FFuY`9OOCDXMJBY?i7t+u7AlgJkj5v*@U~(^~c3rj3-Kj%skKbd=)KNmLz-w=y-WcC?Z#CUIbWQpm>e{DJ zuYzZY(+hx#{cjvX>B09u6)v^HfHk>PXay7Yc_(i(9(kgQ-~1l z&xmc}u(#q~18umS>aa-uVFNgMwIux}djBR@PndPIla+zGdC(%ghHkctyvYL=Xg*=P zY9VTh54f~h!=Li-+k#`#DaXW#_>0Rw8Mt^fc4 diff --git a/Mono.Cecil/Test/Resources/assemblies/hello.ia64.exe b/Mono.Cecil/Test/Resources/assemblies/hello.ia64.exe deleted file mode 100644 index 1d50f54d8bd706751503aac96a8e40ac6216699e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3072 zcmeHI&u<$=6n^VCRhp8hl&Z86Dw9n>p&}bM4YVprn8OOQ5yfpkBM$$RFc*D-_Q-y2%5xRO;vQ4VdNId%|; zh!r^tYXNfuwy;`Yz9?~PV4!~_fzB_&NTui&|1+0_=nDa7>ZD4wZ)I(IfTiXQf#!$O5O<_wJ<)2L5a8S9nI#fggwxR*TW2lx+v zOq2)0Ps%Ptp&OJXOgaf}ivI9Mff#Icio;hoatjzU@YOgx=ZPXlB?uW;PZAwf&L74F zIu-9N9p_ZO-Qr}=i1a56kI*EIp$R**1bsv6ZxB(Us+Csbae5BAS9^H|lRl@{G|D^L zyKy>8gUCKjSvo;ypa*G)?$EQ~rEH6i0l}hY=mkpe(mweLzT(*ugGO2=(bS44)jWQM zD%|sgm5c1at@##jaLUIoAo3C0x3LB*F!hr z%WlANI6EZp8^W$0eDc!o_kVtI<%??R?cmL|U#aiAkG3|?O#bp2o+P7(k&$MG(U&H} z80<3$mjmRiI)(Mrsq3L#y(WUihQq6h>v|;=AIkWkbm0?qxDKTBd&P)$Ph-L*jNS9% zr#}A=@yY>lHGdxnBJt7Og!N^XXlw67K2P-9o|D^3O`>X(3iK}YBCWy7(JEbopMze4 zt>lOF!@pX%I*_QDWK3h+1FNG8I<`qRg}`xf2XSBqc2 zU#GtZr~yt9s$9g&2O!<0D$pK&0`qdHQ9E?0hOC85L)VOIe#@}SdiFf3 ztJKsC%Ro@yE5&VDueF-QRTtD+t&S@1@M})$edd8Bs02O^R@uMX&OX(i)pM$PGmCym zaP`q$4=mY#&cjrCc=yMtnTGGNIu9kTj%o9}l`$C)98tozXWHCYUmCk)GKu@OWP2ju z(`J)PbLPrG|CB8y_lsVW0U(gmW-SaZOQ*tpTaNjz6ACGIqA^GKmu=}=_46k4aZB%T z8Ex)e4N#1=!Ez;z+c;`=F~Y|ZtODD|@+-~RYSnWceHmMJwQ7#X2vJy*Q7+gKhvYM1 z>UmgOa;JuCxtaKgg#3dVc=A#{bnEygl({@4>V+06gLH5f8(2eK&da>cJ?1GrZQ3#y z)W!QeG+E7^b@0tW8+U9^@?=vQWc&a&E$ZW4+^5FdO+dlacZP}?VGDpEz7HM%x7cba8vXC;3cE*N`hFDOZofT#%UZlWzEbyA zRf?n;2|p6^%M}sEHR#9Lfb{HGCP;0 zXjk($a*3L8En86hq@Q0jA*$V(A$op4G6-m^2;Av|ZtnVDJOP~D0OX{yoznkRb7!9^ zs9Og;BLcYOBr5Uf8E!=ydVMyo5nYChP9lR?Cu+H5G_bSVcAFwFr#a-X6?FjwoX?`q z_aQ_EpHPk<;qb;J&(sL^@5@bc4M+BKqRN|dmO;;Gv<^9W=Z*Z)Lq|36Rs_^{`A%F0 z%0&24+m$r&qjg0SJIPJcpSV!L7;U|a6K5`z=Gjit*X_hy5Lel1VaPi3Jg{9me^`gH zC##Kgbf0;9cDH6mN4gBRA&*zN2vy8ce{A%ZjA+r>TI+T<#;CU%uPkWd3mi2l?-=ju zSOKH#eFg-06(o>&k)6DTajwPqkspe}geZR-=F{L?2VgucaHsx;qN|rdv)*hozHlJtSti8kg%-bAz0SvumxTU zlzn>jS8{tUCT`Ph^e$~MR(K2`s11#;%Q62KLGu8*x9Ps;w9bC*!GiwzUyi2`+^R!A>#yR>W>eIBf{4{j$ zuO6-mbk)gjtH1RPuqHZhVykeG5Xa{oB#9Y8pH3|=LyuZvugj=nzl)T4F}+M~4&5NA zMNTQRe8$%wf%K`#$@5Oho@w4Ic>=u7uiNV9&vSMK&)_sR%_Eqb=g}YJt}-`a_JB*C zx5(h-^ox}hD diff --git a/Mono.Cecil/Test/Resources/assemblies/hello.x86.exe b/Mono.Cecil/Test/Resources/assemblies/hello.x86.exe deleted file mode 100644 index 1e0c064f6f2b319995056f48890cf4036bdb9caf..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3584 zcmeHJ&2Jk;6o2cuB~9C?e5kY%l*y)*LPa)i8nbiueb5;et4zsuJZ(`~~I2ACLnlF6E3W%5P@ZaS|1hbJgd}ypMVF=J(#t zzRld5H>rn+vKS8^65R#YR50`ZPwQCjf9c15x^v*(z+G$h-oRqbSFA3@nsh_vxltry zR^d!GBIZYIdcMp;QRU9z!+j^y(4`roS*wSd{6VpE+6HB;gH~?>3QUtTh>2koF!aR0 zGKmW$gI{x6$ADc^4;4NkI%591JXI4H`rRg4(Q<)kLlf&R~B#`2UW{45paHNtRG=r@GVShTnI#d99NAf_x(O|uS6&-5_aQIEZ zx{Z$Lx`H&e4DF*DBMPur!?KdoAnl#TNMc)k2>bi!^oh(6YT9=i2bW);vUEg{hSfal z*hAdfRB99?Mfdw5KUg&(Lwq{WL(g>3QJNvO@>y1(nA$Kl|uD>hHDESL%eW_hRPgigfGOL^RX#cwOUMtV!{{vL4voGM&)( zn|1ZAQs?e(wGmyvEaXg!n@X7~a_&?EeLvA5PZ28^>G7O0=DlJ>>-t`w2j8A&a_dX~ zVXr;HuJ`W<0!#7^-Gp?jfc~F>kkVgMM1LmB#xk231z)BzUB^5_3y_L5PuHLqF<*hK z>6h&Ne>!oEA)PLzJPW=htg-5zVIitZ5^;R=AdZ+3>D#I4Bg$UOwz=kBIcS@yVg5B)?Jgl^g=Rg16h+^q?a-yE)f*LNAd z65d@bIdqZkKzlHKM`sfo-w4Dr~Ym+jA?Vmd}`O(>oYo))Y|T6jhehlh#{y-4dfr=iEPiVo0rZ}-%DMKN#w8K z8KRm2(6L?jVJqGL>DTbOR)RJ|fJjZ)4H;cfUX6#Y8V-F=3ME$KVNZk?TopRaGd2s|$Y13u zUfy~dLNT@(tXSpfz;SyUB77WyDsn>{Ki8hD*8|@(4cKw(b$cX<5X**&i_xmsBc8Li z*@v?g_Zn!&?No(+BETU((s@Eq^wWMqyHN}5tDP>@oIACokdB2-pR>O(74)J>eWK?#X)8xTTDY-j2$taqc` zH6#cjpDKETGyDNaaNvMMh2X}8Lq!igqy7P?fW)anl<&=~>unUZoU6WM=KYvAZ@%|- z=6U&@&oBg_$Z_u;aGhMJYUhVfJua7C{-K2L4&Io!u9j|0T-x#zy&XsGxY5zAMi@q^ zZWpvZ*oOmfm3RSuan zS;4tbviOCg$3eRg^I}?K_J6=L)w$ryNnl0fDo~a}?4=Fh>Akl9qibL!=Ql$AeuA`n zso6=%{}!xVvk7Flsaev%h8HJsi<-q&r63 zpAvm8h??X=G^q>E0S867t4>P7wAuSl(dI8#Ky3XXMHE>|aU3skeiLUocPI45vm2P#uw{ZEn(@qzK__WNao{&m-%V1}!AkQz(@L@G9we3~ zjFQxEC8(KZx7}_u19L8Ajho%nWU(fi#z4w*Vi!e{YUSv9j)BH#)_*U4K=I_s!%9G zsnP*u)Bbs~pDgg3$a+=&F^TO#4+p**7%q zo?6bq-EY3NUd~97--#r>fXiKJU6Nek%U) zZ$D0dukf>(QY3e$WCk*M--=NiymRO69W#s>^4>+(Y05UqOI&Txn(z)bkkT)r=IGmE zg;*6arS$S?Z|@Un%=(nsW87Z_P1|o?V5d;L;Ssw)hxa^W6lqABV=A|{ZO`9jwhiki zXN%7X>(fVGV}yinMR06CfKzR#;(cN*+)2u)i|OVrwShh(>nU5l!XE#k^!ANaW{Z*pIU`(nIrE8%>r7RyQ&L#ixT z`gw~c)dQpNkIB_?mHQ)hmM&|Q<}z_-RBU}7^x0dbL4BlFQX{G9IU-Fg?j}*~^2r%s+-gD16_uO-T z=iHCixwmf6HX`ald-RCtE_$Y-;ZJ6(7|y@)ZJzGzxOecbHGA*iLe1BruHt3ohQf2B zC{9F03e|{&ABm~?vIygfC~D|&+zrqu_LRzDp%kQ+oz`;TDZ@`XvuL``8e zk2wYB^}>l`CpdgB1>irU4SYaULIggC1LZ{d(Xxg}eZVxrw##K2g^XRLf%BJVrqItq z=YC)^h%4xsV6x7?K(vFE->u`cC(Q|POldH_R`M)YSo$-B+i8eiMe^5Z9Q;GWZ^OdG z-pu*8n_h(6Yvht(`%R$aC|8a4@!nIEhxRO;qUUHIc%BZ@SM(BavFy-JdKvtAI!ryQ zw23~4&Nw?{(f*D|G&&bo8-YASH5ml)iX&T+O6kp`Pe$?$_AWEjVSR$>70$jx*teYma6G{Qd4Sh6F-hF$-r$HNlzr$kV+$wlucwe3|0KV zPuktl6cU0&Iu0aVQGOz4{YWzU;TlQoc0e%+S^-y(tB_+_0#DF~#;U+qOui5HfAQ0m zrCS&7{CexNn;-4?l={AT|Lw(nBlkbSDYLc-vU-GN_4SZt<@>Dc+8yBiS;+0VqTKq$ zIGS#Gvd-x&)Kt8pEs>pjUf>MNf~CJw=YDiYuAPn5bW56InnFwIR0BT0ctH=7C>rU% z$#Uji3B00vk-*9HHC>lVdV@=UW3N5N&XZTyMMy=jG=_|gXFcEhbzzN_-wX>;U7W#l5n;c-8_&U05~7U7SxJqmdaW`nu;ff?B|oz{`hy`7x1JjZc9(zY(fHCVCCG z+gkIV!s?nl6Q{mm9Rc40j&;{}5xxrET`UE>BHhM&w-f%HO=5f_U=L6)7q^S=VfPlU zV5X#&u@Vg$Ota9I&5X0iwoYw>Y8kWmo5gsFCjNY8=gc{Nr;4mSd7TlHPYLs5-2Mjg zPOuXjv+Cxid2tor zm@)hE!nvW7w$O&=VlCKARpRkY+8YqzqX<-y8)Esn_C&oN_?~%t z9k*V$htmj&YUpGpT8g)b=a_BgVQnqF1|H*fro*D-dkx@})spg?_yjCVy~U`veu;2^-gT?4(ZY*tH!8NYu@E_u8Iz zc4j*>>)0_yDdi_c2vYGQQBbiUh(7Qq6_fyi=Ak_B5D5v1rwXNlhYB8osD#9iT)uN> z*1HZ?k_VnpuYJ!w=iKu@XYSk``S>-`h$w>j-g`thvGVAZ@c!TmwiCO4o}iyJ+}?dt z8NR)Ha?bShlIzU6Mp4fjw(a=(w9wtMt(&$!Fgl?Zoq|X=HO2RarpE?}h82xI@7z9J z@pgw)rBSIT+5`?39=}Qf=$O5j40J4N5H~OxKd*EJ6MP;T^?rtEi~O&yAsL9!9PCao z-b-|ci*WC_7=-cf{X`x2?%j{p*Fu+4^`M`skx%<#!3X_jBLMbfu3_AuO>jiq^e8oM_pp>E6!%{mSfCNmv~u5A`!J+>bA#IU2A6c zNrm>0N^603VCjqIY6N+$P+JgTHFo$xjBHTu?C{W<@yl^SdTaS1@miV7YG*UoPYY^P zt>`irRMthMZO}*b&AV1B^;_opRZ2&X;+bS2gM462?L-7o2f@S}Q;C=ZZag0CY{5b? z2X^9!{+&N;iEUj~fW=}?18==W`xV5iqWL=Z^GikaSPqCz!mLFT9j@}{4I_7 zf00m$Fy0z@U3v=q1r^*v?cmiR28A>fdFG)O&9=SzndX#j ziY3z$?u2mX%{=x4hQVQt3(HuLm{&CyDzX^1rcKNA7puFKGEjD1>^+5CE>j7(ChyvO z*Kj0=+$)vfbcY5^ujF`~*9Jx^#Y~YUp?hFsjL+hBIQ=#;ho;6{2F5 z`cawZC}0x!G*ji@f(7-#r7O@`seVyC{+^r;HI>{9mU0z!$qEpL0D5z?b^%9_4NsZP6@6e*K)k!=%B79)t zM$poYo%(o8YuO|Xsgalh1Ndar#Wb~E)nZBlv!fxVvIL^SH&ID6#I!^pU$0P%Z4nT@ zPT+#VU(rdm?VM|r&N%j3p-^P!k|$*=zdKZjk6~`deRw;rtm6{{6aMb69HC7w9{)~E z`MX$o^<`GbAHCo?Wfy1Dg}lg{)`dyo`4`asA=B_YQJl6+>{m{obg3{+*TQ=?OwbP* z*BSfoQMr#-cXG!acW^<-^Hv_=LZk~8->LA6Z6E2q68ql(Ro=aHqAS~B@CmHz?FM%g z)M-Qh+y;EszegAxS$cdmiB@{?`;Utsj=%O3{W;i{oMH7a)+zi(%K;A3IItlar8A(1 z08aqt@yp2F)rwuo2*H!#iUte4R(A&^ZwmJW7j{hCQw40=G((OQ+Doi8iCqI+5BmoB zkaIu<4TGAM zTE`(#l6NN)oH=L^aZCf!$Eb{WR%XvWDwSl95B7Cf<~0Tz4i%`3{Czy<_1RVP;vBgz zxfXrM--Bck)wB?u{y;sb(%oOYk$rNZXzBC9^>Ah$OLnI-NnO}^r+_p1Sn}-Ti33k0 zb$p`if?+wfIF?)#Uh>JFrg%1dxfgX9u)Sl+vTGmp@^hkScn6AR-gP`@#y^mEiboBv zn4a%W>P5pgXK+GH)p~;|U0*XcgpY=gYsY@u{*XQ6JY+lvlTr`9J%PIde1}iYiU>lA1X9ZGdRKK-b@$kF zZ-0#*0C}#R9pDzJK*{32N824yfBOsRn^M0 zLgk05yiie%Xid9=g99U3>cuHw*6G0u@4j}az1tlWhW0!CX;FQtc7B*tah13PDUw|3 zLeADN6x&?X3-qAW3mmY&9h!-$3x0hLxFUQB_%@5nOet9fp4_AOhk^pw!7lVu-ffUt zH_@93>9P!;Hrv2``%}H@n%LB6wzZWqzicLyERVgt5(Ir~8 zD03x9Z8`L!sesQI>xlASz@egp{fuM$K^WrZz>DZRc|14DMh8w}qVmRslVz7$ubp;_ z?kmM}r_ae|y$FbZ;TrygH8K2#@Rh{)VLc{`Kd2iM-Q^03tdpmU;pxjWWzrI5p~DkF zR3#OVR;HiMVV?-UJ7;h>?Tyul&8{}j)V4CAGQ5=b;S@&EhY#>3@mItGsZBa@Si=!& zdM&@G#QF`++W5MaK0i8z0<8xzg{N?gxWIY@yPVZC#D_4#9QkeB2j5YaD%;@TM4LT7 z7p=7deF1@AUDrVnxobgyS-)yLvxP=niwrHOY{iLgV4?cHt|ge($tCek2MV{AL?&}_ zms(-sH?%t$HJW~)O+}k)eoe;;gSx#P0PjO2@j>(N;I-Saigi~2Y#~Ev9`;T zx=*b`^MnILP}m?gn3r#Z|U@EM$7=UiN5DQly9P zHD>!-WR8dxwAg>b6WQBcr!VOdc-6*?v;UZ$4fYYRI`z;vhCYTzH360W&#-vrQEl)z J?|*p$e*p+}20;J- diff --git a/Mono.Cecil/Test/Resources/assemblies/libres.dll b/Mono.Cecil/Test/Resources/assemblies/libres.dll deleted file mode 100644 index 66a2b194d2fe39848e377e9128c3ce98549b0384..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3072 zcmeHJO=ule6#nMrrKD*aD%R3~rV~=7_%l4yCoL*EOHl@jLg<`-zs?O+le2x#yn0d+vA6 z+25+2(&Z4Q@1 zn9V6?LMUncGGl{-cA*})?*jYve`n5A6N0_WJ14RWe3Y%rTxMDV_Ujf zE>(*z>lYGiIrJj6fy-QLiIH^H1_rfscWfwkloj`a7Vmq9ihBJ6C}Mzp6m7TW4))+dI2;cnzroNQbeS4ax5>gIT9)0e z;kmYag_2Y+_RqA{$k)t$cz!0TuLkM`1b#JEiBk^(OjGpYbu^M1KZjpMc|A#019R0k zR4s*5OQSfmISZ>{>Nk`#9yOYNpyINMFZwl=z!<#LkHQ5NcxzfpPNw`u)zwrXTPR_4 zRsFzE*E?Q=2C7k2^}4D*?WDX4Ep1e5fgir9>RM!3J+`jxtHCRWXPy|E`+nEw7q)JF z`ZM~zx%ArNVDb6~46yRHW%c!0*{vIrk5I`SJQI7(*(jV?tEr~It*pe+TZwhxr{BK) z{l@#h{P^}4zi!?b->k&et2c|;U69RYMYcuyC$;X3@thxz;!+UIcz$S_s+4ZDc()&g z?V7Ov1-JBRI%HnaF2v@17j9#hAbC5^xK16?#2d6Z$=*jEkrl z`ZE79uZ%@ZDWiPamv574L&p@*`YWPJ8F-S2taf~fyC1TT4X*@aLt+ouFAojspzISxtoL+Kr!KE0a8zTOrhQqj7-zLjtZP)u zSRpRx*gZSM$({5V{7!wj7IPE?6oO8c9 z_d921?(FE>A0q)E$?@O;aGSG~tkREGOI&W-_e~qVZob=nTa4W8o}9G;z2R3mCi|vc+*n+<%}f`#-${Xy#lnW|Hd4<5d>G6w00eX5Y>{2~3D($CpmiL(@@ z5T}n~TeEcj>^*`VQ4Oth30LhPF+9T|XW}8TvQBBsIjXrOo||wCFY&evDLtjMqx2=E zf5DGj{X^-5kaj^F6iu*{{zyf>Pv;n0CmU(n>Fd zruMUFp?-&2N&@e9&TuWtmB1Zw9?vowt=$n8BeiIq8DRy`K@ioS+rYJpqObPeBauoLLu_DO{l*e#$7bW;-sY4_09&`V50#glkm z9ERNC81-=!s7;(wk+-NXz@om0T`H2nbGVEQdT@n2YTPGa4LR1F!*)KWJ8^=@QKHUb zA4>RvE!>RjWDC)X8=R9%%=sD)7 z8P0kY*f?i!~FYbvv}mMiAyr+pHR)iLufJvmC-8yG%Ls zd=%VyZ_Y$vFj#cU6K23GpzI;Two68N4mq=GxiM_mt;E*2;eta>UX;^`7?nM5&N4AC zNyLmY6LmMV95YjJL(}(aMbn?R%4UGEdN>&J%_`MNZ8WNKFldCPT*q*Ys##Ihlvfz} z5lsu{QATCsCPSW6vux8}-6aYbq2;*~rfn=JYt1e(I|<`b$+E3*vB4p3K6nDu%i)Nz z=&dCk`EOco1$o;pI5p2-Q_^|QQ#Xx|o38Ha0y;0;`}D<;tK!se?^$zqk-l~5?DVdI z``5Ilu9U8cuFfXv&ONCXJ-M}m^VaQ*3$e8$2_e#(knHN}N_R1xkl~K*RNpwZL2T0Y zG`Ah%K72l!T+iWus;^ng39T=cBrvVehqax3iM?Ai8EH%NWmly3$~S#d+i}`AY9~E+ zc%f|8WV0q`eeYr*mg93+VtNNxzR&vnsGb$Mel{4Z9pGu z33Uc^g2%-=k=*%Rct~8r-c)^pUun4nd_7*5hJP`^f7%D2hi z|5`a2RUlTc#`DVAy>=~6M=+}apLr~POZaNR<%8-e*nXZFz$8}59uRbKxlEU<}?&xoT?=yRVLp+znDn8HM1HK|MPi@^kIvIJD^8D6Yn2=(i=U^|9|Yj-#LAf_y7O^ diff --git a/Mono.Cecil/Test/Resources/assemblies/metro.exe b/Mono.Cecil/Test/Resources/assemblies/metro.exe deleted file mode 100644 index 68784b316eedb4c3d48f2e1a8b20b7d815466b4a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 15872 zcmeHueRN#ab?-j+&fFP|tdV9Uf6L}d*p3j=SpI-uSvJ;(Z3LEWEZIOHmByNDY2ul= z;@%l!;W$r*SFeUb60*o@piRt2SS_?oo39oc8bV4)vRYb_M|f=mX-ZStq%V(THAzcW zYxlSJJ@X;Sut@*tA8oEY`|iEZKKtym&pzkud+znfyFNrF5ry!(aDnIv-1*ui@U6id zisP63QJg+o_k7zEYTxs1W7ApRp7Go%FP*n1(}jXtw2wNrS1Q=qf<1I#)XuvZC)Lmp zTc=eY+)cDknUr4r`2*$FzC(tpSM@|&!HEXkoriF@@teSpt+R160=t2c#ROju;-^uA zCO$&cB>$>+O|mSmA6`#%9U~J&{~Bgw!8J#;1gs|x616TUdP~x-m@Z;b(AU&dNEMxv zMbJZ=0Z=A=)pmoD%Z61c&-W%liER@=Ec~v-ujbkXhon3w=R%Ner8)dqS08>g*Dj)g z8d6Z3{fdiiGbl`59YlBIXM$=7T9fj(3z~aEbQOdZQNrke?_)*>V#_jO)_E%d(oX^a zZ)UuO%gyB@B|vAuTe)F_zY1i`dI9x~ zj@4X_A&Pa^dr&juuK|9$RI}W*z-u%RHTNij3Fs#!LhdD8*9M4LZX0f$dyG@i5$aN% z#`4pQb+(t0JB(BCZK%86@Rz~v(@X>`(`^K!^Q{En5UX?TvU@O0s`E;t1JeKwLa1Av zR_9&DDVU=hWz6t)a7WfdXj#Vwwu`OclFqe0tg<$Ae&BuZZm2uaa^8xA;bZ7xbIcNc z$7NipxyPi-(O0k&E%nB!2v9RgZYK)6Vur=TWYu5ZV3;n%VgVWHgpW)KHB5_y+0n() zMoXu03bfSk7LL_vm>n2MD`s^y=t9d)q0B-9WgQ6Hc{)Igj*V3v2mq}^3N5!sba>ie zcN55Nv>@h(Tuhu;=PJJrwWOUe-Hkq?Fwqh-*Du*N2P*2haA3z4uGt#(e!D`nN4=j^ zh>pu|FkgUkl*EvafU{zk51B7un$2TvGR$hI8G&kcoex2)K7v3-L|Hzpv0Th2D*_L2 zoIy1&W3bEWeAw`@s>M#T4-NkcM!B~J>xiA^t{ENg1loBdxEtnaR1F!S)95IM-8jW0 z--TY~W3t6=|1Y~8HA3MIb`b1}v0d@dX+*CWRK6p&Lmb<~5NkQFmYtVK-#d@Gu1cXR zSZG88A~@7}t#L{;pTcAcxmYr+Dhu8Yx$N>P3j&%Yv341J4bLQuQ&?w0-4d^ialCJX zt2jhiy%lI~>D+8|uxT9mR_9KmgDo>dVHYuDb@m3mFhefl)WWLJfd$BNd!eXfJC72r z#(GzWsR*5D6XPG+_9K|EEM_jh2koh5D`73Wr0Zh|%f)IOtB*8CmNiGO`aEP3kwo-? zCCi$zdT_m{i^(2Kn(j{Ax?*)5SL5Csy8L8N(6LL%Z)Z0I;%+}^7wdVfx$g39$-0g~ zM#F({BD}g|2z0j{2q(gCqPz|jceCIZz8z22onHpmt#o`^2Lu{oNECL$lmUfp})!UgMY7^XVs388bUgZGnJ+VeDFRQbAr8jn#HR>NCY z(Z^q+IO7<7tR1|(nx_Q;0}DaG5CjaYvjL-maBRq8D8a_7qQnp*5=5+ygGKamh;%-u zBLd6zHR#A`4vK)KP50iZXvXBIjk(tXbe;`-#|u4zB6gYwDPSQU_OXPg=V<6O927Fb zr?LHn&@v{7#4~d_QkgbRabXa=Y#nx|nlh%!Wy?<^$fUm9xlh>VgdulkV6ziO`HuZ9 z=&K-i7#-6XF~qvuP4@^#ueTi?^haR$?eHnKyr704XN`{ITq7Rb(ZP2~m61vnjNriN zwF8QW4;TDSC$^?~Qd@eqY(k(Da)%t?RdDvD?<4vI?oq}^i(a-c<+H@^v?HNG^-B+r z(vo#S9(L*8!^4PFY6U$LLfJshJ<7tku(PTgmOorqhb51Gwtfp?__=iiJ?AC_%PEf^ z%VRwybd9hp@Lc45o!ao*fFFWd>S1-&*2nbSB3m^niw0E};0*%Ls=SKPL+Sx=ehZu! zeOmBmrSxa&CGg*AtTkeEkHIn@H@NOA#+QsZy~jLY#_03m2T<#)0!y)*V=;O#_5r{@ z6!@aRe-^l;p84wq?h<&jz@or=1b(gl@%kA3u>O_$+b9IL$7suv<|Q#21x(VpCATiI z=ns}Op~aV%aJxSNOwxJbuWMjyZ))H^mKwNUry5x1w*W2rwD7;$u-35X$AHUdBz{GF z6`hX1f)*c$v&@&`ACFt~{Wxp5q>)>hZsgWK(#WOHHL}ic0FTid!f$PQK&_=cfZOQ^ zX5j0T2aM5KaL}&6rv(1Fz!wGn6Ceghj|#__QcbjhIx((gY5-IM<61{&P<9=trPx_H z4w`6`ra^@X%L1rJg^CiU9kf0HY7H#t6zWTwN(uE1O>xvT(W{_VK=Mi{dtJ(w(_x{0 zs;Qeq^4~!%h5mP=fg6q0fOi_}G@hXT#@h@zh9e6Yutxy}0i4`^VN#hFSKkpSPXfH~43H2=f$k>juyMr=m zp^kn}*W(uI=!-(#OBalOs;4J3m28|bme6-~y^z^~NN8;j>|ADU#HKT$sSa~5;^JYU z&d_g~(-`TeHTA6NQj)%^slP^2pq>vXH5%Fr>P21l?$CXRsBdX1E7Yr+x?QO6 zY3c(){ZLcqg!&gveNL$JntB$kFQ+ipR-)(XzAhB6yr9%8As1!Mn)?5tkAhmIsecKb zqgB+VDKi|yvoAlZaJ^*sQT-%rO7uK~*~OQMvd@NHS(O9orSMm3s8_>(K{8yBWPd(G z;&xr{9Ep0NUJ8E`bHA+f)$rf&+{IO{hg3}{ZttViU7=nI|2_3oD6V$}Z4|ZKUPxU@ z*93it@~HIEK~1sed+A0^vFCf~n5NkCy;Rf`d%lP~Bw8ld|%^%3h5P!DVBH?8$*kRI36lU66F&jb|xsnw%~ z=qXLTYQ<#+C$&d)J9NyY4tm}?`LU8qlYmA=3>V8yHE24LSDrr00qCM)}^gdm-1!ccP_v*5NXbjW?y6jN& zK2Q(qvPmiXZC!Rs%08pZ?vt{oblJmF_H0lV{Zurkeu@4}Q%^;21@+B9QhgFat3&MFxWL^>cyMi-E(GLXH zmIm4u>M@CHh3KtoEw-V`35kaAJPkh*iIuZ2s6bD6*^1r7*g zodyMx3;U}m=r#AzoM+)e$+Ct(p0!=fGeN(&MU#Tj-zPQ%t#e(aEh+0Uusic9A?IWk ztpwIa@23}3kGfaj{Q@5n_?W;?34BuEGXlRR@aqEqO5ooD-lx6?c)xlB@SIYLbCf#Z z44+@}3AF_HGr<3D$&;!@@C0O@q03ZD!`IX>?QHmg+NLHN{uwaW5Tkz4a1-6r@P_JF z=Ngo8JvcomeX1d1Tu(1Iv>0g>iLWxUsyQB`TT!~fn3Y;>((W0NucMdaj`5K2?+0WX z?reOo(Ms=c{DN^4aVGGX`i;itkqt6u9X;Oo*G8A%U4pmLCmVkZdFDT+{;2V1kl}uH z32YU3nZPHdm91Ly_ZwH3&!}kATJtg0*0dh*9ZhF&z{{6&o&`bhvp5&R%zui_1&iTn_I=6KH>BUo-o)yZPcu~ zj1*1M8)k}p+8s*KDcTQsGi?NHrkBAVl+xqW2TnbG2%Oczxm4igbOD?#B8i%XGAamw4WX^-ae^5A&Xvp$k zRNTrLgW*F0p9!GJoWB+Lohai}$IuqIOW=gSIf2w5r2;1e&I$ZS6*p|-E5@tF>js%o zv&HmH3v(uhdC`Du3eUFT#{s*-p9I_<{tVzy_zA$V@E-%-A}}j(R^VBI9~JnB$p4PO zpzhnL73i<6`vmP(M2|%F0e&iSJ>VsEY}Gvm+q15Y;l?_)r%&MZ0$-=QAo)}Jpfd1; z#P0@HQW$U*vU~%h&FjD#jJ-i?(N_amUn8K6=QRUsLNj1Ho|g=|6gj4WOm8LNJ5kTT zNzfX=ZKz=&3u*)04k-hXy&iA}y#sJ3T?TkH&ae&SINk8+HM9}y0Vh{n-bzv$!#(!RsGseiJVJ&`WD z9`$E3WA31v%Q;}Vg@7K)3X%3^rSf6l@ub>br&xqFqrr_E8FBJQ!MPz@$hf!p<$LPz zaEeR0=eg`;S~P2!a#?C5?Hw=8(D0y}pK%LLp*ZLk3a|o34F{@==}fwqt~g<#0>~FV zH|LZ1FX&C}rI%WrE7uql|yFZQ5K+8d-49xCx3sb_=16GYaUk_TUhLzgu z6dW%*N!5^?*i7Rmb%TC@2D&xDCXBhG#dIN)_A=6x1o=pM=D@Lw6$W#`8SfddOvXXa zL1?RKNty&0;L2?^8~3d{4QMiNlM_E7Oq6If^mTi1Hc7E6!G3 zMO-@U_j_J?R^wI2R2T)n=#|ieqd7E8QC|cdgv5;lc^`IHrBSKUGCWtk8KbzS#3~29S@ux5P4Zm8AmKTg;M@VI#&YD zBUW9q{drUnL*?}wLquF&bsck9rs}V<%zO?O^#vm#Hi2Cp5J4CASD2L^GgaF?(Aw>y z3@rx}s7&oH_mTQ4{o8qbe0%`IfEl$X>*O-jH?K2`i|6%YQSrRWHOmNlVZ6YL6Ax#x zn4X-L=>TfT;nmqGOwN`^j%5xx>CAybZkEQ2SYf0GTE@Dw2c##6BP%$qwr?LTX%sh!Gzk>c=S`lAHHuqM+!x3% z@^N1vxQH*lsOjvyj$sNf_VaMn&2XC!D|q=t7C9Lt2Ux#`GZeU;cpL;sJ2`ADHPKZh ztc+Ayrxz^K1s?cpd11pOB%YSw%#@1c21!HSK_Zu-$?~$`1#3lRzh&Jr$d!fR1W#8s zwRS}pzXJ);nLLy^nmXJC(4 z+Y%V!)I&}#eNr%90rVj1id+vxN3*$XvBt@7-HnvaT(u68ybaF?Sxg0KXAC=EVPX1t z4KgKINa;*wye0?Tg9I13mgnT%6HaXbuhec~VpBQ4)vaM?@Tb$r`7=Q_Tvl6?{q8>L zOqRGZvNOc%6qcBSo^vAWmiz@pK}SSlu;h72kjl?24oT#bZk6Xt&=O}(OmXg^IptiH zcAuPdB+TjX@a~+GXMLFI<>afzBL|R$iK~LOu#%`(`BfJowRVu5<+$Yv&I6ZosY$g+ZSp&mP=+#Zx(|P>{2@M9QOBPfj;2v&d(sN=Ix&Q59@rSB;?MF@4mH!XDXBh-V@&t9@~d` z069ePSXYS~j@6o2)6sX0lS91t9E^jxv|mk9@en&WoyMawo`2c8Y`#3~x@M}9kMrVF zIDy=s##}5*TQ(Eyt7a_{hv48i5Xlk;2y~;bHB``HSuwn{GsJcD9)%VsL`pjwR&M7Hn2sZSQ?ISysW zChVbrlf*lB8k7SnO9lLj_@yCdBRtYL7jlR;<#E>84Qd8|Cvh&dQT|52;W`JkTnc4r ze1Vc9wfzPu$)J_nP&b9QOv8XT>T*6Kby2g3_Fc%cL|F?B|NM0iLxTfd^R-g{A#kUt zgci~$?HBu5dl4sHF8D>-k30AH7{1L);ftC1JtCacQerQ(6!8Tvd!@wwNQ^Gz(6-TU zwZ1X<(!i&eKG6N-)*@cw|NhnE|10s$Sg&c53foF0*ITxsT9cO(n-Nd0EF*0JlI)JNPTbH)t6{~Vv70&Z zWH&hRkWI;M1}hn~fn`{>sajiG*?`v8kgZzd_*5Vs>R>^Dl?>Xz5))fjL~J9uBiRpm zSiYmq4kdTAwg$9H?ugl8rkR13S4ILe8n5?)~*klXLeNKtN(Zm>UJ_UPe|lDN{-LS^`;SucdHIp++d8l2MFX zV($JhQF88M5yE&R<{m{m1`h_hJomd{NX4TzC|k%k8zH{N42oOPN>o6+-X{3@2T<0m&;qb{EAtX_KhiwL;v7oN z_*%w{#^Z^(pDc~UqHE&u)+ki2iAO~`-fEE<$90{erK$b9#|B-`>C(C94t%h8g`%-| zOC?q3r8k$BBe9h%ZXa_!8+)DS+J131=h*3)8NXH0@;5ox#fNu1Fceo*R~b?wThZ!D za&3RQIudSBg8>CI;vBk-`!AkfDoj>&>TB~r}K4vVt!As8|nW(JnW78fE zb)`i}mH*EOSB8!BB0d6m5y}sZ4vn__`kuot9+TW}sb z?UWqvmLYdib{zi}lXb<&TkzPxN45SfZ_@WS<>P4$WjP0@GjAr7n#ml6 zMgR5JibK^lQ;geHx)v+{zYrp%q#kl%&Y~#qPa>Y2R3^vYdg2Ypda`#3_6zXe!2<@q zjgyd=!>7yq|9Ix+_ll<_@wYY?gK7`+c6GYSUMvOUF0y0G34~m7J z#=B`kE;5QYc}MV7(IH^NbO3qGIPUvt4{*NzIQ07YKySHnaK}gVa)kiPC7MM;!s9&0 zgPtH)97dLQ3^@{C>xgTOp)?JyFIg4mPMpaF*YAhEip594CeG|QH=MeNrca1W557$c z{7r zpSAsPU0Cn+&p+LF^~rqB#&aJZ>+NXA_S|mc$l2w$f;-v|kL~HcsvTJYzs17Irn94c z*74h~-q{fA!*iw_>e*0G@OQMAyh5*!$LD<7@6MMKz3xdj-<$UHsS}&p?R>hBJ?8ku za%Li}L6vP+lnvv&yNHM3c@}ZX&~Ect>5lf1*_x;M6cUy8je!QdfAWj`w)$<_v$w<@j$?>z1-s8&_3Nv{ppbLN*^X1Q$FXpT8vf$PhbwXKgrj|~tFYfW@^BE6@Y?FzMPOSF~{6gEje zC$TU*89Z`f*kYjzIE7#CG=~RzNllb#CR(ok>w6@IE_4cUbCS;xeJ-1@kd6>7U8uVm znGr?Mm3Ir|T7l5$0iO-9Uzg2?O%)K~hNOrQ9npQ^n~)T?446Bj2V0dgK(G7U_TZ?n z9)U&1S^yk=S!n0cSEyf-#1^Aw3K-FPVA3Gtk=gze<*5Uw+d9z7HtIn8BX;B3SO=oI-7~x5T=Kzx2Td!zKrbo3&^xSgIlT&9Dm(Ttx)j(f60! zz;d|0({qZJ&HWtr%a+LnMFy!i0xNIXR#52=@HX?MfRkA_||>y-mB-I{<`bL!x#L=f4%bh z$_<+yVf!wh*}L>mdHA(+ubxR>`u-fzr%44xEk8(})#XO6dVlM>!#h2HV3w<%sF%dK zUa;kz!i2w{SVnP+FEMqO7^diIIP`?mw81s}M34QAer6H9JUrJBA!Nh*aRS2W3{iKi z?r=Fv^iyb7%I;V<_DRg>!&nDsKe!U{C6R{AXCLD&dbB#o5E+P?mG!zAKrB=DNKd>Q}vhC1j^S1b{qXN z$bn2)9q>B%StWNUEW_ZZmFG@WS)__WGmY6JXR5@}qi~EydReiITkW2d7LVVp&W+)m zM+GXO&H$aCUqv0itfiW(A9V_NI_R1WMC@PB;V51E=#zBctYfn>_XX}^Z=y?2B^Y;2 zuYm87-o(WC;O3qL6M^9t4BK;gZ=%9QqHo8twzMGxck*_HA%H7-6D8l>F3cJ37-F+y znZ75ysbI6|Iol24=;f{ia}3v-;v$%A%!W{m)q)KbI3{FJnTH5pd_d(I4$_ZQ`in)| zGS%SHjbbs;8Ab^Fk_d*}DeornY)Pnd$St^8!kDW>GBiGavILyGFy>oj%;{+^ZZhiD zYE%ZQ$HAyEOLE!`^D?)YE!WgRFn$Rxd@sn^v-$M l)19>@z#-jPeM1oB+rCY=+yNH;2K!~}El0S0@PFKazW@a#-Dv;- diff --git a/Mono.Cecil/Test/Resources/assemblies/moda.netmodule b/Mono.Cecil/Test/Resources/assemblies/moda.netmodule deleted file mode 100644 index 8cc49983e620a143a87e240bfaf12c0e484e2d3b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2048 zcmeHH%}*0i5dUo}-_nR00tfN6pfQ-N6+iHRq%B~>uC-XLc9L0W@9>lYR4>k2mvXX5a42t>=gXI6!N2 z6Idr?$^`t+>=C&W$KNOLwrwN1ZcJ|^=a+3yRJAJWVnvjSuB&`uNug`5uw5}eTM!ks zB+bsw_JJt%+ypRf#PDEYWOD1YIugkaqctol7Fxfj2nDSSEoOp%d|Wrv7GjYUvNOez zX#x%fPXi-0+=8bmpb*KsLIyavtK%<50Z<3q)JpnxgJd;*x#|=C;9AKSG!WHIT0jC= zG_`b8DXJkuX5Q0GYX@b3+z$1h#E+?PJJ%LN6RHB}p)-ts%F@_;ByFIBREqC{CSGkn zjpo6=*eOcdK8Rf5YR-tV^ITVk%(QtSJv=nbIhx=Q=R4T{5E!8F*DM!&ZM$WUM0_F} z$Mr81@P%Z0yXem^OpO!PNx#H;&QTU26StB-8VldWFXJ4#!`}GLlW%)bXiya+6&h98 zjEgu!<1Qml{4sH+a1VE3(D}VMMs>41C)oQEmxK6npgrlyB0;_`Ft!EUq6r(i*MnlF*{JXx`vhQ-UPNvS2* z*J7av%@UINuRlkfS2G{dQ?ah(w-;!AcmMW{-t+ZmG~q;C!06-A%*VQK>SFbpawk?x zvg+H)onO}Ko@c~cj0EL*lM2!W>@&-vq3@Ko?rXz#XH4mF$C)YGZa5Pu%_WEL5&h9l ZKx6`GpY1UL5q?kgp*{Tj=Kp#EzX6R`o`L`X diff --git a/Mono.Cecil/Test/Resources/assemblies/modb.netmodule b/Mono.Cecil/Test/Resources/assemblies/modb.netmodule deleted file mode 100644 index 38522b293594af6daa2c4c0412a9e316d60a7097..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2048 zcmeHHOHUI~6#k~A2t}HrgvbKC1vLbd5dpsBtHW8xns4KS6iKg?P@)09_Cg-QsD_d(N5foI5jAWbZ1*tbS z#?OVVXNG|ZErJ(w>9M`L?I4kA(CPwEkszArBrS+D#4H3U$}w)HJ&k#C!kQ>DF(B#x z4|M2q5z%G`kPpnmWd=BTc;@J+0BC}Jsw01YK#J;~T=Pgb^YSU@4-n!e&nE%Q>yETk zF~pFeFke$kTtyimTjlC&_H!m--Iq|6pvp-ZFhU5 ziw2E%Bby)3YGHTY>q@WQqhIM6=pEpj#bA;AO5FJf=%*%M*v@;7X)n5D;wQy;ubp#r zYSf-i7oDSXH*=(uYyYbk>?6NR+V=12|K;Fs2imS8r1UMS}?9|6x>%>*_?S&OT< zL@Qs$ILW6ZWB7nKbbV04l7C6GqK$HF&j`-G#C5;RqVGL9lS6`XO<4Hp6fNKdMTiY0G=-X24@rAL~4WD6SzQhF98x2PP;G>~6+Jz2uEu`G)o zMhhFtegM7bDJM+nw<@-0mZUzUN@dfMPF^}IW>LBb6C5vireRv9w?636_Kk`sG3dIo zWLO6gcT|l@M>4EJ6|4}_AV!oTjE+A>RQPIjYis0f)2pdZ>GZ=NeQn=R_kQEv?biOC zXLJe)x=3s11P-$t!1_Y=QH;+mz%*Z7UZKQ@y6BinA8Y@o2LrBfozPJP9nP?tW zv#GoQ!4m#K7ySWUu&62(b%T(AAbtW%7D(N&0*UaQJ2SCOtI|yci=6Sf=W)M#9{0{2 zdG&)YF#(`V-rECiQwlj|eDpBj^s$%k9K+X7?@rye8oN^)SG-tlM`15=`>NvxL71qv zR#6%#FHrThmgrhtIQz~&2K1kGlO7u8hBT92e^^1%cnB21w1q6cuYe9>|mb`(Y~;6 z0d}IVCA2@4oSZWa{3AczTXqyj9Zs9toE(?$2`xhotG6TVhXk5hx9FBwhsh)4081mL zQMaZukJMJeB-9j3u>k%IH5Kr4u0M|Wk)WTxzyFP_|BCFlcH%_$?R6c8Y1Gm2zP7I2 zu8u0IA9upY_u3V;siW8ngTC;@!OW!=ey8Nyh?%!8 zt<))nSdKMGX-Q3goS4J&S$Sd>EC*SXoOxxmP#zF8M$hGzppR$znbokH`uYt7VcQSe zcGvfF6%kK^oSloHCzM(9;;Vmt=iIq)@y6#rEdBb$-G#=qaho9!T@CF~t$3G4eZb}A zFsl3hDmN46thF{p2x{*Hlrs)Lu>Qjxu+01ULiQCMsUy1q)ra^6B;Str9H3qjE2Da; zMr9K%T;_Nl>(o}ThKsaUIKD|;=x+J`U&T9Z9QklImu1S4u*NHQ$6{0$5#xC9p&2v4 zM+nXQtofL3aMq1BnBI>cAxv@qE8$2hpfUkqs=dm z&qwGLQ&WSOo>{R>#5Q(JRXto`G?;7anD}eCUpklgMK5AKI#12?)8zV)*;DqN@Fd2& u8ulZ7Nl&r|=h$~lWZ%@k!)pF*o%D4;Pk0AZ_Mc(!+7r%m5dMF;1AhY+5$^#2 diff --git a/Mono.Cecil/Test/Resources/assemblies/pinvoke.exe b/Mono.Cecil/Test/Resources/assemblies/pinvoke.exe deleted file mode 100644 index 2bd10bf8beb4f1198851ba58f3cd8ffa384d476d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4096 zcmeHK&2JM&6o2bD5C@3p7YY@E!2t=OX7gD}Y8{2W5QktIOIrHYdH*en8 z?9SUve|($Th$xM*zE1Q2GegecSEE%dcO81zMc-$h9DZO;JvltLoqA9D5^w%R78s65Z%i3ji5bb~j6T^!hAc2v? zU?ec5YH@=y@$*cp7?3lxQLde6ulZ}vb+)EL_h9!5(>bE2T!gJ~ooM$~*>-rb5xUXt z0KbtSBz7W~6U=G$i8YgJJ#KIY1krU{$JzyFV#|TpR1Q3TxBms5bo^lI7?SEdPUFRo#w}y17FTu9?zcbe zKRI}kO}3K{oQI>H&xr10{($LXqP=i2W{qEv10R3Syel0)A-lI;|O< znr1Dpz3c*+G_qW!Z^Xcc73NML>Nc7cy!8&{shf6E(QsdO7w7;u_B{ifqIp9*hF$<} zGZjjcrnjg-g7yO+pu@mNDPw4xb|F%m-k~9S+d5?B@Fop#4puvzfW`DG%(TE$aGY}k zEPB5|5{*o&a>bWtDDuLpx*=`3ENN0H3Sw7j-z!mZB~D~OGo??Yo6xwF5fv{?DjhgU zUVBwZ(~cLC?Iuc7`R1gSpJK{aw3B!$q@|l-naW0QAxLnJDq?wDH)~(2gozhO`Q{~9rUwiLT#}Buz&hH;y z`>LH%sZ3@kr8C``Oom@6Y_Zb9vN{-bby)Sg?I1rrbE$n-v=d!a;l#2lO?fDNQ=8wSJUDu2uaF_Zn9qW$svkF4~PM zoT_!xP4%eVbF=>+ligXQl zf-Zq7;J&;Fz5qOF?oOgd>1QwaCfy2W>jJ*>x31=mY@Qt4u#@EBww16M(gG>7>j?3# zIjlO6##nbKft~_agZt@wFlr&D1X>>Ci!ZUXYIORk@f)TRX!JYW#MXv>9^PYejh(2) zkAQAJE{mq_Jajd*o3Zqx3p59x-EQb}Hi^*<5xb9iITU~=icGXs{nE#3i3{HzO7j`^Woe$ zC$7O5@{XYypo%^s6aTpnTj|-4k4Mff2fnCE9i!)rW(Vy4tdOCr%J|+G&0e0H>^+qg zapHt!$5){o&92Bed-lwp&Jib$Wl-{01Pp}nXttum)3LiG11IhcJXfn&EhN3J3Qjw5 zU{?pSB5*=)LB`4aW^XVh#D=j#S)$t|D=iV>0|`-uP5}4QD`QdQd#-7Awi89!zM6$Z zSK_1)E~stBGnh5|;5(LXMZ;&EhXftEf;eS)7Ht_lcTvXMv^vzVDgaG8Xfq!|SeJ_co5qe)s>?3^}MS#LcU*m+p@M*t+ SZC60l|7YN9_6@vt75Ez!HQdJl diff --git a/Mono.Cecil/Test/Resources/assemblies/switch.exe b/Mono.Cecil/Test/Resources/assemblies/switch.exe deleted file mode 100644 index 114083242cc32328f47be8daa13ae6f111ee0280..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3584 zcmeHJO>9(E6h3cS#-SBbKuTHAUZ!ZU*w+DS__3waKcL#u3DcHfjPT~oZTs~7jPJe~ zW?Yyq)WnU!#KbKzy3&OvCK8D;apQ`;OP0iiY>f-?JNLcmv=y-~HJtXId(XM&=R4=U zd*95xdXw6Ss2$_sL!#T5nev)Ho~>bfci(rr>6@K*58pOs?;c)Qb(E-t!AfX(!nS-r zh(t+>u<8rP7gO^^;RR)B?%LIHBne%ZCYm+csQ;&ihmkTeOR>t?7z8fveNp+PxUhVDuz& zy4T!$Y;U@+%j`_|2{U~x-92z%pl6_OV4yd36piT^po!wk6NW|;ms2}o=FAs!r%s$g z5a4ye?_>18gI*%(m%J`Uq2sS8EOj6FIrJ|UDTBK3Hcqdjy6ojVBL1!T-k>ZC*9`;g}#wXe|@`V=yIH_3qYI*rT) z<*F;sk-FhT_NpoCk_z#uB~RHw=sG1THdG`%nlHT}?TF?q$0yT{f{?5bt&Mlh%T+&e zJZVk_Ud3@`Sd?MSv8AF|VMR{hUzV;_*DEz1;mMS$k)*_t&9GH+TqkO@c4J%`Z=2B5 zt>3w{O3;ba43I2k2qu&~BI+?ZPlJZBH4QjFFtZUT*e6 zs{2Z4RW1eoblsK}hP1F61~(Kxhoi~+&q>blTJY+x)I29d*CvB-x-NA?bhD&1%Pzl% zxIv#Kk=LvLCQISX(k)oyGkQ9{O*fPhzq^IM(XT#2&(3QbBE-x1B;15>D^E0)Y8l+0 zAo?ZV*2<~WFy~%UfD>x0+fO08B3s9)Y|0~Go5LI3vR#6029PWbF;Ahtfd#)zZwmz`C=$Azv zWP>^8#&oiv+ zDZoF#Em;MQ2v1^jRjqosHm-?#Fb?brmL9t30-5+nKe*C^J3ow!)je0#WT@Dd6`tig%Th&48?zyl5bMEa$`W^H)YyawA2*=#Ef4AE z8sn9U>)870G_6V{I}}HV!m5g9{N-Sqcur)sA95>cS3~4XWN1S9Ruwp9xez)v+~6xx zZ8Pf0W>f)c#lh8RSNV>el{M)Km-%ScQZs%ncvFU1QFX>`d?C=rWy@7EDM|+!dIXv# o^r21IM~2p$0E3aC<`aUzPx}dNy8|NrT~#=_ZI360|Dz843H|$}82|tP diff --git a/Mono.Cecil/Test/Resources/assemblies/text_file.txt b/Mono.Cecil/Test/Resources/assemblies/text_file.txt deleted file mode 100644 index ea780ea5b..000000000 --- a/Mono.Cecil/Test/Resources/assemblies/text_file.txt +++ /dev/null @@ -1 +0,0 @@ -Cecil ftw! diff --git a/Mono.Cecil/Test/Resources/assemblies/varargs.exe b/Mono.Cecil/Test/Resources/assemblies/varargs.exe deleted file mode 100644 index 4e3acf4cda6b588ed03f99dc4657124bbbc34e01..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2048 zcmeHH&rcIk5dL22mQtj#qFjveQP4ERYzV{<5@Jf_w}6B~G+tzBUrOV4m%MHX5+%ly zM-Rroz!-0O;6RKA{{f6wFQx~s{sSJwneHwi0gP9}WZ%qu-^{+5H~ZR|2QSeCAWCa* z57;Kll5ObI)iVkwuYOEot7WHiTTJhCF07QRa#gz}ZB=B!avax_%S!5+Bg>8)xto_2 zx2VjvwnTTZ_1q{hEh4z{V|OI1R!35_in!lY#Am;!$x2#TTC5})igDj8p~Vsb;#ufi zM4xXw2R49y3SOjveBd8zvcS1x1AieUKquIjIN^zX1el&$_XzKDuM}$>An2P=LnN?d zYGu2Hpoc8coD-vUNU}ig5d0_ibJ|bm-XbvYP6BlS(8KdPQpwLfO}F>Pk)Q;6KXn1W zkRd10102u4mAseaVi`JELX)>D`G}H=L-JS6keBGm<)?B2oaoPDtVwV217&>vr%93gIt@C}aTYMOrEUBHA&F%jo6}j>zB<3=D_N(2QHG+3FVZkE@=lU|5$XJ*6$r)tIk2Ub&)( zs#TQZO;}FRRxk@3TeGyKX?~Sz!PRzo8Dp-CoTX7Ey#ch9U||C;96X|0_v+uCKAHM7 z{(kKFrJ>sO*D$0Isg@=KB5DYcq?w7B5fQ`jc-)AJB-?1SNE!6*hjiF1@P&POfDe1& xeLdhF-gfoqx|*@dj^C(KX3^&RK>ujhAhQkcOr0HnVUeJ8}v=>K{GzX5YSeQ5vy diff --git a/Mono.Cecil/Test/Resources/assemblies/wp7.dll b/Mono.Cecil/Test/Resources/assemblies/wp7.dll deleted file mode 100644 index c3cbf7b6f1b145382d4ff0ddc529e66762775762..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10752 zcmd^FYiu0Xbw0B%K5SAF6UA1xyyA6sO)t?|Kj9Lx)N(wX*5CmylJAD{!9!=380qiyf6sK@2ymWwhvzddN9*@44rkd+xdSp1J4D&i>S|P?U&bxZi!3=*xKWH74PEgDYt6 z{K>C$(ihvl)%|5<=3Cv1tGcaLEwf~4WwoGHDyE|@3)QMsRK223oz1IdvnWy>9qk7_ z(eo#XW|Sz+yzmES{ocM$k?y;cR-z;@2^afo<9MoWS!&1Sh^seaS$}z50|cJ0D2+W$ zv|aw!pI+4^p)-)1=kf*Ife=P`*A=3>QT+ZG(S8qgM-P<ngE25ox}#@tSk9*il02bvSq69?{|ca-)--$ClZ z;%GNp7{J!;yG^jR6BD8gEl{9C{5aHb@61H#9WA6e}4~)Z{-2ZcRJ{Z^I zOVH3SFn;%C#zm~$Ce}#AdJ3qXJ&@z<#bUUOnT!GZnE<`F83%NG(SGY|KI%lV|v$*yQ`Q3 zdEElsu2B_#DOx9u%4EofePvX1s-Qum5{XdrS!|r{2LaxC;j5$L)hg7~91KS7XjgHq zk4zexZRe8nt7b)@y*~wz^cu@X1x>4tQyodC?ZT=kYj&!v7cA2@SDaMAET=E&m6i2$ ze+TByD8dyuMaeAiSP^r z3(oc%(;?=D)+Wp$(iwe4@M1c<{Fo>>zBJh#6j~6E*K|u1RZ}*r&Z_39t6HUK2wOEg zR#jZYq}l3W6WzM-x5uB*Q};jm?FFiKiHON++zRF_f~j#nECf~MPi+u4}0qLvLPx(_DVxx zJCBqLTSS;uQCTk=Somelu~Vj1N|!Zjtyb-WcdNpUE$fEvY)B91$to8{rb`vm($GsT zSxl8JE3&8K2jG27TU^jhi8?pbgVi4S4@z;GITKGx_?+99|5$WL;!ZozMzvz6GF61+NVY zGFS)KPr)rSb85l7G$mH_iq7xHup4Ev(S}ylpVsl3V+KAY5Z9dcPy^v;x_PG|t>C>E zb;l6%T16Og>~J2gh4}rank$=~wF=;FyG_6BPa8UvYlTfzAINZTACCh=d%xbLq->MkN7Ho+1`AlK zgo)x~2UeA9-adDAs#>uq7nA1B91B{S;jW?JjmDC= z;w~XRjpVg*)!=PY6so;y;;>dyYc}sBtewzwO=wo26!X2utBucx{(B#6;a%iz`^I*4 z^VSDqR#a*yE9^eulze}{hV-w|W|F3{`6p_QgR?6a&slmdnVv3VFm_t2R+lwvX<0UB zQ`JhzUwa-$cI!I&ANA4Sq>uhP>m$X(pGNGl*~Rean~vOP@VAr4uWlXG2Nuyp=X5i} zG*x=EDQU1AZ+|@6yoTi3<73wCSx&ei5KZJCoKU=M1m`v`_9G-ani=dLWP&(x4h0W7 z@N+~Co?k?qcp&dsSotz_I6VWdEN^G3E=q12TdLwoNlJ~@KqID?#3V6>* zSd{STIBW9N_^a_w`bP=l2`;M%*7k%fpOes%@T!ELm+;RL-%E7Tk0fku>2B$y<1KQG zEtgS#w&jNM1^O&zim%5cWXmX+9UB&n%QDxt#kV2CjZp_(1J(0vNLXzf+MlAGfX_?# zdzhRk^~L`ZFc<$WU_SmTU`4`p;9bgjmHD4(9aegPS(UXXTTd%}s5x%io+HXW%-!p5 z8~tkJan#=MYJVPChc0h=wI4=)9(Mazua=BHgM8n=d$rl;?%)Z~ve{^2HEBO!FySGZ5|+X$hwRK6}lWNZb_(Cw0>~ zg%1wm#M;slpZ?+dPwB!a2A%q1CDmrNgA5W)A_CM6VVxEgVR7nV+`)?khYaBlWx-A3 zfyJft5+OFF3XW+}NjOV^He@%{E^0q0g>)$SAKH7X?zD z2w2^^nd)A32ETOGYupXA?w2OL4CQ46fSY}1qjHt6VZnRXLuwgt+mV`$sic*%h(8yi) zn}l-c!HHA3x&prDO8J6#A=Z`ghEd;}zTfcon_N0<0AvGdnnCBLPa2}kYtY{tUV|md z=0)L)hG}?%8CVSOA-k?e-EIgH2=_y9P{i(m#UO`_4(o#IIDh}lA-cc3qLaK+4;c1fu6hzY$M6(#Q^lL7&oU==&wdR}b6b8lF z4w^F^ePv@FTT@uh#(AM(6VKWcHQgvKYW5n9dx>yR6l(>iJ|u4eEQl4u-DLskq*>jt z*bmf+eJMzx6!9IvTB|pCUXTrma77IXC$_wkvc0_x^!?`8)1PJy;Otqg%4=f zj2W$FP%R<$0z6m@(?zy8?_ap6f&|4jr_9elXL836699X?`pyBZp3D*)@@$r{#aX{X;q2)B1qQaO;pBMHf)(QAq1 zr~m5S>F07i-Hk;Ja99ZJ`(xEfLR?`Z?tt>b%I1W{jCoXLNJL3a#|5_dmy?|2}= zEM0x>BkMknx{qP7D{e98KF|Sr9G7sK#m&m%tlRoAesu151YeFJ@?5M3DnfICTgP2S z*ZVuU|ISW@+I*+mPqbU1u3#&xfBZRB?ayR^kIOUVeH>veM(#OpX;rwq;GD6zYT-1e z+^tYc*8Sp1^ngMKGlNG91A|AG`?O<2nZAL{v25RPrm)f{L}55v7#Qjw&a4pC6iSB< z620DL$X&$O(_Xls6>QC%cchT24rZZ6=SKqnHl^Fh?QXDZdmto81;6U?sghA0Ol4J1 zB9FecRq=je(XLQjRQeF&Q-UYs$_+HN$U*aQ*8gn@pO0s7|K}L)B+){CDqni&M*8iq zUmgF_FR9yazJ1pZm}zR{QGORZ8dx?|!dJCNLLR%h_1*hP9dpV4PawzKMEGofrLj9VZ;@$&XF84`K7N7dIvd!# zu15w?dKka0Spqx>e~?F%c$Vf+p9VaIGG8yo-g?K4JQP`X%S0dbYMg5ciIvzXKm}4Y zvLHv7z6B8|t-w3*br4ZHM>3Z5H#XYq9!3(-_1Ja@RiKjtD)wikCX(KSN(yCyzXAMe z1va2j#P&)+KLu}O!;7(;YT(JZpRN9wz~36;eHgqJxLxnZJXyq(nc(KWIzi8)W3Ol7 zsbM^GfMwL1^^u|?DBxo;FJ0iB0bNOQvG=UPL$jtOyer_HX)8`eM6TkmA9`c~u^*%k zXFWc)7VF?!o@?)~%Yd}mJY<;AuLgTLp;0s&2ho7ERU^-4i*2^okmMPMO>K<3j2Sa9 eVil{U(bAjwFw76{|B2Is6a%sQ(+*$e|Aa diff --git a/Mono.Cecil/Test/Resources/cs/CustomAttributes.cs b/Mono.Cecil/Test/Resources/cs/CustomAttributes.cs deleted file mode 100644 index 4c52c7c51..000000000 --- a/Mono.Cecil/Test/Resources/cs/CustomAttributes.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; - -[assembly: Foo ("bingo")] - -[assembly: TypeForwardedTo (typeof (System.Diagnostics.DebuggableAttribute))] - -enum Bingo : short { - Fuel = 2, - Binga = 4, -} - -/* -in System.Security.AccessControl - - [Flags] - public enum AceFlags : byte { - None = 0, - ObjectInherit = 0x01, - ContainerInherit = 0x02, - NoPropagateInherit = 0x04, - InheritOnly = 0x08, - InheritanceFlags = ObjectInherit | ContainerInherit | NoPropagateInherit | InheritOnly, - Inherited = 0x10, - SuccessfulAccess = 0x40, - FailedAccess = 0x80, - AuditFlags = SuccessfulAccess | FailedAccess, - } -*/ - -class FooAttribute : Attribute { - - internal class Token { - } - - public FooAttribute () - { - } - - public FooAttribute (string str) - { - } - - public FooAttribute (sbyte a, byte b, bool c, bool d, ushort e, short f, char g) - { - } - - public FooAttribute (int a, uint b, float c, long d, ulong e, double f) - { - } - - public FooAttribute (char [] chars) - { - } - - public FooAttribute (object a, object b) - { - } - - public FooAttribute (Bingo bingo) - { - } - - public FooAttribute (System.Security.AccessControl.AceFlags flags) - { - } - - public FooAttribute (Type type) - { - } - - public int Bang { get { return 0; } set {} } - public string Fiou { get { return "fiou"; } set {} } - - public object Pan; - public string [] PanPan; - - public Type Chose; -} - -[Foo ("bar")] -class Hamster { -} - -[Foo ((string) null)] -class Dentist { -} - -[Foo (-12, 242, true, false, 4242, -1983, 'c')] -class Steven { -} - -[Foo (-100000, 200000, 12.12f, long.MaxValue, ulong.MaxValue, 64.646464)] -class Seagull { -} - -[Foo (new char [] { 'c', 'e', 'c', 'i', 'l' })] -class Rifle { -} - -[Foo ("2", 2)] -class Worm { -} - -[Foo (new object [] { "2", 2, 'c' }, new object [] { new object [] { 1, 2, 3}, null })] -class Sheep { -} - -[Foo (Bang = 42, PanPan = new string [] { "yo", "yo" }, Pan = new object [] { 1, "2", '3' }, Fiou = null)] -class Angola { -} - -[Foo (Pan = "fiouuu")] -class BoxedStringField { -} - -[Foo (Bingo.Fuel)] -class Zero { -} - -[Foo (System.Security.AccessControl.AceFlags.NoPropagateInherit)] -class Ace { -} - -[Foo (new object [] { Bingo.Fuel, Bingo.Binga }, null, Pan = System.Security.AccessControl.AceFlags.NoPropagateInherit)] -class Bzzz { -} - -[Foo (typeof (Bingo))] -class Typed { -} - -[Foo (typeof (FooAttribute.Token))] -class NestedTyped { -} - -[Foo (Chose = typeof (Typed))] -class Truc { -} - -[Foo (Chose = (Type) null)] -class Machin { -} - -[Foo (typeof (Dictionary<,>))] -class OpenGeneric { -} - -[Foo (typeof (Dictionary[,]>))] -class ClosedGeneric { -} diff --git a/Mono.Cecil/Test/Resources/cs/Events.cs b/Mono.Cecil/Test/Resources/cs/Events.cs deleted file mode 100644 index 22311060f..000000000 --- a/Mono.Cecil/Test/Resources/cs/Events.cs +++ /dev/null @@ -1,8 +0,0 @@ -using System; - -delegate void Pan (object sender, EventArgs args); - -abstract class Foo { - - public abstract event Pan Bar; -} diff --git a/Mono.Cecil/Test/Resources/cs/Fields.cs b/Mono.Cecil/Test/Resources/cs/Fields.cs deleted file mode 100644 index b85a57d1c..000000000 --- a/Mono.Cecil/Test/Resources/cs/Fields.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -class Foo { - Bar bar; -} - -class Bar { - volatile int oiseau; -} - -class Baz { - bool @bool; - char @char; - sbyte @sbyte; - byte @byte; - short int16; - ushort uint16; - int int32; - uint uint32; - long int64; - ulong uint64; - float single; - double @double; - string @string; - object @object; -} - -enum Pim { - Pam = 1, - Poum = 2, -} - -class PanPan { - - public const PanPan Peter = null; - public const string QQ = "qq"; - public const string nil = null; - public const object obj = null; - public const int [] ints = null; -} diff --git a/Mono.Cecil/Test/Resources/cs/Generics.cs b/Mono.Cecil/Test/Resources/cs/Generics.cs deleted file mode 100644 index 3f6b1f966..000000000 --- a/Mono.Cecil/Test/Resources/cs/Generics.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System; -using System.Collections.Generic; - -class Foo {} - -abstract class Bar { - - T bang; - - public abstract Bar Self (); - - public abstract Bar SelfString (); -} - -abstract class Baz { - - public abstract TBang Gazonk (object o); - - public abstract Bar Gazoo (); -} - -class Zap {} -interface IZoom {} - -class Bongo where T : Zap, IZoom { - - enum Dang { - Ding = 2, - Dong = 12, - } -} - -class Parent {} -class Child : Parent { - public T [] array; -} -class TamChild : Child {} -class RecChild : Child {} - -class Tamtam { - - static void Foo (TFoo tf) - { - } - - static void Bar () - { - Foo (2); - } - - static List Beta () - { - return new List (); - } - - static List Charlie () - { - return new List (); - } -} - -class It { - - public IEnumerable> Pwow () - { - yield return new Foo (); - yield return new Foo (); - yield return new Foo (); - } - - public void ReadPwow () - { - foreach (Foo foo in Pwow ()) - Tac (foo); - } - - public void Tac (T t) - { - } -} - -class Duel where T2 : T1 where T3 : T2 {} - -class ChildReader { - - public int Read (TamChild t) - { - return t.array.Length; - } -} - -struct Nilible where T : struct { - public T t; -} - -class Null { - - public static int Compare (Nilible x, Nilible y) where T : struct - { - return Comparer.Default.Compare (x.t, y.t); - } -} - -public class DoubleFuncClass { - public void Test () { Test (); Test (); } - public void Test () { Test (); Test (); } - public void Test () { Test (); Test (); } -} - -public class DoubleFuncClass { - public void Test () { Test (); Test (); } - public void Test () { Test (); Test (); } - public void Test () { Test (); Test (); } -} - -public class LaMatrix { - public static T At (T[,] m, int i, int j) - { - return m [i, j]; - } -} diff --git a/Mono.Cecil/Test/Resources/cs/Interfaces.cs b/Mono.Cecil/Test/Resources/cs/Interfaces.cs deleted file mode 100644 index 486c268a4..000000000 --- a/Mono.Cecil/Test/Resources/cs/Interfaces.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; - -interface IFoo {} -interface IBar : IFoo {} - -abstract class Bar : IBar {} - -interface IBingo { - void Foo (); - void Bar (); -} - -class Bingo : IBingo { - - void IBingo.Foo () - { - } - - void IBingo.Bar () - { - } -} diff --git a/Mono.Cecil/Test/Resources/cs/Layouts.cs b/Mono.Cecil/Test/Resources/cs/Layouts.cs deleted file mode 100644 index 3a332fd88..000000000 --- a/Mono.Cecil/Test/Resources/cs/Layouts.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -[StructLayout (LayoutKind.Explicit, Size = 16)] -public struct Foo { - [FieldOffset (0)] public ushort Bar; - [FieldOffset (2)] public ushort Baz; - [FieldOffset (4)] public uint Gazonk; -} - -class Babar { -} - -class Locke { - public int [] integers = new int [] { 1, 2, 3, 4 }; -} diff --git a/Mono.Cecil/Test/Resources/cs/Methods.cs b/Mono.Cecil/Test/Resources/cs/Methods.cs deleted file mode 100644 index 36c0383a6..000000000 --- a/Mono.Cecil/Test/Resources/cs/Methods.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -abstract class Foo { - public abstract void Bar (int a); -} - -class Bar { - - [DllImport ("foo.dll")] - public extern static void Pan ([MarshalAs (UnmanagedType.I4)] int i); -} - -public class Baz { - - public void PrintAnswer () - { - Console.WriteLine ("answer: {0}", 42); - } -} - diff --git a/Mono.Cecil/Test/Resources/cs/NestedTypes.cs b/Mono.Cecil/Test/Resources/cs/NestedTypes.cs deleted file mode 100644 index 2129e6b25..000000000 --- a/Mono.Cecil/Test/Resources/cs/NestedTypes.cs +++ /dev/null @@ -1,16 +0,0 @@ -class Foo { - class Bar { - class Baz { - } - } -} - -class Bingo { - public class Fuel { - } - - public static Fuel GetFuel () - { - return null; - } -} diff --git a/Mono.Cecil/Test/Resources/cs/Properties.cs b/Mono.Cecil/Test/Resources/cs/Properties.cs deleted file mode 100644 index 961a81a92..000000000 --- a/Mono.Cecil/Test/Resources/cs/Properties.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -abstract class Foo { - - public abstract int Bar { get; } - public abstract string Baz { get; set; } - public abstract string Gazonk { set; } -} - -abstract class Bar { - - public abstract Foo this [int a, string s] { set; } -} - -class Baz { - - public string Bingo { get; set; } -} diff --git a/Mono.Cecil/Test/Resources/il/explicitthis.il b/Mono.Cecil/Test/Resources/il/explicitthis.il deleted file mode 100644 index 59b332769..000000000 --- a/Mono.Cecil/Test/Resources/il/explicitthis.il +++ /dev/null @@ -1,113 +0,0 @@ -.assembly extern mscorlib -{ - .ver 0:0:0:0 -} - -.assembly fptr -{ - .ver 0:0:0:0 -} -.module fptr.exe - -.method public static void Main() cil managed -{ - .entrypoint - .locals init (class MakeDecision d, method instance explicit int32 *(class MakeDecision, int32) m, int32 i) - - ldc.i4.1 - ldc.i4 42 - newobj instance void MakeDecision::.ctor(bool, int32) - stloc d - - ldc.i4.0 - stloc i - br test - -loop: - ldloc d - call instance method instance explicit int32 *(class MakeDecision, int32) MakeDecision::Decide() - stloc m - - ldloc d - ldc.i4.1 - ldloc m - calli instance int32(int32) - call void [mscorlib]System.Console::WriteLine(int32) - - ldloc i - ldc.i4.1 - add - stloc i - -test: - ldloc i - ldc.i4 10 - blt loop - - ret -} - -.class public auto ansi sealed MakeDecision - extends [mscorlib]System.Object -{ - .field private bool Oscillate - .field private int32 Value - - .method public instance method instance explicit int32 *(class MakeDecision, int32) Decide() cil managed - { - .locals init (bool t) - - ldarg.0 - ldfld bool MakeDecision::Oscillate - stloc t - - ldarg.0 - ldloc t - ldc.i4.0 - ceq - stfld bool MakeDecision::Oscillate - - ldloc t - brfalse subs - - ldftn instance int32 MakeDecision::Add(int32) - ret - - subs: - ldftn instance int32 MakeDecision::Sub(int32) - ret - } - - .method public int32 Add(int32 i) cil managed - { - ldarg.0 - ldfld int32 MakeDecision::Value - ldarg i - add - ret - } - - .method public int32 Sub(int32 i) cil managed - { - ldarg.0 - ldfld int32 MakeDecision::Value - ldarg i - sub - ret - } - - .method public hidebysig specialname rtspecialname instance void .ctor(bool s, int32 val) cil managed - { - ldarg.0 - ldarg s - stfld bool MakeDecision::Oscillate - - ldarg.0 - ldarg val - stfld int32 MakeDecision::Value - - ldarg.0 - call instance void [mscorlib]System.Object::.ctor() - ret - } -} diff --git a/Mono.Cecil/Test/Resources/il/hello.il b/Mono.Cecil/Test/Resources/il/hello.il deleted file mode 100644 index a71b8fb4b..000000000 --- a/Mono.Cecil/Test/Resources/il/hello.il +++ /dev/null @@ -1,84 +0,0 @@ -.assembly extern mscorlib -{ - .publickeytoken = (B7 7A 5C 56 19 34 E0 89) - .ver 2:0:0:0 -} - -.assembly Hello {} - -.module Hello.dll - -.class private auto ansi Foo { - - .method public specialname rtspecialname instance void .ctor () cil managed - { - ldarg.0 - call instance void [mscorlib]System.Object::.ctor () - ret - } - - .method public static void Bar (int32 a, int32 b) - { - .locals init (int32 res) - ldarg.0 - ldarg.1 - mul - stloc.0 - ldloc.0 - call void Foo::Baz (int32) - ret - } - - .method public static void Baz (int32 a) - { - ret - } - - .method public void Gazonk () - { - ldarg 0 - pop - ret - } - - .method public static void PrintEmpty () - { - ldsfld string [mscorlib]System.String::Empty - call void [mscorlib]System.Console::WriteLine(string) - ret - } - - .method public static bool TestFilter (bool b) cil managed - { - .maxstack 2 - .locals init (bool flag) - beginTry: - newobj instance void [mscorlib]System.Exception::.ctor () - throw - leave endCatch - startFilter: - pop - ldarg.0 - endfilter - startCatch: - ldc.i4.1 - stloc.0 - leave return - leave endCatch - endCatch: - L_001b: ldc.i4.0 - L_001c: stloc.0 - return: - L_001d: ldloc.0 - L_001e: ret - .try beginTry to startFilter filter startFilter handler startCatch to endCatch - } - - .method public static !!T GetState(string var, [opt] !!T defaultValue) cil managed - { - .param [2] = nullref - - ldarg.1 - ret - } -} diff --git a/Mono.Cecil/Test/Resources/il/methodspecs.il b/Mono.Cecil/Test/Resources/il/methodspecs.il deleted file mode 100644 index b8006f322..000000000 --- a/Mono.Cecil/Test/Resources/il/methodspecs.il +++ /dev/null @@ -1,43 +0,0 @@ - -.assembly extern mscorlib -{ - .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) - .ver 2:0:0:0 -} - -.assembly MethodSpecs -{ -} - -.module MethodSpecs.dll - -.class private auto ansi beforefieldinit Tamtam - extends [mscorlib]System.Object -{ - .method private hidebysig static void Foo(!!TFoo tf) cil managed - { - // Code size 1 (0x1) - .maxstack 8 - IL_0000: ret - } // end of method Tamtam::Foo - - .method private hidebysig static void Bar() cil managed - { - // Code size 7 (0x7) - .maxstack 8 - IL_0000: ldc.i4.2 - IL_0001: call void Tamtam::Foo(!!0) - IL_0006: ret - } // end of method Tamtam::Bar - - .method public hidebysig specialname rtspecialname - instance void .ctor() cil managed - { - // Code size 7 (0x7) - .maxstack 8 - IL_0000: ldarg.0 - IL_0001: call instance void [mscorlib]System.Object::.ctor() - IL_0006: ret - } // end of method Tamtam::.ctor - -} // end of class Tamtam diff --git a/Mono.Cecil/Test/Resources/il/others.il b/Mono.Cecil/Test/Resources/il/others.il deleted file mode 100644 index 60713af30..000000000 --- a/Mono.Cecil/Test/Resources/il/others.il +++ /dev/null @@ -1,81 +0,0 @@ -.assembly extern mscorlib -{ - .publickeytoken = (B7 7A 5C 56 19 34 E0 89) - .ver 2:0:0:0 -} - -.assembly Others {} - -.module Others.dll - -.class private auto ansi Others { - - .field private string _context - - .method public specialname instance string get_Context () cil managed - { - ldarg.0 - ldfld string Others::_context - ret - } - - .method public specialname instance void set_Context (string val) cil managed - { - ldarg.0 - ldarg.1 - stfld string Others::_context - ret - } - - .method public specialname instance void let_Context (string val) cil managed - { - ldarg.0 - ldarg.1 - stfld string Others::_context - ret - } - - .method public specialname instance void bet_Context (string val) cil managed - { - ldarg.0 - ldarg.1 - stfld string Others::_context - ret - } - - .property instance string Context () { - .get instance string Others::get_Context () - .set instance void Others::set_Context (string val) - .other instance void Others::let_Context (string val) - .other instance void Others::bet_Context (string val) - } - - .field private class [mscorlib]System.EventHandler _handler - - .method public specialname instance void remove_Handler (class [mscorlib]System.EventHandler) cil managed - { - ret - } - - .method public specialname instance void add_Handler (class [mscorlib]System.EventHandler) cil managed - { - ret - } - - .method public specialname instance void dang_Handler (class [mscorlib]System.EventHandler) cil managed - { - ret - } - - .method public specialname instance void fang_Handler (class [mscorlib]System.EventHandler) cil managed - { - ret - } - - .event [mscorlib]System.EventHandler Handler { - .removeon instance void Others::remove_Handler (class [mscorlib]System.EventHandler) - .addon instance void Others::add_Handler (class [mscorlib]System.EventHandler) - .other instance void Others::dang_Handler (class [mscorlib]System.EventHandler) - .other instance void Others::fang_Handler (class [mscorlib]System.EventHandler) - } -} diff --git a/Mono.Cecil/Test/Resources/il/types.il b/Mono.Cecil/Test/Resources/il/types.il deleted file mode 100644 index b230c2182..000000000 --- a/Mono.Cecil/Test/Resources/il/types.il +++ /dev/null @@ -1,58 +0,0 @@ -.assembly extern mscorlib -{ - .publickeytoken = (B7 7A 5C 56 19 34 E0 89) - .ver 2:0:0:0 -} - -.assembly Types {} - -.module Types.dll - -.class private auto ansi Types { - - .field public int32[,] rank_two - .field public int32[0...,0...] rank_two_low_bound_zero - .field public int32[-1...4] rank_one_low_bound_m1 - - .method public specialname rtspecialname instance void .ctor () cil managed - { - ldarg.0 - call instance void [mscorlib]System.Object::.ctor () - ret - } -} - -.class interface private abstract auto ansi IFoo -{ -} - -.class interface private abstract auto ansi IBar - implements IFoo -{ -} - -.class interface private abstract IBaz - implements IBar, IFoo -{ -} - -.class private Fields { - - .field private static literal int32 int32_int16 = int16(0x0001) - .field private static literal int16 int16_int32 = int32(0x00000001) - .field private static literal char char_int16 = int16(0x0001) - .field private static literal int16 int16_char = char(0x0073) - .field private static literal int32 int32_nullref = nullref -} - -.class public auto ansi CustomAttribute extends [mscorlib]System.Attribute -{ - .custom instance void CustomAttribute::.ctor() = () - - .method public hidebysig specialname rtspecialname instance void .ctor() - { - ldarg.0 - call instance void [mscorlib]System.Attribute::.ctor() - ret - } -} diff --git a/Mono.Cecil/Test/libs/nunit-2.4.8/license.txt b/Mono.Cecil/Test/libs/nunit-2.4.8/license.txt deleted file mode 100644 index 4beb762c9..000000000 --- a/Mono.Cecil/Test/libs/nunit-2.4.8/license.txt +++ /dev/null @@ -1,15 +0,0 @@ -Copyright 2002-2007 Charlie Poole -Copyright 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov -Copyright 2000-2002 Philip A. Craig - -This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. - -Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment (see the following) in the product documentation is required. - -Portions Copyright 2002-2007 Charlie Poole or Copyright 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov or Copyright 2000-2002 Philip A. Craig - -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. - -3. This notice may not be removed or altered from any source distribution. diff --git a/Mono.Cecil/Test/libs/nunit-2.5.10/nunit.core.dll b/Mono.Cecil/Test/libs/nunit-2.5.10/nunit.core.dll deleted file mode 100755 index a1dd69866dfe9f4a0ea9975d961b02230aa66969..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 139264 zcmeFad7LCgna7=-S)FzE%+z#G_1x1OGbCNz&2ULG+_&5ahyy4Bf*c|V)iax+-4lg^mZFFtQ$dxaz9Ay6&zE@AvmaWL4HogY5g+_pg`vOjkxe z@x&8PJn_U6Pn>!3Ij;_)AP5TlJ@QBpe4MBL9d5sm{WC}Of;IOn2<|T5x68)|PP%WG zGcUbtX6&j~dP(bo=Z-z=f-A2~H;r9*@mOo~m1CD(Id=4^XN)~Jz3Aepp`ps|p7d$Q z1i?uIaPYG?oSfzMP!R4?9Vi9CZwG>4%t5bQ5W4UfPjM&sBF8r&<6qC#i6rMwwPsq+5=gv>N5kQn`*(N{96r^$_=*%n;}xC_Z_!S8N9K|}5qv@d zPe|Yi2|OWzCnWHM1fGz<6B2kr0#8Wb2?;zQf&U*#;53b^`KPgI$RP7wm4V=jXdoyX zwD)t`SP;zhULQ4d=d~B!^|K#*?6>Fs`M)RM@}h$e9NhNaTMkWs{qg-Dx$7y*c0ISb z`s=^ic-H;f?q7HD_FJ!;JACo}pR9b~&fUM>_`}DpK5^a4Pd(;W&E`k%-uIrjjJ@rq zb>F__wpZ-;jwiqArp-6pSKs~2^;>KAeskA7wj6u;RiC=$+S~v9@CmoIeqTFa)$w=# z`N!u!|BIh^-@z9j`uySbh2UJcV>De4qjW(KRMLg~L@5L3N>b-12%>bcffW1jKqa2s zBTR-3BDi6;AaIpWG$P;}AV1>C2jgeGgr ze+~q3%3MR-T#}DnO6(m^C+i-+VX(Z*OR`LN>ab6|7_p3p&+oA?}0dh)r2Kik14rS5?HLHWAGM49!#}Vf@BrH!-I%gKolyQdXu#A;j=@`xRsN&I}?jN}Zs8N`#RnF@~tGOXehG3Bj z9V$;QBu;PX9u_y0p(ggKSWCI5y;81bP(+R^XfN+VeCR+uNE%dPVD%ZM!xn~xxDp$v z15TlJ8G?utQqmd{L|!5H;lcXg6O3xUl_-npeR4Ayi8D7JV}|Jq0XnzJRPp9*(dOR+c!~ z2Q**tLt&}h5dU#dhTh5`9C5`nVJG_vGZ|H$!2{BrBlbg3{JW9AkMK85{hh`WMIMmK z2tEkxW&EM?_D^>4wS>@+dN6|4o8bOOMYmQQjdmNa0lSU2+B}U)v9?-5DPR)Bnf>4< zIfQzcg_laQ7q6Arn#YQ%Q5RS_wZH{dnPF@WG*HqgXbuI%wWDWOY4N<@9@m;d$?M^3 z;1`pO9;%5}T&t*BRTk4FR{k)-7*lga@sB*V?@%09Lg@dBc|_OE0_XfR~+*oV+wBrqdu> z>kkfp)#2wP2l9H^@L)bgSFpozJ#Oq>tq<1YheK#c&Bgs#v9$uy^}(B-PJPy6dn6m6 zG?E^~FSgovnpjs%F$$H*)yW||Oib+uX+>#Cm2)Vt9MwfZae3?c&>cw+Ga}NZzhv5q z!$pjh%tVmsoa{GB5YYSr3{6+(1V5a=bNDk!^Bi6u1;_BD|CJqAYo~$ILq5sB)fz+1 zu~KpY#%N{O}>U-j21vJ|{X<%5$ur0Fz(OPNp zNdI=rWtHYS7ZGpCp7WEBN6%i1kP65N0$)R&)>eb!W>h+KZ53#-m>v#G)u^~MJ;Ef1 zGK~iVFhKPLXPgWYEIM@2adxw zPCy~K2f@QIov)V*+|u(GipjHyp-4wc3d&11h3>@p7Ew-YcvPjx#I|Ul5GCi6E*eaa zvUF!{!$gJ2(Yz!yr+AKLNr$ff5c?_Jst3{LbD>%-9{5Qh#nv}b+vHd={iI^+XWf@0 zimgYwFDDgSYr+ie^kVD4?#nZp&kNh?y3)n83t6yAdK^EM=H)xV(PH4I=i#!GmF8g{ zG$ImXfUH$kntS9?)j6e4=11N^TxnKNgX1kZ?%xzjQAkeUH5gwVCMOce^!W>v60;_M zl{OM5NCfr3hZ}-xfYf6pIY}vbQ74{IqxN!&UQYEdbODu_rwDSoAWZKC#azGFAO#Z``sDP0;D6(hed;=e=1RmT|=bi5_jWKOyZsN#!Pxyd=yZ?0IRL| zXDDerbDpu1K9dKXNI6W;Csb=Ti|GXfXwE>F#IqOjqD8UF=*ILS!zdTii!Go|C*#fK zohaMn*~A)e)X^n`RYwuJiNx(+IHpz74sE;;F6q#!3Spx|N%g?A>p@?s2fC!k3O$UJ zRVn=&uT&y6oYAJb{x4`-0XjQmFuZ;+Xwl-(1>_gD6}@b9=2D8*p{fdi^q9F!01UMN zdZd>NV8v|fckE=U-#YSIX~XUiq%xIo&B2$aXb#%w(_Nu-CXleL$MTI%E@4~ZSu?WH z$;T3hZOQ7&egc*;)h$l+7{gZ!rm#rDU331%X4wa?+UR8LNlD(z&)$KUaYNY)j$6ml zd^lE2oRHn%dTV`&rHWrA0(mK~Hd^z?;orcr)ud#A_~ysMwt&}*Yl|oi$aRT} z^HIf)%TU$s<*+DYF^ESuR_H-g(1#1C$UcwIPEhcyk3bdF{!QiDs;Voa)#qfXbBy-v zLLqn=0x`X9RGL>sc~;sg-T}>>VSPwqcjLo@6oqb=t~}Wp|Lnd562``AbIA^cnY^)K zqor(|?(Bs%C1Y28*KY8N-Bua9&1K((VOx4NrcDlFf^x{J34hNnenK#wSRS^erfU{F zX;HXlL9z~*tA%bV$uczG%jeT=986(&x>4{;=+e*_6JJTSW6!ArQIfa0;VVQ28To24 z1AoxKu5OCS9wb=3F>50|6{`8#D;dVl@nc7xal(zzGenc1&-t4L7dY;)3Go(5{Q?Jbc~(}C&aUy zZXyZnD4%YGWxClSMw}%aG5a^ZJ)D__dS@4~!kV22k@(vS0TL- zU?pBNk-msPwYbDdUc-_#!R#36T2IBXijx-;?WR9QhKtizK_Dy8{;(s(Qkrp}=Eh!{ z)$$=TTnZVJd~cEi6Il>jD19}0zS_$322C`ex+s?tcKC|)p(0k$06*71lUIf#1Q1asNM z;tFss0EhBpdmTYjq*`+~=iF`*d79WOp&ey)kB?Z0tJ|B-v*qnO+m}1fR(eEj04ian z&Q(bs2uA1wY|6~WSRpeNdmm=gndV2Lpuw0c56+#NugqLXm4QOa24I&_C=qwEtjrun zVdez02rF|$oBR#<`WI?&kFOYpGY>KL=+If8{{mLY>ElYWS@>W3)9eu%Q|hbZ%Yh*4dO}S9SNZ$kbk>4P3Vm=g6I`R%pFkMe(*$ z>02KJ(E3|JAEf#`)z*W8>L-J$EHlpsBmI=r#uaYn{W*Y2HFISSAU0+`y(8cYI|8u# zU81VFnP=_@`09>;bGv|X=4}RpQ>auJqzzaZeBoa zTlg7{ryl~0l|75MP4vqH^y$gLAjRpc06kOYT0*h((YKQq!cOV=_)(3!qp^ z|B6RYT;}+g+{c&m#Sj_2IfCKgV!haK*jwwxbh)|FbEP<+4#TO)`D>7LvxgpftL%Rw}9|1N?W+exsBuM?f>0eLd;YH}F%58&=Hp zjmo6B={jiFn9_R_uS3nCJWhvzTc|k^R8w;yJVrZe(Wc zoIMw;Y)kcMf3JjpT08uwZzbWPfyg_0Oo8HECQL7l-h91PT4T+`TTAI}B7eFQ5eNkq z=uQfn`(aij{q(PicD?Cj!-L+|1tC?2E^~Y*EgY#Y|tf@1%LiCaShAVk#Wb z9F*FGt(EOZ0K32{-6dq<`^8EJFT4;r*e)WWefi$lZYoq&?R;YVCLJzGhT-W(eT z$A#9nD73S2(agOli|+?Qp$7<2WyWKc_?P)4gK?IGwxPJ7w=Nn6G?vV7QyfyJs9Dm{ zUebn3YJFXmGzgY;69L*DX!P~ZlU5PxIq&EGQgArTFr1UP4 z?n+7NOiI$b&qELT=v}3?CoIOv7gV!7LXHJS0|n!-I;&vo5Kx`n94a@8>78V-wVbXo zqiG1w?MHaGL)fK<@TPu*_kfVTH-}YZ9CsnC%)C!AckvU<&_Lo^DLDozDME{bQgU23 zJbqi?c)J(M#;dXAmYS_AOTMTyn&H)Oas0wCdB4bNHWw3A2n(HQ9>MqxRJ;HS2a*qf z5Vi%L`5?jcLrO4yxkq5mV#lc0ccan|gKN3(jHSAC`wdVO>i%v}P5ripV{j16d;~y; z{uA@s<&kC~9`Uf@@ln!a3q$Fy{4wdTNUUX5R&4v%$Pew4RMH5xm*V7OihjWK-pvs& z43_TUjz~NndLJkGy72MSJL)g+=ja*lVInD}kDf!u@A!ckzfo{8^r^qB{OKnk!ICEJ zk*0h~CY4&BRLpM(+Y+wTG_@{y$F9bmARFmD5)>jUWg^STY;CarIgSVQY4r7(El?d8 z4`Zs@hYPZQVfsmt8fX4G3XTO=|H8)1r+{{jBmvwGcZlfquTclNNdYhc_|EQEsPY@= ztOq;z5?w!i1bXNuy7jlpD13OhEo!D@$D;9`x{Dom`dA}P5kC*m%%?$~`HTv8479?wep|nwp@zu}@vf16 z);P7e<>|flGMcnpmP(L*PO$zy$LHxhBP6?P5H8KqNJMge5RMT|Kkw4ZU-$t$A87J9 z6oeGn#Fb$B^*}*3*;-kkn*xk&hXkd<$qJj-1;wzf%1Eyh@nYvyOHbwpDWz3yPZ?`ywT2Jr{8HIgp@+FBY7x0d8M(*4YQnTO5QW@B#* za7O}^is5%kw@=_$dH0@vRRn|W%g}j4NUn#wN)%@iBySFZtZdS+S?+#KcVSQ;3zoeM5#=*K z*=IgaSq@dEiceSWREkq9nPDjC_9pd}^HfLp(da5V{rXOHPwUZDFuiXljHfudlGP-I zEt|MtRPgj0Lif@Uper38VQyA;jk~^hXL+1%? zP`^p$mF=ZsW_Pt^&(HNN3>L0-c6UoSvkknCQgnUMux$jsr3g_D#?7RiMNl-9_a!_r z(%rm!{iTvd>9TofT|XP6-Mt1K!_x z$oGM48ljOrs{Bqpug3>+cobQP0}8f8!$O7o1d^ACUuRwz?6!}iOPfH%h>dpsG*YU8 zYwUX$d0~Bf;|3QU7UaCgowJomK|XxkImdDz_<>B`s1@uyGcL#eGF|oGD;Vaix|JA@l{+b)m zaC$>_;r@_cm%Mo}z#pl^&3y_DodZ(>ThDH zdq!>>-a_T}06(a;xh2Rk3_d`b!(BU2J-d2D?TVun>z%{4s=QX3cv7i#Ikn^Vp6pp_ zUDJJ8UuwOq`*KLBb!+$K=q7>|Syy7qz0y3=y}6k5K{#^Tjw;P0ACu6Lx;YsxpnB3)CX z^$_S=i=(bDEiP@XFYA4oBfGV@+()cv9cvLQbCTU!T-AEIL03D5(VT~}jGeeG-}jR* zl`EeAqF{H=3wBLju*;i)F;{6WZCymJmFA+>+w56t{lK0wQMc>B9(oS$`nbuxwYJ5-dqTHXS*W28qIEa%w#%wpPoc)>8Ye(+ z_U~1VhBF3pIa^l`XMegwoC!;LDE)CR{m;5M;;TRX&v%IHrtk4M`-^@Yw^>MetR|0P z%cJ!VSvjz0NQr6S8B)2b+p*05mErcvJQa>6h*@^a`if9}lG&21D~U#JYarwYM;8q= z8`11DsTLdL0V~?uqJc2F86z~%IbW4$W99|WDH)G#0kt8K8b6e3nmteTN_(({UbV^8 z=gCygK11|(F2Td}!wvFCT8pc}RR!B@)>=(4LokSKLZA5u3Voe}7q&S4BqhtdB2};@ zo~>DQBTD}fbP6n4CglBO@riN^S@Xh+G%w7i!haH4-^A}fP_|IW!STJa&3u@$Sn)PA z=2W;fl{pDX6Cam|1cmNg03g)-1G1)T3r9K^3bLg0EMdBFq39MJT}7t&HNG{ue*DG6 zpU{h+SQNGm5923a#JMfZ;5ILy?+x3QWn1(q4ML&w-8~3nTS;)a_a!G8bKF26?d39nbL%}L=RP#Aq&tjFMt zG_RvnRu_(z*^96(M5C4EagxhJDLp*0`O5)=N9ku&2l3=sl>Rf)u(`|DMwG>Rf!3=D z&HR!GltdXun&|TS7X@VI`_IQu2UT5!s)|_pK4@jyx~O$Kd9}9hm|-Dx8cz%G9MA*9 z!FVPelR>08NA0s?A42Q5&}bxg$cXvs8x5l6-eroDvxxBCQsf%EWK|{oDM~+kRVFIx zDYAJIYmcq(xa)6tQwhY_C~sv zo9nT-KD^(E>WJm<+O_oZRMU-_rCB$SwOt1{9qC2xLn|$eBwux6Aivo5Sf3^u$>)H! z?xsj9Y~0Nvk8Pf>E*{XNdm;H(vfmnyhAXCq!d`)KNPb0{t?^Q~X7gLH%xG&QGN`*ISKRE6ISp zv42qPANgtR3ZQ7gT5=!aDp~eJVR>}sKZx(N;3I77cQpMI0L-BDwN8HfTRmA^`kzD@ zKWZq#j?(`U_V_sUll->@dr?kEs@L_bpXT=0kYf^l*l zNgk52TGwrLcLU+$RCjJqgQH|>?#aRI(X28@_C0}O#nsSvT17OZ$-$`Kv6 zv^~_^-EVcG76)_|fS%bMm?9kq5dPlE>h=x+`S$kZe%FxOrvfOqPbJ%fy*AkAX>Nat z<{vJHpEDdkVj@ZzOj21nE^5uSezVL@TxgcC7^OcoHoDtozV(>fWyUGWA~IlS*}kVZ zKF(uQn--O?lSH-$O*$+)c&7M^l2xiES$!I;7NLKpY#~QIyMFSiy>fK>Nqh&_2K+cr zWyUuM@FVI$gBLvBRjX` z%D5=l;{Z4BnejO2c$8*zd6Zp-Px%X-3~m!edZU0@TE^tUd0vLI1N`}UxcWTv8(QP2 ztg~jCdwve^jjrqny@b&5lBh>yoD&6y5tp%_LC%)8Tn$JVQCbEYX%HdribM}=Ur{f( zT?kGZQiz@`GGRDbj0MS)wVlw}R0<(Iqh9?P%&+Uc|I8$9at+YYsp0GlCMPEf30+3q zEGa}s5m)=uJjOXoEO7puWg$Rcg0oGg^PIC>KxCNvTTYlEd`!0gCBXB^6r1FBSZ;f{ccf1fjZSvOV7GC1 z^m@hmVn8~bWkwe~-*HNh#7ct>zg1dq&z)Pu1pL1~^SEQ$Ph@m=Jn`sGz6_N|r*A8H(@h>Ww`PvRhJ67_rza%t1=$f%dRc9{plB?E(Sswj_BFH{OEamtFue^m zXaKvh6Zz3kpw$cP!thjj( zcqP+%q}kZn7r{xk#5d&Mpt`h3IQ&5@Ql8?v%Oj$5C`OSt*aZ`d3A(; z*SL8%AC9+Fk>wP5% z_fijfIPpVK+3Kcj(p&1JXM4T;pcrO7FAnx|a#Jto<(8WtoBbO~Ws`@_E~}rL z7w=s=;tkmJsntW2)~LS;&eIL??4AaYjpsaGz?hr5as~m~?liA6^<$>0`M9N&&ram0 zb<bSZfZrsKT1MG?)x5b6QbRiknW;ap#7JA2O<{0rip0AHe=_2p~hj%EwTr@8pOQg!n zdb!2w)U6FMgMKnlCS)v;JBti&VH4%=_HY}@+G_Whom|&OpBOxR{D7)4*rHC&inLBy zczcJVC|Fb&l-rEw(nGU`?9rAzI+|Gpk2bm^8u_YkxRB>FRrfed-TJFGCyV*2Tfm%{ z@A@$;i$Y|+ps-+YK`bX8`&G0Ko~W;EA1zvQv2BtvT-`H$-EuDo4mv(N(^m}MME>V1 z|HzzGXWDSsP7M|eM(&WM_4Lt9oywb8%uj{v{pn*COw?I)*)c&aU?+st^a51QI`N=6 z-6OYBGM=AYUrNT@R5xrRr$O}>^T}zCyquK0CnoxM@s(f(S$EGQ^v%bRkn5`!1p6PA z$!9S5B>7&jqkItTdBLNKr*$5>?XEa*_XoU~l2qg3$TDYyazb-mY$mUsxK8X+-$`1n zTOXTxj+mF=S=%%W$t~5Zp^kr=0oqSYdzj9A2awU^eMqXK{uIdVJ&0_2pWlwos$Y2l zaPJf6_p?PEMY!k*&a2Jx=4STjap=XVAsSQW3;RAwNL^Z&BJ&(PvdNUQeU9^y#L>ku zh&rO;GhXE~o>*cdmALh7q?Q{9=2&sO^!)E1foZJt%~hNSPtS7Yo+B4}8)uxE25tSE z6dgfZzf~^7w1`cIPy`$NV53%PGGhTYeS{d>9Rje(8luvu*VNN?*^woFf&57IF-Ha2 znni+zm0Ll>WY?y~UJQU^<;0pKdqj){d*#4m!tj@YEkD%y5rJaiX=lVuzisTl5U_}%B0eHA<FT#@GqhF)xAttT;jKTUvD*H$!=oPdQY-ca^NOe04 zxy)GxMZX3V1qVy+Ovt?r72Q_l%(Ex2)@yifAj_?%xQ4^QMHbH-Zp@tpy8% ztHwqknvPOE)_+)L3z<2WWJ@C{laN?swU>g8OE2k_ueGu-d6!*zWP|d~4~w-m9?qgQ z%d}zMv7i!lQC5-#+n_4kcw;%1eU5CowySnbMti{k_CfZ?*j~SLz9=5IC!cIuJPf0?)y_-7EOuVTZ`juFnkj84CM#Bu$!Y|}7nn1vcE;WCnWu4k9d$fj5%#2fA>M9!v%0N6jNDZ%Nit zO+FVpj1YBm_!9H*T}mL$z)w%di@|R(B3GCkCWb=WFPH32A(@K*ILRvEW}0wz2~nk9 z+3;!P7KC>QS}iJH6BjX))z;^f!gfOxlXbZm*4h=*d;tfA`@p3|0$*C(4NsbX|M~*! z>4rtE)S9-)6T6X*#1csxa!0@D?XqU>u$+0s{($@8fifriRUmMj^YgYCvl6aJEkJ|_3EEGLE3 zm>1zpLqL+(^s=13mo^w~esh10Pa{WxWWRTjAo(|!uc_;d)cB*szCO$7L%EDLT1Ic_ z&**qE5=afCad|$6j~b2Lb_9PnBmMgv>HmSf(AM+a=)-jFieM&Hv!L5*{Rw2>l0uuy z8m=~mYt1pv<<`<udY)*QvHSMAymTDG+Cn|-wC3f1tK?07-A`TG8X ztqEFxCe!c^!HurHyS*Vn^OSJ&)B6*!R&4`v9sK2Hkw^N}jHwy4X(=)N6%n_VD~5w= zWjeSr{c04@`3BFmwqGr-*<=05#bXwb=rsP`@hE>AfuGOc9Di5wM<-&tte?lTxMtU> zY3NKP)3@5|)2H?;j^X(5-Gbs+GRAzWP5+$_M1RezTl z1}E#GHI4Po-WJdX09t!EnjBC>jn8eTGbK}dO{>AZSIoP%7 z#+RB;sg|W}K3^vHOj|x;xF~FdyY#fM0F0r#9`8DOdb0?RbeSwhA-=TI9-!*1XCJx zQw+~V6P-U+TP+1#fUM31y$Ou}*H|Ac6AeYYFWWP7_3;b>9 zZF0EMX&KO@u^VpG*QL(gv9N*hTev-?GcHUx8r+&7ncFDv9_Xg5Ot{0DY68^5 zBLJ_{nA**|4+kIla-iu^#(i!t0Nsk_a(nXtk{WW#=8=PwOQTlW$NObGi6ulZ~MV_U>{}+1>sIYKk(xI-f@)NRCBETDOQEy-j6K z(GJOyYaD@B8!$CR+Shc`sy;Tb3eROOCqQ6w^-|kCDTQjZ-U2m-yQ8glx9^z>(Gux5F35Xg3cfn!Pt!K{9LC996nvVaLg z^zC3_pQ+NRsrStYTpzS9BBEmTo=9VQB7A1R1%-W(laSI&GEp!Zpv&xz2lq0&#B@dL zcI9*!Q9-$Nm%`W&!lm>GdwO3F?zrmJO(!6aLNJ5+;3>hcbg+^f33hrEKMbX*^Dr0A z`L}p%)5tII3dapGjn?PLbSoFew7%*B)#Xm#Eb`k~JmC9m4}`j8y$z1wcy5mCgW=NjXqEeq$X%o1WR5_Fg=Y=gDfG)O+r3@3rGSLo zU-0N@wl5FnVc}k7ionZmPVz!(R`6aK}ToWvgsjqV2>3T*YhkopoFP>n_sT4HD5k&)A>4QF!KS z{54T2hl(q<{(OR4e|Ee*8K_6;p3ynw zH>+5`zd8zTfS0y-!EJK0_PPq;e7k@(#d=jH_ra~uvlORnrK?Qr8mA}mWc7DF%lHVo zvhAH&H<+Hns~jRt2XaKDwE;o0f`ba!l>|>|?0lWVt!%Q@%%`*K4fruT6V9Frt$FvP z=WtHj8HZW)(d2Ka|0p?!U)x>W=mSgyyU@2yx;1DrV_>H8yBnnLQ0}@xim{aKovjva z%UI3bxrsjUpLWEE@W4ONY#$z;Wm2gy`P|hrr^C$J)>ew#NY1eEuLzI&Fzc~bE%o6R z;blJjQNqi8_)mma`0%l#!Bs1L_&UO?Ed22BoU-$|)@zH0k~7Kbz{_E!K6Fe8@eTUF zJ$W9)A67N^Du1l`2h7g|(|BJv(5Fx-zJV;LFPI$S-s7hsuk=*l!SowKaQYxG1~StI zW4KVBsMJ{-n&pMX|6wIRAc&UDvlZ9fO`6MQL4;2}r+iLUKEd>q$et!sIw-QNTb;p6 zMs{hBEc4Mg7Tt7zq!97!Q?vSaV|mP1@=UQPmR98sRNaLDiPJbS%lIQE1$3#>`Yo}I zo8;`ddrha`)E_sRkLwUuY%N+!!@HBLWMGurd2quPWT&x?8@5eRunHp@1Y22GFD}1X za{z0%G0j*=m<8b)Rem%K6NN^O-!mca84ae(mgA>($Z><3E}5d_KGTyRu1N#=$0B$^ zfK5eamEncWq`uHrf$d7y;j+63c5&I==~_-0`1?Cu!LuQn2z-qp+CsO-Yf*hsMz&O6 zlnv2>=2gWO`}F!nu~xI0jsyy{=?5KT*vv*+ka{I?|GZ#crJj1+ToZ{YKDJ)GC?8+07E6w{X z&F$1P)2Fj{@n$D*x?3*DqYwZ6efS^vi})Yx!~f9E_?kD+?8~h93AE}Mr$^`q7v2rF zYt6m=9!-2D)(KPEJGu5A_?(HDAZcu2eLSIto9SSX9PUv=p zHYp@^Xnj>7y01d3w1UvzD0GTKVy|_JLSm`)BZb69YvoEp?@{Okh2BeO+i~3UJ+PaC7uUR^>^yV>` z;?Vsz`b@uSSQ^d0jHJ&{P9im{pKNRp+1*Q*T0S3}C!dDP=QhhH`7n9T32jzCj)wMe zFt(8Yg1>!{V-oFpl7Dd*0&wati4Q+uHE0cby^~Y{4xN&Zcd+>l#zyXbqr^N2#DONGD`*@1ghSjz7hRrj|Ujv>o=pzRHyB=Xx zaYbmm-6x8z*E;6D%Ol&C<+nI;Ld2+#bVRsldkx%d-(CK`wNC->&W9%#BJ9pR2Et}k zI-evMjNdXJZshO^9>?T%0P>iSJo@iudjSH5aT{O!e{?sSvXJ|!A&fS()K+I_@jEJE z?`}5FOCEO`Tz@y4$Ib3$yO5at-E2PkG4E!ppolM#403m}xrxv0QZ~ChkZaj+F>jN> zz&F+8^0y0e@ZSogqB{@S;Bmc7nr<3gGnpX|v3;588c9==napoAwp7Zata-;N_S7z< zJ@8I+m$Am~IIJ5025VOMQO+AFPd3VV8{uq}^IpQ)DCZu+*(m3`gtJl3&k1LvoZk}8 zMmc{b>_$0jTctI@Rjd8zXN2&YvVU2rmx_PcT`yJtGNG56f0@?HkbgN^FAMz3`FdIC zUoO?lBLA{UFLnR&YP~G>FCWm$uz&fSUPk=O*Y&c*zx+TinN%LqOD2|I=_QlPpY)Om zrZC2flMG`!3EIoMUcx=MvEA+=N>Dy#1x*5tus?<^_NkR=o-8rgv6koXq@Dvj!vJjv za4&+-^7k$Ne###HlL4+U!2UhJa}9u$G7P#n zXbkrNsR6;bM7 zpxN>G&$G8QY|9L$2&KZrT(x;#4nSM1Hc!q0@Y<`*gL8o807^DDm^seYa$}n%tTpSc z1?W;_vy<*{Z}&ELoIYF`I+d)omzaK@7PK^T9n1`~*~U0yeD9_#8KoaZc;8F%5!VAD zLXUkXhU zcdvWjxoDYD>qXCMollavzvaF4_FV{3dj&h2_+aK%(68kEukV9pNw3MSamRW1EUD=2 zG3}MkX9(LpPxN~gYCiH1qa#1Te8aFUJR>CfD}keX>hDF1QKLOI<)Uva;}s} zzOAc+m$^Fl9J!cexwEdVm#8o^i^A&ST_z+>&!96eoDX=zd_cVBos*+NI|E-nAMmF6 zfVa#Ce02}VmF|DVTSq1EE}++?Ly!~sAZlHygnQDxX_wi>_dH&2&gq?Kz2b4v;tKbj zZtd;e)h-=>CbY2DtVLfdH!0(;clwKudv*EK0z!$?BgmU+y!`1eTU*!`ZyU)5!0xJg zyrvayH?Dm9lgJCPViVZ+Asu6b;LS?G8akI;@qo;kohEld#Hw_i7F0Nu$H@0~uXKHt%8C@S z#^tv&eO9aYaeE}F?of2RZFPSQ<6-+6cDyl24PN7T`@Ag2YfMUxd)ctVh;J*NnIdte zx>}>Uvg4l_Pa1P*ShFPe@eZrK`?H#o?j8j#<|z7T?dE9NQp*k%Ph;4L-nX*WAl^O< zJ(_Qqo@wMXCW8-Vpp=?1S=6Ub(nK~<*g8;^OTcv%in$hwI3XBS;r1w&x1_H{3RbZN zHnAQG4f!8J8Vq!=jO}H$dsGZ~U#T0dZ)mO&13NW=4VSVdPK$X&(qW1Jqd~mY@jq+A z|0~}ZG6B1Rxrm#9=M%{NULc~!SUYQs z1)I6DQ9A9T8uJNH%^ERzsmzM((F=9gL+}Pmli+T5*DS$rgeJMxKjNpDCp7aTOzd?W zUV9^g%-Y2Y?&Z(`0GQkNMJY*K4(*Gm)#lzhf~MLV3qsB(a*NolVqyC-OrE2^_pY9P zJo95^0AtW|`%#tzODBV6R0Q*31^XWKn~YcN*BC%Xm)e`vz&l%0FVqLO)MDE&U79GB zOay$ik#hvJEE-$gRkYl^@5FZXdnRiy&k?&~&dXZ+f%buqEta2~4%wB)LyfFb?WzFt zOyrGVb?w`sj{izfYqF?j9J3Y@g%S^3HdUD~)wEQ(VJ(FDj%WYB~)^%uT0R8~JO%Z&iM?U!dqM zK3~L0;q|a;s^zXDcdHABqXbMURo&Yuys=U3PVh(5H-OKkw9i0c=9`eOYAy!cVsT~z zb8uCT9OE(R_*8y>0jmuS8D5ReMEUV$f$$xfu9Vr)Ip*yWHkNn9{w^HJD7|8ALE=W%%v8+8*N&fVce;PNzY$l zeq`(Ag8v28oa}f@w(WEF?Xc8;^l)nrf}iL2=T;GFq&jMShpe5!k-d2m z@EZmHKbnJAi&Qg#EO(zZI$wf=+*nhu-LXgwBtKRX+?di>flfIaCw>`tnoxJ%L?U}P zj(n-{+@@A+ys78R8xcL$w@XL#UAt+2B~L#$Uj3?1ucul^ZoJC5a?X+;zk!2axoL(me$cN1^f8t$fbZHAfvRY^%hh=@zo|-!;GtST+lH&zdjO z&!S>BJ2$Qr%w106g`z%XCmZoYD#6FgM!c4?pel&g<+58Z7rU6MBMESf``aW--z*(o zj&?d`3w9HVy91g+TK)w)wBC_iIV+`yyQSGtKdwjJ;;P%ZdM3NvnGb_eGUdmHXLY;- zs*qqHc;54a+8P2O;TOHwIxcJrr@zu4z?J2tYxC3}s&o!O%4~e;>N@#OR`P624qW@{ z(DAl%r9NnhC;B%ly>)2-tF7n2`OI4=KexmQ84>7_zEu?!r?>G~Gp0}MfXzw!zZO^u zJG#V5U{O0?0}$wH#I{1&eOJBr{}y5{{@3>I z%dYl3#(tawotz24*rwwG^ zI8c1<8wYyre&gUbmgs-?je~jVeH^~lg~{Wlci3Ox&(UiuuQiqIiwyHncWeF&gLV7M zEa}{QXm_E#!^u|ZbKf^${zo@-SP8Nlq@7?L(B>plt2hVfebS(NwRV3^xct`!TxVkW z%hu5zXbo1k-TbY-`oC>3HTF+f_c>LhR>-2fsn$ zKHEI#@)g{WGs4+Z-vho*g5qE1YSOYF1Ru-4%{{)QN3xYnI^VV+K1rqX9R)`^-_>KL zf#P(&r(mOVzu_?JQR#f&f(#QYogY~64h4T`!FMY7BZ6XBeB9~S=j@&HG(_rGA zmD#a+FAoVo$4OjQB6}o=-I|v9r*3W!zfJZ>LhbUpSC5Y1j@L0UqgT_3%sd%@sWLRN zH(%&!s&eL|DR_>iUK1%-M$-WAnxCem)uow}so;-arow)7$?qgnUmlYwZsLwIEy#Y3 zU+3%6-BGA1A-88deYZ-&mI4F0Tx~P?3^R&+&WE3Mw1rG}teuB#wIM4fT|wkpl)(~w z0d*==QoR3F~tG0gE^B_V?m;M)&6C0A?JqbH~SP&c3WDsU5 z_~5;@RgY5=q@0IT1gYjBH9>~*kVS&ntwtH;1%fOT&iFl;$H#A4$ERlgqbn1YxsjFG z4U>;z+!LlBpu$X|l8c+ac$Z|I$N8Xev@45Qn#C^S7!s5ELl)yFc9h4{$ivcyHkp#F zgz+rt!OCw^itDa8njH2>nniLoz@nP+V3fPVwMUG2HT{&E5^=hpvvrK)+!(+Yr>leX zEz-fC5^qr&|84TJ==OV2XFKuw2+ulL&V7VOWW%<8N7D~WyWLA`ueJF3pH*obK<5|Y z^j-myqX_C)Nz8!Jk{TqvTgf%%4udhDzfWvq7tB5>Sd_AoeBN5PaC3IpV$7HISUra} zm(;vkcTx9#P)XLB_O#UW9#UxvoxkrE%6%w^?=9pYVT`_Xqzk z^BxQqg+cIMl{;$PjHLYhRMh$iFAbZls=9fS*8K+g2rA=lIg8Sd5=KYt?8*YX{Bc<0 zAkL=;m?UMZ|Hp`);AZrX^K@_NCtM0GRqMcuRxX59<6e+^c;b4cpX51n1Nu5t*0Fph zu|roCpYjMI=T690r~gc?ai*LOx8k;o4+f=)A+FHOmRvORNKPB@2iPM2Au-5RB&u2t z>D)lFby^y7T*MQx7W+w(epraiv10@*`D>NDXgqVr9Xo}ffPcfiFIo9lFp~}(*QTN) z@Ep_S^B*cj(8L5~F}IK-C*?;uCvQ9>DR!He*}Msg(?^44fA;+d8Y-$0Tmg#- zPiDN`L0-awe}unbV9W$|;kw`YG~o1Qv?B?d(XKTkt2-C=V&~kjYT8LYuX`qYJMCL_ z+`4UYtd3rbXgVU7t&YlWUP*qi(7W3u>ij||*iBk>-fsSbz-|4SJ7Hftbsk6_it_Ts zLVi%i&+u?obBH+uy(OHqpx!Ye@{45aH><3UK>ArQ%%ID!RYsAsu(CPo%Z6a|E{883 z{pF)0oqrK$QRkoZD0Kc=kJe=YbA(JqS2jfmyz@(dvp?sj^=~voHyi77{TyQP`LSml z{?gBpY@LtQ927N-DLf=_1omII0|7S`(YhA6BVhC7cFx0pCMRf~5w^vp>vAVOrF)ga z;BK$_A~?y-ce*G}XByu>%w_wJkit&))?eH=BFd7Dl{{>#zzKq@Q2KNqllt}=<%~^Q z_F=XK4ma7?u=L%ul?a-dtLmz3-e+;Je8QHZ_&yq%nZI;ROpTv_)tWHk$p2SBtbb4+ zw+oa?uC4@68CU7}Lc9CY99Uv?%{K`>bQqM5iq=o|*G5+QQp{+&l(R~y*syI?-&W11 zzwc7f0>q1CO57MG%L^-!#`n9ANUr22dJcsbPVD>lAZ`o}6YD*oa z?AC~9c0mB0e>Fbz8>Q@(!@2v?<4#aWU575Y$yS(e>~bsbfwH;Wv{E9Lm1lZm)>M>c z1!>fV(PA-xk~!Z&FX^tv4DIJH;O%C3XKg#9znWEM)QI$j0JlyX`p75!ylWOZ>BA>I zY;kY6IDHccVYbCtaT`tq0%##B#=Q@tDh&=d$7B6fLrT97yZKishAQS7t)jc=NHL?? zy$^9|sk=GAng^=iyCZ^wOG2&0+2sOUAaTCk*HdjC24b_Ae!=MKh|>;4?P4lNvYEet z!lw^(JB7@WFrHo7Q~{YjtL_&5mD@+lxl5bMHg&~?PvEN`4$7q8Kj%KX>WGf_kBMuafPAa3qQ?T}uSv z?nO%oe)^TLRNlM=-S_u^i0~pvbT1TQ&GWKy{x+cuqk9t&7{`@2zh!3{-3xudSX<8D z<|7)zc83pH=_(()MQ6BB#AEq5d!;wVsrQ|nKHe1il zC&SYWqIsgogOMqz-ZWpTe@6+Td7?SObzT4||vjw027rF!~&sc=x>aOWseea$3~GVEL~+99cS zjw03TEY&A=OjTefR43ZDGn_AdT^w$^XFmLsqj})q?;mdaKS2AT2rTmy%J3w74~X+>Pg|YZdFX}8TMo~ zwK7-QsfB$-LFFBz;&TX=23>nfzl3r2MW7EGv~zkNbbXlYHXc#>ce3Bb#&Bu+(6XjXkOzj#_44H4^cz6X#yK6`M2`oP5_;}GC$+?v%& zhUe4$c;+k8CidNw)2|YeVx(VFAVXB4xEQ|5XVqfQkC|*Pd?eqWXD)|cLcW|jid(gw zdW2j03w>)b)b~g&Cb-S}tv2=d^=%Fyx~>-fbId4IR-p z-j)Z>zR(M^d_#F7AJi~~)~>mqM6-X8Ds}fy3Ro`Ayc;Hlng>L)XoipFhAc0f zrP)WZY~vl+*BLf}Q!Ega$M4y(NvwdQISH+GJk4ZIWLq~Yr0ly#UL`B0!~)Ef>VhFf zg#r0DcyM3C0<;7tsdpyNHe;1=8K>V(nt0n=$-}z6DQ>K1i-v}o*+wspMii!R1T847 zIXK-$q`MLHe7g~pDU{hi!id{aII%D+CudWX*m`))4cWFYNNhi+kzPR0mCfNV z;=prW+;>4a{T5U>U1CxgwfMtu@8}e5$7K3#Cn1YK3I%t!uA75ujsPenw^25`ao0gP zJ@h9em=}T1dBZ~zEtyLiMaxrkH<;mYoamyN0B|RHZo< zZIZa`a^*^MakOc*-cGi-LhhWy1<*WJG_gTaep{2EM6z$}Y&|a49u+@x!yR+@r)*c< zJGQ~;#1glexOG2Gx;N9Ql?s}o+=9lI?grVjTEA1nS9@z6kPuRX>Y4zXms$)j()1vj zMd7>w@=k|*j?Kj5ruE|QUr<$wz7cy539oKhOf*!}Na<-eL zD5y`jy2!~&rnualrCf+TXnRvP%ck0H#DgeaX0;`!H} zG#n&-Hvs-;LUBG)4Wq>a$+N&UFNEbC|J7*b_D{y{;o=&lTFI&WP`TSt*(JtuVpjAL zwH|~opK$stGAmn!yRE^y?Afa$%k3%-k>$?6`@0#jQf^lE7IpCK>#A3BQ^d5*K|e)Y zaV~&Z&=hgSP4{xCRpwKbm=r!&g?Io1B8#w1vNTKW`O0?J%Ex*Q2w3Spj)d=K*elJW zJs-omcyjZYDvI_$QR7mo708c@l))A^i*)6yme(AkOh_=r&MX_A4>Zhg5!(CzBGb)A zPP8W?J}=sMxP%L#J)|o!eyrB;LHAYSJ`DC9c${!`~MJ=4#fT=r|{%t4B=H>3Q429&WAcH24@GSRXhCbMl(d^sR2(#RZk(wZjnFk-yi)tA6>|e1M2XGX~9O!z7vYchoroHH$FO_<*&hW?YE`N zlAL?7;iW2B>vzy~fXU}at^J$bx97O?_CD?zVf(+xV&ZgnG~Zn)_+qf_E7=nVWo2Ub zOguT66~W%tWS^_Bw|e%e3cZzd%1G~e`96BH@ggN>Dn1L?y+)U6QA9SG8?rg zrLlBwx%bKFRh0eG7!)@NB=;+Q0Pb@4-W_EFfd>Iv*&P{; z&6bwZ?Lf7PMsxoO!Q7FnR0$Yah=cDlq-o60GA%eNSrrZ!F(Q6(jXE%+LE;TpxV0_+ zMn%oz-@^w(RMLW-lgXfuO9#u&HK1YGClQ@8GtdDChacO5tr96>B`cp_` z1sM%ue~VOHNPk9zH^+ta=edlA;<#YfKy^^F0_FIHF#kb6)}zJEb?C=g6vh^6hvKwB zxa{!C=~7XJm&Srh4i2LcyRCT`ZZ+7;9X|j)j+q8*Py`01a2+< zxdR8>?)nbhhw}@@2u!1BjX*V$9uIv557shZL(=bZz-cu1TFek*42OA&Mz>QT#b;W6DbqgVXb%z@XC)Y$1%c4}dbLUr9 z_h#Wo8TQF4?I@!a6L}fE68h!F-es+^yJR~hct&4>bCiJLv75D@FN2Tu;g1WS(a=t0 zf8B=`f#&P#Hx$NK?uLJ)^d4SHo=Zb!ik>SrZCzyAuZwhV>)f%V`%dOc`rzB4RNr|` z&e7{w5G8z`=&ZxaJT>jZ`P#~5*3 z`YA?rGV$~vE^l$C*4W&fO&(IRQ$UbNHUBeGEOUVI(IyU2LqF;CX?If7P5de0)}o&+ zIweewz;1Qqn`Ep0&ga<(k9&*99lztJYr5o`9UR#$l5UP+ay&BE$T?+`E1h5D-xg#y z56L4#w&syY4s+!3S<54Np4^HkTN-5S!Vn@(t_E6bo`-BT*kN824dM^86EqLe$CO)! za7f(P(s~UlVmEPGKg`#V7gF8{zGLdhG!<%W@hNiDInbrK%8Q|SukkW71Dh2N0=jkq zFZ&@KR~LL~kGkNLBnPjRw;wa~ogO5?59x|?KK315?NxE?=%4kI@`OI8JVzKZS$~C| zO!$T{;@~p*|T8bs2&Z%$y6K+>GYFv1Fk}D5R%QIKE8c>Q-vN*r;&F zTglTKIUzNf5mx@bBXuu@)`3|%>l1yyD%;OO8B67s#NXQC`l^ov>wn=~8I5Z-F8{pg z1e0v9QA?%9Rr;ak{(i@rW*<0TT6DCMP0)2cfo2{T`YinJBaK_l<5Jvb{=#myaq@ON zEe?)(n%m2!u@{EL@3(CKnF4dP=J#Su-7wP=3&QsQ0L67@ECbZ-08zR&>AqlPu`AIu zMvobzUuz6cj`Xhe%tq+VQ{&_s7kf+)`H!l)XEvcsw?v-n;@t3#_xu&1XHWr|*xf$y zQI$)4g#P=WVgL6*#cR&?cs2K9yf;8jW4wdiaLEk|C&t}y$-k}44upcL z_6mK``0!?o6AH|^FeZ37wBa@j-lge(g4;$F=*?0%8RoNPn0IKO!v(>5El>jid?J~U z^~3c+6qd^oy1lICa5YfpThDy9sZ<_)3yLwiaj5LN5JkPYsIX1I>2*-9_xZkGx3o(} z?QRA+{tc|!);cax^H3Ui(ZP#wx~f!uwR#Fs7}C70wj9K8%4LInxqY7tuieOht6Td? zkER#xNWJ{~F?yF`Wqm~dqKo{x?;@!$nLLy0(He~dJ3On!nb+`0UMo$q<(DD8nPC>B z+-&(_;HC>PMCJ~(tK2PxwB3Z2I_xn!-%lIgQZHC+J-#*lHm&iX2-wxjTC3TWV&4SFVDh*9z*9zVUK)Vb-MvKNbMht1%|yLz_aWt8{tTzOBV zZ1B7X8p2`o<^^txYt66d_{Am6%wpJ)gN_8sZqAgl^=#zd!_J_aZG!cljqF{aSS)Qd zoiXhwn05Rs+$i(59gpL|ZYMh))u-(Rk6#v#tRdd~bkAO$nb-)X?nfTCIdZndNVoM1 z-#e)dzMQmgBW*aQ=6dtTNZrA+E9Bn`diO`x+28eu6eQ|^uLmpRdN3gZoY zrj50rXRoR=+V)Su7(!liND@_3{2Io!#Qc&YMuVjDYkN^}Dtvv#1?NAAE3)Kt zV&aR2e6~x;2Xn))s~Y(nPPZm$lCkYJBviHG~nkLI`-*kEtlWq?-g zeoBaWpU^(c^R-@lWNmBHGii{9rJa^a7deF;&$fvQmKg)+xV@S_pUR`<^L3Yx;(b2n z=ksy!8)zZx?Bt|-XHy9WU$T4!%kn*^S8mhpj*N#CMf&?>%6*^mL$%gZ2*q)r^+q(T zEg{{Sy+~BncXHiFRc@QKkK%%8i_M?c!e`MKs)>ddL{{eGU6~YRo7pqjYR@}T48Eaw z^6w(lxcO9mvG)@e1bZFg?mo_hr93lX z$sT+ge!dAmVPj^NEISJnKl5q@7xz%{k2(wW8n*SobWpD=I=G8!$VX8Y1!=&Fjc>jA z0*bK}(JjehwiIVx0ZnhKGCULJ16ku22{nHFg}Ztgm6cK5WkiE+E7;3O7Hn%qz_Dfo zzUS(EzzWYaA-bOY6%6ort3BE(ov#?_{87kZoA8}OTw05NrZ-U-HNePfo=?JbAW@IZvb?| z#cY-6_9ZOft4;9vP`iS(F*HrjLJ3$~f2RUYRAoGmTd@W5rDTQo&BHPCQf1+|dcur% z0gd#f2&NV^&&(%@_g$L9vC4H@TC)+)S})tjCJNu(UP8)MR>9$K!!asiP9j!zMd%Bc zB|qFT8+i(4{Eo^$!rmD6SEyvJUCq1_#@Uo#PTojB^7OlIC4gd3=5E9){fc&9tni)F z=k*O1?O2o^585T4vNdWGYXj%H(UfI!(icFJ&eAoB%b#(XcL^Mlw+dg+rOQmU>~1S*uumTjd0f>;=5Tg9GPEWxyIIM z_%>HGtKqZyrn{&Ldh&a2x-BIRcB;N4z-~5qrJHP<6)eo>+&YAD5cZ_#~t}jz*JSxS7Zfo z#?IkxxI%W*k4;>}=-EE%IHJ5=V=gfGq3P4iR`{sQ4%1F!TVG+$F)B8fIEcI3Z0(R+ zbSc}kpM1irNdF_H4-Bujf>Uem>HI=IZPue{<3Zcffj5}lrr+}q?|V%D(B<$4bD*=i zqyvt3KH}62o>FB_IdwOCaJj@K0O|Om&Il3CuL`Zd{IPhBHb0xloR_5igq(O4a%{hh z#pEqZ7yHHp!btxJCz*dNKa6Pxn+wXa^;_3DoKkIVTu;UR2MMn8`$i4g>Ox_02{ak& zG>p?z!e}tL!xR_TsKLYodoBF8n%Y9N?B!=^j_Cob$F|Y2*flGe==+nnq;GITOI*QS zS~rnxXn3}{AvEM<1G1X=vUD%h%<`RNzDZjzH37 zp=?Ypo7`mTkQ_7&V-pP4bf--)mA$*0U~tBFioV82 z`%N&}*Fds%vdp!IWxaM12bLV(Z(#(JI+ffD()5Cho7B|l5C9@CV%*7<_EEgIk#@0~o z;raLCuQ0KwU|$37ZP;s2!wX~=?pBV|uLhNkFDRRRuS93F*a-76kyMeo1*0BG$fmpP z7dV*v7LA!bB5JIe3??5D$?b7(ZI_Dp>y2?TfVP0{8e9 z=OTgshqpI@kE+P_$4}kvKssBevxkHwBrG8ikbNf!ArNIJh*1=pq#+qX64M<8w;_r^ zMi`AEZa9LXg5r+jz9XX!GcJQ7BcnJv2s)0AIts4;?>SZXb|+zc^M3FBAAI_xzNb!Y zr>ah^_g;CEmmU-1X?(eUS0K-q=OWz?bbYg)-SWN&-Lk#bg_`vMTgZYzZu^EB+GI9= z?E%wa*swIW+)}$WS{FSAZxS_qhR;+mho=vvTtQ6DyTnAXMc`)C9Z!}OuzBn1)(?1h zmFK(hnKz!&VDvx_!o~T5)66ca-0O>z7sgBYp%fkY&1a4hM#kJHh;BNHrf*Inx;W=C z_Vz0a?+9$Rs9bX~<5~#Y1s0g=J(+!&e}BR`?OLWBadT z|5fb2lZo*{dqoU-GN|idG%eg@@7ucgZaw{tb(DhlBM(P({nsNjJ{kNiE1vVl%}_3C z;d_T1*(DjMtEQWgT9*dcg~%6X8hgfj^d}JS5sp{CgFy#+27%1;&bZ$77&l|>;TeY4 z6_}lPeAiyLZ7CvOBF$kf1iwRuFsb~Wi)^0^b}1;ZZ=&=5;%FQE#|brf?-$lQoiLY=Y6$e8|g63_9{^nGPJW9iWiKOi?7s*tpkPkWOb z<=6UNMB{I=_wp@%W}H5fHpwq~iHUI!%!)82gYbbe-L3VBqj}XT$GOVggyyW@K^d!; z3aEK$s9g#Mw9|q|W)5BDx*s=ro`*);=Kzs+a$XKA!5jmKD3(R0-{SMA?e5pipmFPU zSxTDLK{fi#m)s!OM)H~4lP5YavaFg3C2IV|5NC#n1Xqe9y9_;qp0T$Xuq32=y%d(&D2do)zpF9e%X2Fe$pjbBnBT4j$LF86zx57+(;G?(p=f zNc8NgpDj-ADi8M#igiMu;^GU2M89^n-EcV>wl|S2K_?TV19LJSd!X}TZ#bIYRU6aa zg&MontU2xF^w=9wKhBb@WB(0bFpijqCO`=o2C&D4D>2WbO*nq-@BBU!_QD*);`_ez zF^ALR0m1&i01<7#+yx6UOW~<`Xc-oLv0Sw~9N(ydM6@yX#V3e$TLb19zD(3V2oI*l zi1GBD_o<8#gWU*AUk7RT&z^jmu@Y_7qT!S?U)wu=!_|t*>~S-Sevk5e5-yLcd6Z<_ zGS{-%p2=fUqc=iOo|MA;q3KI*le^*9+zWLWAKl~`ZZnWsOau67O0GOutw9sz#ydWt;3cH{Z`#3&VJ~S14?`V)59^KF!ONU$8OWjvYD`U=cA%SqzU9KTI?X=N z?}|2|uLNO?H*KP8xR$w1{Olc|cBkQ2gj*1F!qYL`f}H7V!Wd6E_^rXOJAV9+ z`FrqVKGtmQ_^H6SCPLVFbojjQ$@43)ct4eujYv5+ISwk!076+N8X5bl6#6={}7u|e)4ou+NY!68SW(W z*Pl(sX^*{!{I}D21p_N496X^w?*IQwXW#!(I=G7Re^MTdg#Rb$2KbDy;PbiF0#EEi+D1TUQ{cSUyZGqKmnd>5`qsqE6kVr$mS zWfL$}*0VU?jd>n+E zi}W0-Lp$QM>~;h--PTS`wvPVQIj{CSuba_P3@R6Mj{iL!RYON#cTTsj(UGLf_u9e< zvyx(wjdqvYUi(k9Wb0^ni9OHM^RRC^rXQY%ne>}+oY8R}#w?kK#c7?$N_LAS87CF{1jJ4__6`7b7t_J^r# zouB(l`?-U5_K5Qu(Jo&+X}iQ;bH_epx63rsF5~}q+og-wJoGK6YxXlD=ek`+-vnRV z`f(QU@Ug4G3} zEQE_-)n#wa>;k-t55w_8YVCNEwKE~fv5cLsC#PnKbMolJ$DE{wvmKdAIW_h)vmY&K zrSz*&O8x}%lC6Z#Q}cIPQt83pX&HMx^IgY!3il(aC#+{MjqTWvm?cfnd-8r{tMz|> zJyVAgegALjxa(+~Phm$zuV+jhM`oW_5hUSaM ztsjI1jfr?F>%ITNLh8dbZ66b<&xn)SM~>ajBbCfMwM6M+%UzW7h87Mf95H0n&{3?3 zD5?X^gJN?pA-W2GU&2BxcV4KewtiWVCC<19Yx@!4&7Vh$|4MRDn>%%Wc`5uFfxqts zzmmEJp11Hn3yCl2d22pqbTEc$7=HwSmHs?_&G_X3d;vdP@1=pjXz$bue__-KI+O2< zwcziK_<8W-u>5o5mw+F)ZN{wdqUbyzfAq}g7;1`M4!TO{nIZfIkm*9d5PFf& zD}~-H^gf}_3f(XCBhVNeV7T!B-xV>O&(}b^&{eS<|4l;U;y9Jh;#ejvo^#kw=wA{z z-B>TnS9>|#&p>0yo%ES6hR#Xi*d77xLhmMV3<=3ratsX?x+XaY_kBX&Pks(ZNV`%v z#g{;1=+7w}^VR8`VoC<5Ser3DBZe*%dN_l1@>OOYwEkxHZ?j`4uRF&!U+Bd>INh&% zyJNc0mH0GR7rI$!ZXUZAfg=7qj`<6r=k#IsgnqgGVrbSt4i!I$OL6vKP9n@Cm|<79}>>%px3EmlekZ(7IC`Widb@a z5y$@zaaR^|onBcSDvqH~#QkkC%SV^XE(EBJU30L_ATJ2X_KSAx7sIluNNN^D7W8 z6>^2*w+eol)CMDh-x{?r#=!{ay~7Qa*Q?tVru3L1tl zLos>_s1MGxDh2%&C=)h#v7oPj@@W*lX~vRqiqROVl|99QK!a!k?vt|LIG}hc25JGC zBB&hS`eMJ+fM(K|%KdMZxbc z63e4NTcH(8aq4@3;(=U(UIW@etI-BHy?20iA&>EbJ{HM!lp*M!f?6@IvgD6ITcNT3 zg5q5qXDbyb&RK7uV!DEc2pTJXSI}@s5=}K|lK7n|lGo5|iKSNjuAvId-xF!2i*@!e zRf*p(;kOm{5Nicp0dxpxg`h1!(Lm=4+GQkzg7yk}jLsAE9#A~qK*!HCCelB|?-{yO zH1QKqCf-)DM*O^PmVBOW5R@nA1=_B-KMceaAs&0-Pl?}T_#Fp&MoKsc+6wefLC+Y!FGX^{pjYW%f<86q zYmszEajsvbZv1Z@)(r#1@OEht{$$!?_ZM@cUd4~0`~q_C>%hOTQUNBv&>Za3(4 zK~EWUNYJZ-daJ{Nju`Zz#6p;RuA$!QWARHe=yUjCg;LBK?5)1Ee01ECjAh05o(zlt zIWgJfrv5R#Ku3VOXi7{U&@*E4L6^kf0T((qW(aJ}WpFFHHf9(&cgDQ}`RC)_1IH8p z4QOusx1dAge*zs5??xM)6yFtey1364+9>pV;a@5AdZD)oeNgDLLjMpSqq@-j30*;- z5&C;jopVKRCG&(-XIVE=b%4TAO$W!d{ekH{6Ly$CuOW`;< zT^Ef_eGm0GB{duL^wc<)i|SIpf%{USR}0+&dI}v*JI^|W{sF4!MA|HuP5Y)VhI?@O zd5E8Lm;>$AxpGh!jV`{UMz-%r)hsx6&VXrO{FF zQOkJ4qK|Si!usEk!L@vK2DjBagofL#o1V(R%h;sdDta{|4l(E!JG~p1`mOYBZbeUb zV|~8b?Qyu@>&7yF7iwj(eqytRpuCw`VVyrE?jN%zqE#ehe}epco6Y$g*1d0(kE*+$ z0(x_I&f$wfKNafj!JNsUr>`E;lWCFAxk9UiHVa)R^ai2#3Vl)NpM`!d^hcqIy*Qr! zpd)Ft(5XTzg*FIXFZ4E{4+?!==o>-yeex#_&V+uWy+ z?s449@XhAFoU2`ZUqK#r_vM^CDRd7c75!1@pM@Uj%X#>^?^}pd_2XLBJw2%(_xEZ2 z-r*Gcak_zi2P|9+?#FTF4R{D8Dj2|hQ|El>fK%`w{+IzHL4Q3U-?2HIXSYbY>GuN; zAh#^8+XFJ7hmQwv&*k2yD6@cD6kB6xtY9f*f(17r&dUpK0o_=zJrI5%xFeoJFl0PQm9!q_ID zM+NPrJ7ZU3j=wUOQ)r>PV=v>cLgi_+ThP%y8oelJeP2d<)tiDA;+Yf<_m|jKguCCM zBe5HSrsZqDFMy)yut7fpd1yRtRq%T-GvYR3C48=+wv79--*Cm#dO>@m?~Z#F^N3p9 z)#0-5j@yqlXR{#Id@JTMs~z+K&|==6gXHhxYEj>-1#PDH;*J4rb}!L6+}LpgMz6eeVFR5ww;Hd|06trHD)_h;OL69zOUwXzt zUf978HKM*r8CE~)KS8J0Hwjl=>8OKBR6ebqD1Omnl1gy3@p_F!y92QAC4N9&HGn=8 zq+3q`eI;l!)gTXs7eNYe%FrPWCTt$`FWXk*es>@Vyx=$fQfpu;*`^z}(Y ztwHpSAYHyelvu=ZatagSw^-0xx+AH~Dx|^1?AJoiC7ossrUinuCQhM64qAv2e5Ihh z^hHv@8b&ub$cqEL-3A>`@~RPZNF#jq;TP6O`ce?bxezG3gwxwAexnKJPwTpfo%pvm zYIe#VtBBT%-(JuBl!a7GTLf*QWht*%#q_oy-TzAHuplnO>sASUufs)ixKi>?l{ksx zETukzSaKsxp-~QMqB5EuAvu+HJAUt5)95AbCvle3I}wuQ^ob+65qJ20i10g&;-_)y zoZkD^bm}E&uf#HghG`@@n?aKu$&ECV=12I=qJZPqg#Eph5q@)MkK^~LHJ9Fs@S8_R zwO{l%DYf`g%n+P6*}bEJ7HC8&^@LSH)duCIl50L4H3(lvaGg$#r%E`fzXkM?Mkvt- z_#*Tn2l-rQ(B{*$=tH1$Xx9ww_g!iU z-lTNYpoFx3u0^zXruORzw3xDIX*48lkjqaM22F+E5?U{)jpnBfbyd-$1~sOQbyd@c z2CYe(>{?3EvpJSFx-xB=YZ*;5Xe<0`XuUxX0M*higZ2RZg5Eahb)e<+tst)3R-Elc z&*3;3m05K(TchZo(rU4@{0og}zPB3aA_vWP)zfiLvv5X31|!|z-pIX=A=JEChe@|2`62HI}?W~MI$8a)|B5yY|JCH8cV zgI2pjv_{Yo5BKo%X^TNEiR)eG({7DaJ@R=zeea<8u9Z|*p>xe;xPYDbw-o>yH&>y6~i>04YE(@TOjNB<@L8P_lAutxNc^cR8R=5s8YfnIT~ri%kGTT0B*R4Ej7{A>B%E8^p8UTWL1#RPY$bD~(&J#vool+)Aqr;`PI=v_a5X z`aYw`eH(2zC@z!HlSY!)GPluwji_g48T=M5loVwBu$>MIYN5i+m2?M{p3QzOG#Y3J zT`y=YoeFdp?Kp@1_NaN88*xSuw^*YknXPmWRT~t7-#t|7*M4g=b6odQok7Q#8C8Pv1eCGMB0BB1>SciZUx17$5`q+9vxbc!Hu*FD^?Q?*9ujkmkspoc_OJt?ftY+hl|$X z_O|nTP0$|FvGl5uI7!D+A*dxfH)|nMm|e?$Ei@wQ8TWqLV9@le#qfL9pmVakYCqNe zLQ4j-O4OV5p+W1i?sC6Hy_Rdgo3mQ!09`CdTZRL4t{|vnT zA3Eqo_d)u~LGkW)sAnCgu$CT$NEPzL51pbiVm`*-XZvcdJ5ujpS!=H@ft;EWPjuSk}5R9i1!1~ zZU=qt{)!TtIhGdco9&MJ7j-?4kxu<?WKQ&Nk?! zlus?Ust~j}dK;eljZ(`6=`utq{_=<2$D-7l^99kd>?}xb7qmG#zI*SeF6v2xO1c*S z?KddceI(G|4O-hh%H2h|S8^8EK+&rA#f)@mJ!(KZG{Qk%S$Q+Mt}?r+AXp zs}36LNmWN3G})7`Ubqn`ubyuROigNI^P<-fE(QdboS5QytXDovY3eq z%RxIm!_;bx=#RM>)(Ex7K|QRIYRwgrI{Zr1D7ED(L9(+jTJ093YizW7Mf;(&UNu_1 zElB5cjQY&+d&DzF#kX-R+;+>Xv8tD#y`G8yvKfCaDJvIzMlZRjgii&;d`0`p}@&$V;hG*XR`1A%#+vXi%G= zUK-Knyv6VvZv1#>uT(7*v^M&synlL1RY;Jw$))O72C+>pQ@1#%iKeRE2C+?^rd~FP zZF0GK*C4jZr>ZXvVw-%Lir&QeJfhepPgmUyVw*fe4Hcx@%S<&*&}NG5LoqYeCWA8i zcw*+L!v^)~lN?i_reDi(Zl*qcdc-VH+YK7lr+-YP`pTdpptDrbW-VFNXGqN1YOz5x z`izWOq&68;-)BOMU+p&N;yz_DOVp6-I9wZD+hmKf_)FDB-_qVC9G!iS-rl#G(;dJ?~Q56msm099xY|Dsd~Pa76n1CUvPntch#Y7K6CIU#p%Jv{$iSHmgGpT1nTb z>$eg99Z{^88`KU59q`U_8Y`Ke2aS9AnyHJRMD**%UVTHb*p;RAWq>nm9kw+axB}`CP8|~bGv#*kS@b^^?O0O zZnvvHImoNFtHXkHo48$l%|r=M>gPU)A?CxnZr!n`c#GN{Yrv6_74K(O- z_}!;U4Z0D2_o>AO-PixynETaAgZA{N*!$I01|95QOAn|W27TJU%z8lWHb~`njeSt< zGsu@e-2I?>+n}8M%jhBXxk1D7Hv)YtXfsX8f5Wv~#ofjE+)Sqm8YpNj&CPGc-N?Tg z~Gaag0!W5M13U)=b{4^(jzKm z7st6add7h9v5%;M8ljy%;(0{v(ulYhKdRm~sB!?KEgrDPdQ{~)=z!-jRV1i| zY9aZA+NJ%XuNyGd{eQH!5Q_bSy6OpyCgFt?ud2~cYE)jZ zI`%bHVNhkk#@IL1oTu1NTemk=rGs|HzNyx06n#U%{jqPUtp?p*@LM1bgm9#?u?N*|$M5~vchr7C zupt9Kj{S?;@+`-q^ZA}yAxP`xJ+)oX5q0*!uVUX*S3Sp)M^w$g?_v+DmtJ7hLcxKq zxc61|9*tUo{;F;fq~rWRwF=U4exP;;(s6#EUNVT|{7@}=kz>)}{-(+W>2QBjHG+<) z_yO;$zp3>GbsG>DcSNoHolgDt15@HYQbjK@+Dz{b>>hVaoh?Ym`LU`I#Ifv){aB^E z%#ue`w*h_QK2bvqiXU(=_U~%C<2NYoA8L)D&Ggy8k#V1^>wm9P=r(9l+!t#19~iaK zkU`Vq{-qv$O{4Nb^W(lzWv?^Rsh>~_1?e)JP|q5~W%yQ2e}g4ksA|xPxbM`n2CW*j zGVTYpct88?Q5y#JaQ~#f64XLB47wCAs~q^I4tM9E4RMyWTTmPJI4e9Z>uux5dU0Fh z-(tx&dS=iyab2wW2N>y`b+s;W(9YPd)&@bkokd$0z0Hy>^!A`FanV+_2PCjKWrmv0~q0#FAgaFHa*mAB(d}4Z1t-L|mM;Oe5@I zQGC30z7wvM608jo;S#J}PPl~l1nX5NTxz`6de5M;!ZIt-`b;CF-il9ixDMHQDYJZ5 zwnlVDVZZn!tI?qO-op4~YqcPKDwJYvjgU;Svj1Yo(n_h;5C@$WpK2w(D}K^b)2z{g zTIgYDBF$QF(2IihJLt=}G^^+^hijqzg>&LFtfKcd`di@wpe+V{UAQJC;@&Vold5I(Nu3?jcsSK}mVL;)hrtwv%-K zUBY23eh_|#9Q1hnFstHI_G^LP^YJ6B-3ARAvM+wL_4Yrs-}1bvYMeFXGmT1y9Ecxp zP5WGVKU5IL>tmbFCi)={PH_s1xkR=<0+DD?^Y@VZL>h zL7c+rR^zuUsZ&^B<$b47&A^KjDy>JqXS9d-wDTk}4Q9}3d@A!l3Df6(E0 zKV*@$+d)mV*vkG<`|+NK-&$i3?|Ce-{%#QOl~h?3KWRzcE2*}gG>G>@0#+XG^l?6U zKV+%J&+phdTV~xUNaw7^dcjD(Iiyh4T8APems`iRB)vQ2HwkstOSloKwRC;L3hR&{ zJ$BSv6}U6W>2aHHu=WemnrO5>6Qt9_$31bgktKP=YqC}v#3NqNI_~%#j15`4+;*IU z;?A?`q8RBoS6b@?={Q$e*9+3^>;fy1A3a72+|Dkvin?mV?d&4!D}&+&z8`yubrd&M z?KoFkF5G0b%hzIM2s)zpeEL#rgCLzcKSitXBmmRhLp##1bNPAPp#zxj@7s~yn!>)! z$6H~Bv+pAgwM=Z!$1(rYB&Np(hp8t%>>e|c-Q$FQDKu>q$J`4Pw?c)M2&Y`!KP59i zOf3_$=IB!Bv~;>-N3(p1(9?u!&Q5VZBJ{5)De^Dw)5nOsq_|()uOa`IDaBjDITS%7 zeZLoe(pZi`Q|-G0d3NDuKl3B?%o>JnMV|9-Q5&?%w~d+JByQHT&3QP&t$nrR)BlDa z8TL;RGWSS|x^y3jdu%GF!qlR#g`;acT+96I0n2ozrQ^cb5=!Xs*yc=^ohvL>~Q8#htIMhx{w;$bRICXsA z0r9x#Y?189ahqDx@kG|Cc59t5wdijW!zZ8?p1t9m{JgKu$>$=k-H}>7Lwal01iM6h z^PAl|UENzFd+vYY9xkzIs#~L`S{uwqt3aD{8Ef$W#@QgPVhdt((GE~IaXe8Ha~Bh{ zuA`rq(eZFt^eNnJme<)bGu#nUFBTF;U7qOFatL9LCG`|8@X zC@kNe6K*+5TD3*BNY`cL+4kbADw30}Lc11nexfEZjRCbt_wIyj=5!OjuJK%PN9L+? zOXG6cRwdG&XiK6wk#60)2T9CYC-;cEq=-}3^ygF5eSat9U3eOVLwzY>HRaxCNl(-x zg6;MchxuA3+9K%|7)f=mbdAg|;ZT*J+UD4nNB5D)mfyJtaXV4cTI>-}r=my0$gq); zH=@1ajq75cpOAE46na3YuC-6ZSC1*W)m4;oTH(H_?YTX+a$4;<|8KRXExgw7LZs-T zfTa7MbF{p!!4(pgbz)JgxNiZq-ORD*HsMF=R@Zwt9=k?5@-5oogw<{rJru!Vc|CK` z!>s5u#As-uA;|QouA0I6dC7#-X2y--rkCsb?6z$zvJt6xJKq|zm>3&*6)Ar4(r(- zee%Qtch-s4o~C*>s8f&BiSFr{1*~)3cRI(@nG?=~Z9gw5FeVAH!MvLRot);X31BpRXJ)_Vxk{`~Y-IBFEY?^AvY+D|k%0&*}qMviS z=n0Y3vo-D3G3armbGn-Vpbng+{s$ zNAQn`TXRlCxYx-@7a5P1VQP;HdOi^5+p{PgLQ}R3{L~r8bEm`CV>F&& z7LKkjU9Qd=(`D~n&N1-#h%Yh0tw?hs-DAOT@5^Jf&CxxP*CY6DtHcoLX8qf3fa}hp z29b&6N7j*cN4AX?k&kS3?6%uaXSbHuv*^yDbUW9fv|G=>BWK-uh4SB>OGL)A9(lGz zlX}K(uMKr7k#!Ln>gRRRIk*2^`N-A5b9lpz4^PSYC37ns}_Hk!?zByb@;nN{+~_t_*;)K4T!Uma5Elq*bTw2mV%HCLNFN2m@uY~3*pojRG$88b=ORn>_ z67TgKv)&%M(R<7~JoFl`hrS$oofjJy!)}(?Zi72<*iK0DK9EP<5%UyeGKV2`HDDOu zy&F8N3GTt-9tC>BsvGt?WJ1Hb#(IeFQ+tT-Q7hN4hAo7f?^{4l(vYrc0s+6q4{kwbj13Gv6(QjWTOL<#vNSAN&# z5%5*pgmW+4e%GTTzM+HG-VwE+uaDS~=y$yX-&)u4xZfsbN@q`3d5w99cpwF1{O) zub8$XKi?;E8C%gOnEKVNBVE25!1wt4>ZOrh&_kd(>iEbs(1cOlecN2zK6ko?jylV; z(=}#PzHf}0?;Y(c7Cj%dW{#TR;~FdhpPxOcb)7zHop+n-oKe$!KB^zJ(KSY`9<{=E zE^!O@tM#L9_RUdOjT-Cr6U#s5+BT|AJ?467R0;aRb;DlvJ?3J`Icndi*N}&|Mt$ac zOno=%YoAiy(XmNN)%Wow63)HQq&?LmxtNmHK?l-XyN0 zGAqa3b?h5SIqrB+uCKpZ_xph2XS^OjDy^Vf$1VoVORc6H_e;oUx%(jEZ&UA&?Vp_EZp#~*{D2ym zx)@&x<9>RAei+MkW0Y8o8uX)s)~3NFpfg9!OrGODWt*`Jmz_f-=RP97OxXUNd}|&Kv)`SI>r z$U&|)wRC(fG5|TgQI@`XKo4Lxx+$W8;q{;$iG=@~ro1{*edKJ@nH`5e1+h?!Zh8K`{l~VB&N@$GY=UF_&Pp7cE5HfiahP!=g z@Py$h9(iuWqt1jp+qb1DO4UwSh<3gbbd0)uLMvqWX>^aedcsD!0ja|pBZs?Ewz-c^ zcrE3ax;t(VTI}*X?vK|EdlxZ$IpKJU$NFi4mFlsQCh`a}Xkw4lo$iqnUxj)@M{q>TbTD<-%Wf7?$<~BQPP^3e9T=m=`2qr6;1jk)#omo#5Qf= zq~D?q)WH2u_qCIHrk!x#Iw=oyVjW*hN+!!~K{I5ESm7p5!0;ae_D4}inB zTH1*3ue8aXmNC|MqYgt?7nXho+kSN^*T}Vf`en?qo)q^VOBdkvX~#;}f?8AFSNRr? z3;9;^l-DzAQBzNO+Z5k)@=(7i$1`#)o-dsXKHJF|Q;>>UG^I;sn`(f&1^jNA+fcLM zM?KkZTxMI;KF~^x8nMZh>T=LFbzlD?@SmJA9rOjz8=}5SoSV5VDh5y2>_iM_z&+o) z2yybwvo^(d%-YnR{!N+B;jY&E>N(=`tX0HkKy50qOe}d>Wi01;M`pe?tZX6je*?zT ze2ec)9aKD*%eSVLp;cQv&W=$nIM*(Au}yA6u0DquW3!X{F3FE3G%n=72NbyP(@+#CKs15}!cMu|6$p zgZy#C1EVnYx^9oDZc`uWw$sh?x-lw$D&|7g(5X*#8zW;xB~6<80({G-a!oCm%Au;n zy?$yzdZl&k)V^5{xVBHlXyW2=tJV^7P8^X{DW$Hoo&%@SI)Jd17SA~=tq-O$ z)ic{4rkY2C;S#`HIw*6|Ae#Kl3;ZDU{T>&R8#xR>ER82bS6ou>zgPaJo`eGrsS7^CS!T4hD! zeQxVOzo!kLgg2-~<31~MwkziB5Y8@jw=0_NSNDVNRu8)pXu4Gym4LUzT@PAey#soN zmE9$Q7Fvry7hAW2R$G4qt+5KbCQzMqA!wtu2Q*}P@y5)R)~TQuSsOuDTZf{N6W6Y| z1j=wf9T!c*-E9`+-QUDR-W`_!d3OQmMZ#GPP9auV@AN99EV`{{A?4E3pjGq+I0eFq z6`D*t!JkZTfzG2x;X91>z&@t;#-M_5z6b-sW@qFQghN3NmnIZn{-ps14;Xm4kUe;^p7N!oRyrLJScfo^2FpR z$@7vclg~-6POeKnH+g09rODSOZ%e)-`M%`c$&cZkzkf*nQ}Vx(zfbn0q@`r1^iC;E z8J99OWnM~UN<+$pDOac5n(|P}<0;RlyqWS*%I7IDsr^$&rOrw{E43!|mefa6pGtip zb${wdsdy!ET5?)uT0z>}w5qh#X;-K1NIRMqo1UJYn?5vsM*4#ECF#r4L+Ll9-<5uU z`ornZroWbcB>i}LR7QM8dd859F&R@b{27fI=Ve@yu_@!Gj9nSO&3G~6K*oC+pJaTQ z@nc3@W^!g(=F-f%%vG6}WUkHJn0a01y_x$m|C0G>rq!)yx3S%dx}Dvvx!a}PwsqUr z?VsJg?G}?YHfwR#rCB#-J(TrK)}OMDW_^?OQ&vXyxa`^4mD%TH*JRgchq5oo{&n`I z?B8VXz#EMBX8$?+NcQL1-)2X3Pw1Z6eQ@_N-Dh-P(*1(&t=+Hdep~ll-Cyp0sQbUV zXZM)bEZ6_?U~iHZ_lAUC-t1s^NgMiJum8cZBGlk zKQ8PqxbbdRywe!F4M{+$Kt1G*u8G)d@L~OyjJ*cD3kN=Z@F}9cuowNXFVP>n5&4i9 z0Eq(l7Q%NhxTk{LudYo3I?i*mf1>r_b0fW%Bl%!b4qNX*49 z#ym(=q6eIb9gMTE_pq3zVdtTome6$cmzmgyn1#KE+1PoQgD2+a(n{<_tb){qkh&Oe zIQ=F4f>skz|G2H7L*zpFn7EyA7sc_l+v#z;K^Mh626}GXQ=qHjo&#+W&gQrm;eIOa z&!BG#e_6uqaEB6D{!*b=3f&_7*S!1z+o!s&1U>A%7<8lWDCpHbmj8|KQ@D5ez65>T zcO3M0z8^r}^5IjXblBGwl%ny5dn!%hRL)5n4R=CvqeF{R@Xbj&EroqAOW`;>)8VPl zf!{No>4J1F(Yo}jU3RFAzU$zQ&-fN}QU+duX5ydN?IyTOG3wbR)%wvo(Rz!|co;Ib zi_AUUI1ifMm&KusZnI;fi0;Zx1HHFLIcQ$@8KCpK&jWp~2dB7S=n(`)@ayNm_%)J3rr=n>nmupbFwZ^pj{yZ-GLwTI5C-S&lMbU>5_Nv$; zprbv12mMpt*G_C&zO$r`LF-?~ytOZ+)GM52iD{LfqF0-Ijkl zWFE{2OYfb*>LGr#*{aCDoDq|X;T z3H~bu&x7h3e=4pkZn4ZY!sQJ53r+mz_#cqbdE zg_{1K{yLNeKP2|2%)eq$uxuz7VHDl3t=@Z*aLpI+U2k{7T!2L z3-oGO4h!!SmQdR>vZcu1joeOstPzzsf4}!+3W>Bv>A9R3P1v*e& z2s%Ms3|g#y30i`cHFTmb11(jTgHBQFK+CXe0iCETK&L4@O^s*wt^}Q~+CVGtxS@sj z8ea=qt*!$N;4KsuEmt>zhSbfV&FU7=^VK%c)#^6T%hc_lYt@~g>(oxr_3CcWR&@{P zuhe~@SEvV2iVdI^-dy|;=sxu@=xgc`(AU*tpl_%rK>wtk0^P5k0X>2_zlCpOzX1A` zdJ*)5`W@)E>Se_C9Vl+2sNci=gV3MUAHexhC|OvqW39#1WxWo*1&Uh<)}P>Z3yrq$ zj%xCN;*%rR0k~s9(QYlgt(xM6daZZBNdQ$?J^lsmM4?F*zXdTF)S?vYeYjIWE$V4~ z0NTs?8)!f4BhdcVG0;KQCy*%wwdfS);FM+Stmf( zTHk@Lvwi@*6Hm$GT-U;SjUKRE>O9|*Y5UTXGp2PLl=a7~wb@r>AHIYrSGia7*+dlj zV?}|2g}5`}?4e-}7|6!}OnsRb{ue`2PQqK>iTAsdr*Z3mPlwPRVFf(s{k_m{N21Ra zqhFqbcE1R}#rXO0TY_H|e%1IbMcc=}@iQ8#o9hA-slK_sHdI*E&=e@F#yb-#0>RLX zK&Ymnnr6;tpULo{$qn_Pz{*f*ZB?kYq2AxLO5{od2<8tpG*NLd7+A5SZq>9vU1J~& z=LY=MfTjMBe_lX>I+Ak(!G^l?B4j7~t7-x?Wo0N(A4D3{8iFAt+Z1p(L7LoL7iw+_ zlmzYS}3)ASv{><_&*7ESg3x{4-$RbYDH zyg(hbW3@*{-{tk^p+>5ugicW)DO|0am0ZtZKhYqoh^7aY`Kwk*P&C1np~?P67NzM8 z%Oae^X9gmDmZ6e$n>Ouprhi2s*oZ9ah#Xka6bO_w*Vb{Po!JnPm0&n8Gn?z`>_()! z2s+2o+GWj97^+0GBE-29l{F#3^BbC$OY?6EN$)AEl~U>e5ov`PrXSAsb8sjct+?8R z(iv~(qos{Uoj03Wg>(tZ4K%AOdte!3?k`iO`Y5P+5Xz5 z^J{~!XQl{cbpiiem@X;{__?>1*Dr0Lie|JAO(Tquorb8C^B>`7$7{<>WjijzkDYZr zh6tTfAHpbQd!Q-9!q-;?XkOslX4vmYy+yWLy9}I$-P$5~qEfp*+Oa#Co!8LZR25eF z>HfOrKnGqYbq6DB*qGZTwRN?jRqY3?2t_#NWNu&?hBK5ivNc8s+L|&YIEjy4grJnc z=_C=75%U8youQ(Kyj2)fSD=yFgGrF4`GYkf{}NQO_M}-$*aT5| zX>G8vAt*kgA8!0K!`~FF@z<5CLPgnv&d?)Mf%18Qrt@l1fl@Ov!kbjfXMyJo<~(*$ zxf#JYdE3nshH@uPGn{c`PNAu|v9YeUO3ZlJfVa1a9KhJja>o*eO-i|~aa*rLsS^t- z=+x!PBP%c*#ME0vBz9Zu90!Ctw~G!19!hl$%cx3E=ImNCW}e3`ZMdX+V!+`!V32LP zW(O%0@HdqS-?R*Khx$;E0%rPwi5{kHRO81OswX6dv($`#VO1~D zLvNT-DAT-UfzTq`JhPj1EUkut&Wo5(Vr*=Y#ET-X4TI+zuwq-j?&ba6SKt9i7D+$Yf2hSS#2FpO%Wf>TVC79 z-VFF}xieOQF*nc%o2o|>TY&$HP16irXSOFBFxzc(SLUy+gH@i#^Q*Z$r4LUq?TNqi zI^9!syNFb?Q?#&(9hRd<6M$@;om5|))Uqg0CE6{Ac@f2lLr92K!U|@cOm1k#>@@6} z8gQ)lY<~#b3}$^o@NiZQJnbXD@e#3-T3*|jRZCMfUVK|y$HQ2_zk-$qsk$M!XoY`S zZ51^J76ogU)yrsx71W9)fu>nY%@QX_4Kg|R*G-e<&pb@q5J0pCQSSUs7I>7Zg*oN% zUzSQsk)Uz5kA<^}$`Djj;((xqsvL0Nh^sm(plPxw_dOke63)!Ay1 z!m}>RgRsf9)w2U!aIN`ZX+sFp=?KQi;U%@9awx(`unSEtgx+v^potf6Sedbr4>)?4 z1lmVl9vN|YFd|Zkxa%8O*#==Y&{Ou6t zn`Vs+d(W#Z(+%0+2Se?EGgbzv&Mc&ZwA5bR=m1p_vrhDxj$>VrYIteStxX1YX?77g zVB9{pY8m5DCgNoUn-mewr=BKLM=Ake!a z()B_-#gxqlO{ZhoW6yqg>PS=Ss~S*I%XH7O!HnWF7M08|E1NPGdE+n9n#M)JB~(_| z9ITwg-OFQ%=Sx*hvr?@%P0IP!T&6%g*s`{#$ zriS{4=AbaU7*P{DKx;~=?&NfU^C94pkj>fexw*= zHP`dd$NhnGsr|T@g%SHnRWe%~?5ES_VP1--1Bx#)TP+cm2j_*$0d@Nu=hp|Zbs^0T z^KoZpfE-3jhR|U3C=UC|6UKl&xs=+JL|8^=imjBmxSi{oCd|aJ4JKO|0m32=TVSkG z-t-_YG*=22OQ$j~5L)1`4Na3BwX%jLJ1@M)BI<_?t=F-X@{$p;>42OGGjVdVsAIvs z>W*7(()>DcCFeGG2F5cUN>}(pRW%~t41L*LGo_l@5Z0Svg&F0}%-Z2eJYl|xZ3ZWS zjV(vaPGtd_-7*f-o`J4mGxXj^y-bC9(rVW~_8dS@Hbo6^o`%Iep4>;+`z7c`|HiOE24%Jb15Y zfI;H;!`q(5kHZYWvCe1($Gue=sse^cS9u2rt^7P8_2~QD%SbOm- zQjD<~vjSAAwMm%X(3GYotY8=Tn|OB!gAle*Fxy(fv#g5p8B-RO&8VRB^@jE`v~si8 zYVXO~BRoy6;}9qHJN+xn&Eop`V9Y7M1f*DEVd~UEwe| zvWJYqw@U@MV+zvMIV4X7g0ckDVPS8@(QXl@y-FKq)dzTaBaxdCj@zWY^l=32)X*My zcG(o}8sO+HcBiwjnS|}Gt(shir3$ayitFlhnRsF703FPM*icz+1GBTv(^Pa#ZM4~6 zVwu^%`x(3eBe(+$^4bt~)Alw{r*G>sP|v$LvR7a?J8pqfBG|T@`KD3xSQ4yhsH;Z1 z!|92=d(XqA?Y2X83Q?{5MK}ty*5UQxH6QVDP(2!kn1&_(Ak^n<(l=D<~&YwOVyQ3h5Rk9OgEKS5dW8plE31V*006CYkrx+GsdP=8~3xD3}j7pkSNB%NQig8P)eR{wTB#_ zg9Nig$99eDiMedKPOn`Owzn)Od+_bJB8NSTlgPE>`gyt6UPx9LVb%&vJ8=}^>;ue* zz^J8aShiX9W)Z&txZ(UD_c437G#rsG|trI}TrlQS{89Xy>-j;FH^ z(K(#s)jpK7t>O$coj8$$0{1*;#qR`>6{=K*t$Ta(9{o%=YO{<7j%a&w7P1Pnepm)4 z$JjVSA6fM?b!MgnMnxF5I_Sl4oDu`;HhmuE8FD6sY(&meI+w^VGbX7(E^ap>9!LmhJvC1x>`5IbjMUFgTcmZwZ+3yeyz z16dCltgZR11RK`a6{=$wFUGN|vDYcnYnKLC2UtGHsUOP0QFBJ^wk?_DT-(ca-bD!# z1{2=ODXa5iD;EQYUROa!lbf*%u)=A~sCRuZj+07~NFMfT!M%ceQXbzZ}AYy-&QpE=;v6Lg-R+7t8kJLK&);+B}}Ga+sa zdMBp|=T`dSM5qQgLY$*oBkFWzV>JXvy3OL7aGjuv8vv&0Jd5THAG25u@Y>k8St?+= zkqI8vcvS{z4rv#`L>ivC7{+|G6S-w(ZxCYM*v#|4Ld^W?t7;qlxZ)Icnoyk>(q)XN zQ9~oo9Hrk(Hk+;H9CjJ^9aA>xN5;*3vtp35FWb$0?0E@~|1#FQ0~}hr>^N;r*zwxf z#BKD%zKGo*UV_>Ak@>m}IFQMESZ^G*6Ei~6R%e8q&5Do;t35(4%#4r>t2#n5%w$Pc zeq^}m;DLMN5lF`3qBU|299!-{lf78N<}pTn31|meqK$@GiRlwr zJ{Fa{XgUu)zAj+fetQsLA)P-{6wCoburLu9RpE^*3(hQ0dQFFA81l#2gn_Km2VfCn zrp`46E;K2b4T*Uw56;9jhbEi^|9|bBe~et$b>HvI{+L;kJJb#>TZ(3)p=Cy5MXtFd zR}yV0_L5vmEAjU(DI1oejL0Rq*8ZUPhsd=}bcQht8?b@0vD+jF0XaobtB8OYagjQW zlDMer8gLNn4<|Jmp)uxBYz2d3WBM*`bzp|0&w#a^Bo`f1G>nx#yl= z_r5pB>Mu>(L8O^;R>JrXPoG~oXZyX{P83mXTXD@!SXi>-LL8N71se0Ew+bC<#vSiwj!pp7yTEtLdSql=*sAQjAeh$_!n zs0B?HnK!mtp;a(B&1pyRqH~+56jh;ideZyJnYj6{IWg^-oO@x=NfQHfjO9ARLAM0E zgryyPlBaFs)_i#P@zyt(beGgk#u}$A$!$@F|6O!Jli>c zkwfA7QPMdcyZA(~0QN!OBEZJr>_BW5&+UZ^etwTNr^9CnP?w(gR0b0g!8NfS_w z(1bReZq}?Ho=ewQ>wHU?O;1i6XCm2!Y?P?BaO*C5-TuFbRF9=8TefoOw8hkGk{^=nUrtBNvv7WmMwx@Fm+|1Q8lQ# z;3`4~>%GHdk4KDaqQI?=u@~9ON-Y;m92`>Rg(EzuAPSvl;PuH_cDO||SXbOXK6jaL zwMIk8p7Vn%FQUykdMg4bKw}XxyR#9qhkA*y{)*0L`_4ylAkeDB&DQaG&Ri|bOHp&a z?S+YXLXwb#ju>8Id|3xF^-`Q;Zx^y>44rv2P~ZQJ!V!`=rlktmdzB|KS!1Qlwt=co}cmCYH|3p9|EQWuEt%w)2c*KL4yO9cv`|cm52EXyg$i=E;R6LNI=~$MRWR0@%u*4~v{4 z^o=QNY#U0dqQp{|T1Xac$F8u2P8KdF@f_s8#Yc|TSMkf!`Str}P~_HY;-(~rf8a75 zyt8mmJUCE4f4-%pl5!3&$tqcseL)mcFiLFJ5|<`to@66})r2{cJWv)c*OysJI>;Dv z#;?KyrkzF2C8(th#!%OZ!3mOAPh7xM(9;`cM?^tya3u-qSOS`UkF!iI_%}Uk3EOBb z5^9GNIWs1Tj>ofvCKHsSgh8~r+GbjTly(S1DWDOY&73l{4G^oF(wIsep)f2di3|bP zSQG(DP7G#eA@PLHB@SrvEkn)XC20rPCpbsiy-6NZGbl*Dy6q$4@XpL(*<$`oqCJzy z;+2J?(<1rAb*s$4egbWEk*l6wXo%xHA+`-P5*+U^63>bxU@*qMY zXA~`D7L&SZtY?9(8$E!*qcb|Uc4qzxCz-;NE9ijZ(^u@&FMd+^zVjH%n#A0w>zy%*&`Yu(Wl&hV>mtJOdZ%M%8+<0@W?Z z+G#hX6PX$~1H``9j2?(UGD%@vWfqo}7fk{r20D_Ljh}<{MFxVUXz@D>2DzAsyP!|= zM3FzIq5y6}REEM)C>wwjC&xkNVL6YgO}LIhdV2H~fsmdSY3CRn$@0@%>4`FFLYi#o2{(FFku{dfs*7lKISr7-NaYmXgU=WD-?=aRqCHRkX;q z5rWXHN(M8rgr0FIE@rmB;7+y|aU*=w+D-#;+C0u4_AH^R*2*=^=Ik7j zLZ#MyLY%`hb?Pp04h0dffYs!c8Ii-%e#l5H<|(w6?Qq zphhVREwx`KNtOuzm?Q8s=YfY=?a?i9s{@pN5VOTa97JgiC(KyLa8#YdUOQO_rzM>pN=%(86GW1guA*CWW{72&%g|mLlXA}3VAFLS zn8}_wR1_eA4d<~~fPvBKGn8!6$;LCPC6m(TV<@7ZK8EU4H%}-Ye1N2pQ>8N81X*sK z!V#je+!*1=%=GMe>yDOoqgnB0B$6n{(YkPQ^=Bg9^jbOx?&e5MYV*lu!cr12OF#fD z$%w4X;ethMXmc0!B=?Fv$hCC5ew=marpU`2D!wp-6k8?hIKHip6}PfHz{2^Mb2D=a z*v~INvOmbo;fq7fsAG=8NXcJHI3u0@3w{o5$qvc*nU`hg&g#@gl;kPUHyvqTtm z%AXf+DubXL7M{<(k@Cc3;v$B)0mw$#Ma^V#J^>YL=VOj=&S<7zvm?u!Dty=?u&?gi>t{o@`@G<&zDk&^|yusF8J$n@y`3gL1? zGCnreRsxPmTN&l`=-}G2RVz3EejxPfH%IDoGqbB2nX#XqllI8zX;katys`4x1@v|c z5^T{rW0B@Ag~y4VOWRK9$z>TZW_vY@IjnZU2 zkImZyvCPZ!tCG5-=rEw}|F33QbPPAS?$l({dc($E--!NBW%_;}|6i!R#E*ZYf zk!nPdADK6k*NWl<1PtylRGwH|D^s!jy_|(26_xRNQRw~nqw_&&N_{hmLy?4)^edxBAp|F=9 zpL!%ookg6w-(X{*=3{L&!9UGA?Ot4K)Q=`Wcsaq<$PuksNEpVd9GYEhTjDbq3|3$= z!cuH}&De3S%gKhn7MgM6jBk>ohgp<5S!20RDsq`*5J`?6jm9S<+0a;c@#D5Kv9Yuh zZS7DADsx6`aiCQPWTLvnsJLM12>^FzJdO|mi}+dMZDZ0J@FVI~r%udx2S_3bg9V`E zFOvZ^h-e^IWy%r*O2jZP-)Olv9+PR=$Vsdzdv60?T)Dg)>X{Aj7T=zc9of1It(03C z3PI1~`c8)hHqdcarlpPa<$JwmgC&+2OrZlFnMg+3pWA9ljrRJsUMH3gGJ_WvEffUw zj$JZM5aA;MdE%qbe+ac*B+_4$`9 z!O+dAM(WiU=e*w&#CdsQbv7-t{>`ZO07`ToTD)p2Nwu&m97tkxDvxc4*dUYZN5T^m zRMl8&=DW3k8iEt;Rvpf!tTTm@GFzmH#mA%b+6f?X3{&H?LSG}FB!^=~1&f$;vJQ`a z+DjGiFqft=p<5eBac>G?gE8tGRIMj-GrKvm<+LN!a+~x%mvkggMy6K#5?9PE6kWz=>z9|n2^gxN%`l?^SuI{5q@Ujh0eZ%rExvGpNx z=BYJ}lwA(tJvk9Z@GQ7gz zX?nTLr>>s19^?BeJ@}}@^W)%OryOS)deo@nB{eX-!2PFqpXD`1u|!(fp5v;Tx}P&x zs=vY~Z84Ix2xp$91}Et=6pUEcfOLscQ8xB`iInhPp^d033LU1c(&tEvimSXzF~S(; z9hpwya9^5t#O7o+Eo;r`Fz?b_1d6EP^QsvP_liPsCiN~_&HFNWDby}l>^=@8&3v7Y z_)3s9ni^NfO0(hg3nSjg0@QvP$fEQGYazO6#zc*2YpLsbn+su$uTHHws|{5jh~p8r-v<5zYk6AZx(H0C z0C4VeTm@xK*@F}0s%G8B7%(l*TnBnzgT~uq~~7l=e1n z4|MM*#f(1o-Hul0=s{58+|^hutHv|ogY9s&0#aF012^4?d*?~{9BZVabJ%eNxEf`4 z7Sp*&X1yxOAUNYD8MFqLXeG`9=dJ4h957aZ4$Q5pmAM}~LHR7$iX&IR`LaRNXoQXE zsCJ8_&v7S;3)^(8;X{!Ne#-Vch2hIKzcbcndq0^K@xh-S*Rb!9VXb+Zp+BuT@!A}t z)mW$ah|5mfh&30BAq-8Dla=S5BWZ9sffBaupvDWl$@4O6PjhoI=%=Wh`}FHUv()@# ztIzY)kPH+Kkz2yUHPZZA2pEX2Yb8g91`n#P%cK`uP*2iU`YBWI0r6_&l{n(|-oyRl zCRrpi^~T^i#xMmG&92sc7LQ1JP$?2o#1X5rp=W3)zh-PN6_Z7B_Z`=~07MDQ1zwlD#7kIxQGJRRu3ihd zb0UX˜s9KBxP<4a>YQEl0NT|Gro#0jneTazm>?+QS@`qB!UMJ@?*RP9hy^3EU< zYhqHVyQ`QZDLXFlN>&N3OQ@nTo0hdi5BH`0s=bfE7j`(|t%O5oS*o&+_5sYIYqPO;ef=T#FDP!&zjLJ;uY80TD260E_bw)5|hBZy%|0MM+%~Z;~2eZ zu4WSMMy(DWM|8&73p-P2KKB}#RJ=>9be_XA6Xa$~Qz+tdl?ta+2KpKhMMd#+PDI;C zOG&R?yhM5w8CK(k&7b0D@OJUJ#%pRNllGAk^iPHTl5(35gPqnXs_WjTc%AeInA16~ zn*CuUp8mpsD>r0PpOl@hb-iu3Wm-=HLAXMV`_r_WIGTfu(=#fCB}!`Sa+}04XMidb zH>(FU+9*ZC6I0X^ryZdmtuHr3?yz;?L^2MoJ4roBUad#XY1p35*!#O10}qNy!p=u> zly(XMi5a6c=hxz*{k-}-=apKQM$hI?c_XzXrSxr?XqJPRgHL0l5JXVqNuMr zT$7Ia$EkDCD0-Xv_qW5Be7zb{X&Kg(tFKIX-!Sqr^uR~kE-((cVVWB`tzf@9o3}3R zZME0Myqbl*2Jep24y=2S58K7fvXG>AXTkZH(J?c&E;Tx+(=&%Ns8P#6?*gH%th4P= zLM@v6+qUi~?P%YpFiPloFP{fP?p}>hlwU)MOi2e7`kv!e{yDC|;QE|hnN8AlyS`{w zXhjY-6IUb;SEK~jm$CnzgIgrUKfsTYN;b~$UsM`ji=VKu}+)Z97C?MS(onx0T z;eiuSg!U%QYKKmZwdv9{TFY`T0{(isD1Wk4WN%ps|0HH|s@7 zvdJoTDH?s>8oFhdeU#eXNb<%6{rH z-Y3@MrPOlo(t2GCIweIH7?bN^AQ+OC?K0vW@%rdb2lEcFJ+mHUr@3!zC+$t)8iRh)=^ihU##@WkPv%{BY5&Z6SV-sidhyVk@8*7 z8C^B9E)dwpdFNO`mL_4{{wA!C7(46I-_RJ;)mS8VrQ^d^`B#eFN#bBb4oUvC#pB-7 zowGyrNovkpE3Mpiz7IRyFL#U6VJmnoUhAm2ZoI_fWw(`u58S?|hqTc#@l{Y zC0o-H>9+{u5S$g$2Z$M^>Bm}W>BLY_t9{A${^UEYzn7m9i)}xGHVyZAe|xb)_s~w; z)u-`wb#+*eQ2#8ryPj>Y|5$td`?Ijx%T9|1L+xXI6zlj5G?~DU3Y(7_ea0|ntrU6R#0~rgVIF$_x|Kt^_Bk!-wt0B8q=E4m`*2DOHN{T zk+QRl$K9d!dYY_ky$D-O(O#yBjBVrC9wo9JerZ5WIaOFUi^F`^^!O3E%Bf zZE~drFVdlHbPs+EjN0c&&Zck5c;C~64#T~vS=XV=wnzFz+}klGw7zZa2*U%DHkau} zQC77qLPbJ64@8U=23L;HxprFRxNA&dNg*a}UPQxRZi1ATf(1TO8Te|ejWLZ&J*5E| zzmw{Sn=9T|+%WTUZ{?~pU{bi*);i143a-nvaKl0&X{jD@xD@A{;U!EpCt3koT}p-R zah#5?8yH!h47S45Vbq!A&kY5h-MC3YsKN$EO@Q8FRG;hu-}cR}&XZT6WdQo@Yo4xvOL%|UgAC>@Ckj{b;G)fRA_E4;$&2zN^nHvF zedv2$>uJYfqe2~-6u0SIx<=E9=ictXaXtwY1rx4t6@AB`O-F#{$@L6wt!x>`9e>;n8-@|pGy;u8oTz|V zofMA{uZ6Z%M!(L*d5v%=T{Y4MGI!HpfUoncJo0T_tpIVN!mJ9SX6HmQLmW2TlF(@n zVI@s>?=5a03qm{#r43=NYlTb|D2!a2g{3~VMcQpn!${l=_3dU!RO#~<;W2TSG@!c> zGP)%z!ZWeOdKSUjP`AUB7EP>yGpVj=4`8NJ-owVS;CywvgqOu3&7e)DbEXxRS`sdN zOjNjiaPjJ4O4wHU3(d1U;{^yAwg?fmRqBN>(Z zs2uu>i5!xyRr^l2GYyja8jtu#oV3<N?ZUMs~+DZVgrQa-Dz5jJ49QBko~~V zop}N2;UQ5(wj)xvIo58vW(Os8E@p~n$7&!hg{X-XWD z4~KBA)8Lq-rKsXlEnFquW?`n?mM5Is9Uecwrs+&^bn42G5yNT02q%r&9b^gl?d&VJ z(~>s;Bll3+PR>h&b>pR}dTQsVE<*UFDMlh1wAV}_{NxHQ zZQBkre4=|_$`wTq8z)GScNd8%w{)u1+xFP_<=Yi$@+4KGymc!`wu%G4V(cblqQ4qt zu^34Nb4Kv17|6qWs_&7KC|xhKNi8JGzzf*a6AU-p{Q`RNB!3Fx9V2bQzwOaqbxhoT zk(VqTB?jgPIgy>R4uw<1Yi+$KYa_;;5)@nx9D(RAeIlEQGSO<%NaJ#pZ5aE+uRYYQ zW#?F<4;T;nh`KH+^t?!DJ+U&zoyy`EJB~OUNQFc9&EQG1aJ5w>CdnL1892`9BxH2F zHnm1t%d#!EwItWw_Dy@pLhZ7=s_7YQMYqH^QD`&%`%-(ieZ-V)*RoLkXz{G6(TYCA z8YfvqX=vO0v)0o|@{L7#7lrz!kMM{8{a~ z_rE@UrTDv_eD3VM`~Tu|z5V6J*LwQPTllQ@_E*cRB(C=KS1b8`{^z;7)>q5rC=7vG zwNUDb)34S;fPU;rrZQ_Wj~Tq+F+_nVb+LxpgYqXxk|D^ia%uiEUH*kG-__;! zb@?M*zN5=Orn6nWA(VF+!CrMNUlshiF4MX^q06``H2=u1-=P}VHbuu>M!r`?t-3DL zx;&xFxJqcDt2%4E2FCd+7}NMvA>_)Bl^b8xC?+5$bMRFI^;MNT&K)$!6*YK>@{hoC zTm<-fk&N;<2^IHPyVtGV>-qj-Z|Ds{U45gcf9NUF+~su1>q7oFfwQc{xBL6=Z~XDl zQ$?}GczHR`7>Aw$nH=q)pe4)W%q&a;docw?wY#Cq8&0M-l>VNlzo+!~J^f9ADWBBH zPUe;0>=)9-is3FEq$qDpTY|-E%)Z9FO2uNx+jprK&Z?;QMzhk#a&b1P7`Klyh|vOl zD4TSZ&!;s*KHSrpWpE-X2j#lL-WqEB6$`=_`jE2vvN@$%uPVg~ zgSutBiClmNjkh4!P7!RU^-40A%ZoZYHCs0giJOLZwIT-8;0B;eRw?(>m43i7Y7+7?|f!tT@cb_(vY`5X0t8` zSAuE4Yb`OKT8|Ram3MNe>*#ubfy>Q^uvyjg4I{GVjz{E+e&$r`yPEs9p#Ia ziUCFae6}~w!`FobB_^vk4gR4EK3#+lu62Wh$?+X@;yeY*NkpEL?@=z zlv0!VFZWdh`g5k{Z}dy|HE#6FpljSH)*$^W%mILr|LR4WLMGmih00@$M;2(cvKcBg zn*M)FOar1h=)6{~+@(84^SsRO5nVnb~A4yM2)p<;QYyoxfEebNUf z=(gMk1C^UoN>PL4PVveJ--bBoyr~RL4o!sMU1mSnBnf6;c~!9ZGM4v*rm^uuWtE$| z8DPF#B(W*LHjGf37jpdt$W8NkLPozjfTx6wk}(CxB%fkP$F|!!WR4;Yq!lUE6?q-N8)wI6>4|+)BCmmyyMCd$bAhGBGE;&gPRr7Gkle zAvHg(FManv6z|H-Mv~dE%m!RlRSqO;cI`8&4?@I#-p6LCe=?i`INZ)(e9+>qRtTmEp`VEl{qm4n_?$)?`n)uT;uY zzl_zAAFz8`a-2*m;zdlB-t0dgr^ck~8|oZJE(Eri~ym!|Up+ zJN1!`znVLpCB=c|J~&3bC~2bYA-h(MH8qUJE8%_Ey^RpQi0RueAA$SRlVc-tBXa!x z$JR2l|A)V|@9q4P&zv|?y|MY+_Fo_P`;UI$fj=8L`=5IL^jp94 z`A6Q^e*bT2a_}}nPlyVy@}$XraWqthstng;jY0_p??#iX44=SYC1a(Z7K9}Z&|B(YU7UFRlt9T8O)8Q zM7~Y)bDOLpqVh%_$__QZ;Jpp9um%SWb)093_L6)p8S15X7Y3*#@YndJNzs}Q0BMy) zzFK55!5>e(zW_I1vtjFsEYHgyFzrXNbVZ{%)cngGc4Q1dm`-K%Ak99~_q(2J@4)lwdW@nz&X4K=?$)O_8WeFMrBM5j%3UmOta z2Plz?Nl6bSJ;lw1LTO+?S*5&M4K=?l-5}={C47$q`eQVZtsSB9hRxhfbWfEjDu4nB z#RZC*lVXoeo%w&wHz3zwsYtc*J)->0e0h|*^baw$;;Z3FJ zk9h%;3W%7>l7#0DkpYSMlCUo3O{p~pB)PULhb3q_7Rgr?=QOuh%FVxo!64VSi-kU; zLw1JS%#LqIak=ImA3pEb4X4+w+3WBI%S#ZxK@+Z} z0lI5^4=R3xE{2|RKzCcOjUS1V$IBW8bp}!?6i8h|g%z+e1eK+luZZ{Z z6$V*8Nia-RR`XyAJ>hgQL<#0&2~n2?&82EQQ{r1$iZ!7Z9jB(Ifa;K_U(8$~;DTu#S+(_kW?vO9|N)^ z4Df|Rub6ZTY=;hh1>PtlMEoXULbS7kert1~zlg?<%<0}fi*hI_u-2PJ;zR@)7B^Z# zDGyyFPD)JF7sTnS&{~pXP=Hs@t9L){+n zQjbyk6_e_(`1~-*29*>j8+=D{yAGfZ*MB}3*7aaz@ttx_wIt2 z-~TAF)<{Kb`X$wtsI?^^JDMOWJb9DnA8>ZeC zw&i43Yzud7%jNqwK|k1-XoDUf^xwUg;uU&By&&Y zg;w(i;?w4vkPe9~IRFn!z6pS_Uo*e0214QtNjCDUL)TxEpb?TdMDW4&2{C#_VvMD+ z-+54L#FhrLqqNg#z$i6nBta92YIhYjG1(BjnUgq$Uhp~29@k|N;}rdzDk8v1mQPt) zZktw5} z=PTJu#oVNtJF#^=2Q9)q%b0}&CG}tT@U}+LXRENUVjZ&@^MkcM^ZcMCi%7!tS|xuM z{3i53T;^~QRpUgh;8wFW!5`~Y_-oZkpEMaI5)LVgn$DLe@~+?hx_nfWE=UHDX6b;3 z1g&LVqs$2Zy3OpjwYH@zOg~)z=DnCJSev;pl^?X9SB}3_rEH>-V(}d|Dx6F-l;vC} z>%rG&6rXyK!Y@mBx4#^@?R)r-f~Znv4l`(!5Z%|`P@*5Y3=uH7&k9H;BH@E+K%JlZN^4yjNc zG3J9=1ZZaw265OUlul{=;qw^(G%#Q8y<38lX@1kMYSehsg~!|UBJCUKS60>gG>}_X z&l(`9#d>0t5o?7|ecLoalZ06Ol!^oq{<^OqgBhx-1vKoFfMjl@gQQ8DyDO~bUc`~? zzDn`_0#^8cq=(%?Uv-<`FXH}6SIN}UK$>5^OX&X)@y69a$p&PNG@8i&in@4DVYATz z>L?pNH-w7!hbK{~+ zQ)&Jlb$+T?%}YKA0Z9`2KlR?i7TVv!PaTOfi>n%E&|tjF5WL0sZfS|$vP@KOwOFjm zZpja@VhaQO!xlH*|Fm5jQjA)fNQKY3hz0NFXYx4DlxUs9#|;%?T$-a?%%gnZTzqC- z@=|AVoOMyXZG{qDqC3gLXwp9;6Y@x7NZ@?NVE3unXNq|=kLn4W?1kp9R4Nq&D>K)k zQ1e&vh$iG=<4yG2+i)YO=?FZ5+=+XH?76;mN6#r1jJr5kLL8{RD8IwP2>|#uufqzLOjmu z435rlFe`qt-S4q~Y}EfP(>rlK{Z8Ub8%6 zbqyn_x#yih%zV04em*VS0_Q(pp7UZRL(REQE4X2=;kqn)BOwPA`Xy@9Z}SbeYSmBO z0f{N=iMgrlnKXMQ$yUcR>VB*9@#TIGP36Y zPfz_^E^N1-w5iQ3)#^2VQo(-(t+sHXX8FSlix)#^d_5N$zjJ6I`60C0Lx*+yWOb?&ug|+(kzjlP$hb^^n`M;3@ zxo{U~-NOoK$Ig}$&#|q|SG}kBe595SU+GO-eWjNNC&O8uQ+t8yI8V|{h6#Jj@CCk) zbI6Xz4f*$a?|=TEvLgFJK1@BlsrCIKDkbcP4Q_ddh)H8g0cu~!Zq5sC_I~&r%mjm`@X8$*7!Ug1~YZfGCBq8Q~dRUlTkh+ zV56(P59r}g{(U%XrLCx;-Q)NwwivVyO|hNz^FlSJ@ung;(C|#E^_ozCVz{vj<^a3)tjQ$f|ZY1|9Zw_ zhWs%rJxiIN57(JSogceX{PwiQyBBCDZNo*Q)vLbrK2{x7){CArTJ}!c;3l zvmg0YccS?E{Ie_I6F>pc(T^-I-)3!ySH0vi1Qjx?*PJ z2SP>;ub2RVKnSpq1p*`xmOvokjR_DF5(p+CKsLZa!tw~PgoFgxCGh>Ky6>Gkk|D{S z|98IgKcB{)ny%{V>gww1>erpovJ);Q4-t9s{_HcNd+^Dx`2xQf3?e&HeP4v`3OzO9 z9%JcK6WX?=GV$KDwKd(|9q(xG>9Ml$&B=JWuP2`Bi8rlijdxp}$-1JV@MJA|Wi!!I z0~-APo6GFlULkWrfe|FS9hA7DUi7$5zry%@MK4x*Gllh+SKJ^1ecwt0?V5j%Ai#5< zl2W{Yvmp0)#$F*x_&722Wl-Tz(m#U7iO>S)6$HN6!HDXz$(>o?mwg8SdD2$V6KVa5 z6K$$XXVM+OMYmUwV4jEZcD?4qAa&_vmjyhz0)tVu4=XSL4NdQfB5as9zE*o%YXUYDTlxOo8;-x?3>@d;?n7B zH}$PuaK%x-`Rf~#8y^1Q;?3R}mwRvOE?XL zFrCF{x=GVu8ys`kaw_U7mB8}45|x-%pgzZZYQQ2+xk>ruc0-1@Zj@r(4RyUacIayo zOzf@)Js_eEmRJ4-c@+pE+I`M0$7Z%wmn9ufou!#wb%oMW4fmmaWb! z8+Dbf4!a6-JO7!oCk!bYÊ>8e-kue9WPzL0lpPVnF59hc8r?dXu03%{FYt1#41 zEEf#APZe*(WtehyB=$gyOIFM*FcYMjg!3N&+UQUhU)Xki#NK{L#;d40o84y zc4kDez;Y4>%E47+mY3(aI0CoAYX+7;93jSf=~>hdlVUz;22IT;C4p$*s5_BC={ulr zSpvqx)S@yA0=1s<8e?o>0)|u*Op!|R;3)A1riDU|1}v%8Q&!>)hN524BZF%EgIt$X zC?%x@0q893^T?n6IjW5xhKbHXAB9VNQ6DOo+$t#syzD~sx?!Q`!rAFasWz!*l=y2X z%5#WGUqUMa(!PaG`wD}#6DV^66bbti>$v^?#9H~V(EZ^-=A_*W3u-8En2c+d6J$A* zK>zp)%Zh3$gQ2U!ra!R?I4kdsdTYJq1uvI|%GVWzf)}Me^$P8UGKf)f)La*0Ic7ii zv-tOrxsLn#V088bO*g3w`moO%g2cvXoPz0L!R`<=%X)-{kHHm&0z(Mq6}vQNEG4oe|)xAbF)x2(ih^QEXa z>bt5SU|QUl)2afw68>EBQxj#?O3F)tFhzak>)2#bFLyPB-V49rB~Zz95A8txMN)ra zscH|rZjA2r3)pJbR48OY-Ecw8a%9L5XIfaf1}ejUl!~O^hGqQ;I1yMUsoWtV((efi zRzP5}efCe#0jomTAORo2T;Z|gvsmE@lO|zM2g<^89z_9D^sO!MSXyt)ahzQqo^yj_ zi!m_{!X9NBPV!w8N=g=o0iDIkncbQ$_Mb6DXDO`0mFLQsIakv$&4$ZnBy^U-#=7!c z8PbmYwa*GD1xrK0oaZL6m38YOaLsrZZ~D*ZLY>R~s0K3oG6szr>$1jID|``(03R|F zYtXk;6EIZ_6aV+nMJR)YN7cT-RYpRRMY|C*!|4xErB%F6%GX3biRml+_J_{tDV zr^CnnR~3*yAiRaa^aK;-W`d!QLvN883M6pR=tq5ij0p_fsLu(1j||i85$J}EN0ds# zr3FLVBpUP%)vqwf697lp)f7x0n^%27U|Mk?FZy7R3hyBlv{kl?M~5mOhB7s^bbx0Q ziEY*_w9A?ekT?RMC?p>_5GK>Fn=7{V(Z>)`!tL>(mcrms?*J!nZ6Lh{de#)Dci_XD zJ_|4*9qUP7$LS-via7vq4-E4<8e3i-{~eqvgT-iALRvw6Z>Jq@pZ-=>DNXqMpwYGKMpTYcjShZfzebWZA)m@HP%H*GIp?XX)qp+);A-uH0@7 z1m)b0yXvSb*=BiOw^MsvK!%MqPZ>)374E6~m4X(Qo#B!|SxFFn8i)q3!jdPT=9Kh} zs3#;gmzhFLs>~M+!cT+IU^L+J(}Q^LQ9C~4CkGCz%N&Dh26>h}Y`mE`7KmCG!2k6; zoall6>6^J}^N~HR+;mYIK)Dfp?d;BYj)0F5LL|p$Df_rxwl-)cPJ*TKOkgtXdfGl3Hje+9O~l2DaMB+1*zco1{2IFXmLF3tQD zMF*C{0A@c!kF^g3%v%b1Fo$HWM%ubp2;~C^!o1P+NNDq3Y z2Wt$kyGF0|cWQK>Lx|RnDl`tZKLxs!iS2a*?q_|yI3cjGbl_-+AcAPV7!x%UtY%oY zux517T8Kmz;mZvBJ>}MBE*7+4t}wV?eYrf?7vPW>f&`v6Ll)-sFullw#6V}6R7aCm zQ8}B!UiSfk4~QPR@6-i0%2qLx|+c z4>&#{*kIa#2lPO5RRoKIFxA9dB#*U(X;P2D>t`Cn^{68g)a@Zm^@MGK?Yp~|*>$Tb z(DX7bk8?6$4=b52s?xR4_UP4m9EdDigM+mb!v5KIN|F3_GRdw*+4E4e2{z@vScOcd zB?V>%rVS4;QDx=2gK036^d;NL$K~|_jNQN3!?4ViV9o2_sv&ggU*>Yz9UBs!C;3Rs zsiQiNW^&(9oM|4DSJ}K7f&IPcEw6nPB>sXhPZNZ%Px-HEA?6D--5xz1IIH3eHkt=1GPnd3;KjDR35GwC1kZ8fVA+yIu^ohZq&i(+^&PsxfKVabCVB7XCn$-e4a7w^Q?pT zyxGsaq|3U`T>Hx4VWppXBuo4nKBVV4k98S*q&8-HtZ#54gv8}Y`_>lYqYpV<$1X_Nz8{f*F#x392*kVzI+`EmCY? zg^6~XGEEL_gYJ69NpaFKCLcfht;Yef7{2B}JLh^Vj0gX~W|d}t9_UbM@c0KhRl17P zTU9#F=`Bcm_;ih37Ojk#{amjiS&$rt=TJ~Mn1TtWk(Un!#>uhXA^og_U({JA`s7aa!24S|Y=#NP_ztv% zM!EQn4&ZpqU87@{TFWWF>*sDd7@fOD=n@YZgG1P{xgq57GJRZh|^K|F&FeW@+!j!7c zr_BCSKrNNvqypOb^a_j$v!83d;8--r?B{|Bm=>XJa=M*!6ZfILI+q1#9(bk-f4tux zjkr}Ox~lG#y?JrEALY|$0%YJl;nQW~820}KLnS1XMfbgP#g4n znGP4ho~mp{G0tV7Lb!ary;YTpqUi_0Wy(of25kwSjyeM6>*P53Aa(HxsmLr0mdywS z1Nt}@mlHTus_^rv!Fmf;4$I_Z-On1<%phb0hiCXr93TXO>+Kx4uHNz@QB*@Abc4*L zSTONDDtx++V>ZueKLHDR0&`k!3Y%jl?g7~^oh5xWZG!3{zx2~g++cGj`BhgzVi-#W zHFZio2=Ho;ruy3gGlDS}k>olx%5pI!Ed7>v7?nC>_7KR3sQ&z4&41jme`Nl%*CM=* zIvaIPN1d2HZ$fb_TxC6_?9+u==QuQEz(PBaGZ7qmB{el~CFRdNfh_FZdB_K>9+a69 zFbDAI%`Kyz`od)tg1DM*4yPlxsP)s=`M&HsqLoVzv!Au`syUM9ZD;&T95ws7R&CR~ zSjxqO?mn961rZyR)9|5Xd3cYe*D3u>zW{R0^!x1W{mh<#AlDisZ+_wYyt?b9KShqF zV-E-U9JBS5eiq8)78wJGvshIm5JAHOdpNDS;44Ua5^um7=o_3MOeaqQg0PCKElz(3 z<^WI2w{j2fbw`x&Sqd3e%CRmy%bBo9x_*m-JC zsC`&;{$5TM$9`W@cH*9qg5u+hxqMv9;J(rN=EZ}r*>ow(n5(Q_cXOBL7$3It6B`xwk}PT2~lEON>nZeLtHSYf3O<-NT6FtBZhQ)9hyhJNb;{ zmFELU_F&AbTowm^%)$qMJQNN)0{LEFS;8-7f$qGPU2nI+Q)Qo#k2XE&H$+jfm$bO% zNDtgg&4A^+JYbV}#h^YV5O+2nuh`jZ?UY8TdSFhEw=5BsN^##m&bB(#6ScUn$`XZ= z59Uhb2bG4b-@ib=dCE_@-_?Q}_Q8JYIMg!0MCCRfwfyl|Z^P9K0%O-Vdr|gKyb;Xg zJs+PnD^2T9V8B(A^=EwYQ1|2RIz8G?y`^K7o;5XQf~BCns>!%y{uDT07F2nx50M0` zw66xUCO=OEpQWQ&&&)2Ug~&J;@=WV=Aae0-ifOEV;8RTN415&uB3t^;8epnFy$nSH zxgr5qk$@^f0c8Me&>r=RT)j1e4kp3uN(VE6qZNNj_B1~lrSL0@v8snxLQ~@0%W?&!6ZV-MMOQ7@)R2F_2W|Orh<`y)c|Kr&kjH7R% z%rUTCZeFkkQFP!^^sVOrW>fX>O&K4A!?YKr)M&#R=5X}URaxf1`E@_Wqj%skc8EYf zW(@DZH&hz&+B80mcChIok-J^=VZ$aj8dwX)vL-Rc zALiFLi8UC!ITr9V{Doae8+vb)Huy>nURa%ehHH+AhI5LJxz!QzT z*;kw=;aDBByogYG5%NX$4_~f|hSecyLA1cOOE6ksACrcJEerc$TxtaiSwTD&X0xxs zqc*l~m3g`a{MHs$O&{X8YkvOk)l7ao1Vm9jq9p^JXVNNT#kB^yh|}*HwPQ_5^IW?M zv}W;T>wGi~&vL{|i;1kS0#V(~$AWkywA8}tEL>D`2y=MBaUsy$<7i>5pRln2gSS-9 z{q!yQEoi&CCFkg^ZpqoUdEbw@9|SB?AHWA4wpOp?9%Q0ivq8nf&OZp%>}MX2eFAk1 z#-k#np~w`DH!9XIRAZI%4g_EV^?2LGV9I(hoMe#l8QgkQg#N{JrvzD-a1(J6qI`yn z!ank70Tx`CH(#z%w>iLm`|?=z#EbSnIWl+dCVBgd{V(LJ^OOipJyM;m{S)<0!FuWc zSiNg)(`vguB(~@I-X!do)w!6qzKg{(tyn*qgi*&AgKE88WcITFk3M8VLs<^Dm*eMI9>EE0>dW3F)h%no0UNl%pD+zJ>E60DfJm z$|Z22T;tp)|LO}5LWkZbPo(-*)n`0z)<7prYxepc%(a9^_xUMT^ijxPJMMV?aqm`Mx_W4^98rwQz=Pd!9xV<#~pUB7SO*j(s55cFm0rH`VNC z%;^#~t&6~Y!?uOtX$jY%v$fAp(ms!Q!h{`1vmNaNd-g%LqvQLq;}`h;P&-Db{#a$l z%{c%0v8x@J7#{{Ieq*;^uLGD(+AnJb#?Szp=Qw2}E-O6jd$Z84h@vw$KbL^n(yun( zd>(}dgK#~K>s~IV1~vN5i3L}q{GnW4ox@L?pibSV;d?y?mG}R}qYf&T%%`JHSN61h z;}NuIxNo?rW9_Vy7A+`7ZRrKjK1m z?3{K~E_VKd^>Xa|KUS}8=SL4}XE)XCXUrLc_9S*NmUaXJ9RXcsT}9t6 z^3$skru;5?n=eddu@9quN|$dc_tRI)xzzFsNee6+$LYfbE*97^j?3_f;|fOI0lG1A+eW zOeq&QQQ#fpuN&{D`vm@VJabN}9#ie7r2@~dX8x~NbE^+jb9?LKf zfzJv2AkG#DO<-6puwer8oFed2fq$Ct`UF3nG?D2S3Vc@JI|7R)N!ta^oy0uL0J(pa z@3IeH2W+xDJ#1qOXr*w3B=1Cx#RTinScza=8XGNGT4R$TwU~AT^C5L8;bdB#qzmC0 z<0dLVp!){o7h&WyQ3%+L;4H!gToW1Kyc1XmPlz=OwokAb8vD6mb2Rp>V8<{vp_pC) z=7Wr8JQZ0?@1q7ko?kwJ_5kx4oOc|ZC|DTS7+OtdkP$DYQpszhb7&8+Lj*gSzD^!s zI8LB8d<*DG;hZOV8|iAn8U<^on*>`b*eUq+L6*4&*e2?sCj>iL@_OkhX;BJTh|(B? z+}fRj?a(baU zf}O6h`GS2_V+#bkMq^EaeP3e>(V${_1egz6FP6M#CGR`51nn!P-vc`Yw-d(+=ZC_1 z3x1K2?c()tx%;VGu$ZUP(?$_+`)KW8m%yC@_X7Iq z;!w5WryB&`Dew`22N)K=6q<7<;FExMDWA~@p69|0Ulh36&*}d}+UB`Fya<%H1%4p#Hi3_L7dbqC3m*p_ zqky4LV1d9W;1N_-a6fwCkb)IPl#VE9MIS8z-JsQ=8`L4Nr(mK{Pm7Bfwh3$pG^nfS zHo(53MS#1DegJq*(T@QCJ;EXE^@ta+X%us=8pYC*qgEh&#;73RxkA50;MD?e5O}M= zyGPZVWprG02_$q!gV3!P(5~^8D9cp!-YMyaCHEK6E#QAnDDOm5NS{;G4R}aw5O7+I zCCrX-*`oyRF1jA{M`FzRQ=vQ+yUDa|`xeq`2ls~=zANcJyK+B_-4FU_0{tbN9tCKZ z{V=u9+V49xuutuFbcSc`pjpl^ zEU-l2{_q(dn`dnK4&+t~oC0_ReF%FVLAxp#o+a;g0^Tq1sfvwA|Gt7X|5#vX45v%Rbbzj`p?ZAm7`D=6f$Vj5y=RPN{=H+_ zdddfWDCvD;uZM)6jpb4*w|HENmv4COFZzoo3jb8E{YAKubYUglu`X;Sv2ew47DWRF~BQMXycAnSQh!|*NQQu1W782w8 zedCcAbn>S8mN>uYv)^~Jv6lA}^4jk^*0+Jb>8`QGzRmhKWLe4yZmg)$yCs)bw9QxT z!uouty09<%dR-W|me5_Os;7MS86PR#rMMdCO_-^Y(4)$Ao+wca31;+>e6Zf1CXsjmi2Vl=??8v}-z~0eV zV_*`n$rD9paFt+f8rvXPuf|e>U7)cu1pBVW&KK-4ja@DnO;R$i7i^x!ZWC;$#_kjB z28}%?*a40GLajDtbUnyz3h|@vF>S?23 z=LW||p27O2OR)VRjxRH4P_S1+wUNERuF#xC{^yMubi2k{A}<1aK$qj#Gn4qS1hh8P z78wgnz4jM%M#@}RZ{&A4n0QTb8XTo0$>n@!MBXrFQz1@5pr1u@q|0_~veu?hV*vFA^z|?EMk48V>Lb6%;O{+t^eSKJS5n#QIUvy>){%@J&a#+C|})!0VCF3?z?U^i&&?BeZ^a=XSZ zEk2VP=%<3c9^yHmfnF1Azrk}r12+J#{XU)p7EtLN#vU_PMem?STBos-fHhI!T+ZY1 zuo-)2`H3u2z0ypjlD8kf$8-nsW@(ITSV*e{Q=@Saosfs^bg<>-BDz2@jxVj|V!BnZ z{j?*x-fW?FG`2h1kCXaBzMRp~W(naW6tByJ=SNRAm(V7ST@Gw14GQ+UaYM8Wr(jnI zrnFv8Hwea>on|hl1L7o%?J!r+$$VTUGu}$v4t5Eq#`J1BTVuQ~SWQ=Jj7QvRx=Uj` z;#Skc8sqWaN-t=P$9pTirZFDxZS;x8c)Yh!@My06bs6t#C@$Fk5YP5&XqL|7(Z7b4 z>O3BQYiN_s<59eZc4~~r`x?4camt8WL)(s#_5~YbXPawjP-Dwudx2e`vGuWj{KbG9 zG`1zS+&rFc*BJZ!I{K-`GO_Kzp4HeHv1;5RzN4|d$XibzY3y?3oj@Co<=VNYzh<65 zgYy|vJ$)j*sWI;94OA*Fs^*mqG)*w>>2H`DXp_b+2X-?X*p>{Xw>F2MubB?b$(BIGneb9dwt=OKJ%2~z^+N<&~8vknUqz4`BG;GX=if>)M)V)oNV8oRmF@bptL zE@QZT_m)ngep)Kn{t)|aKlN&iE#FUf+oW zkN$p&FIM$^Sn5aZb2LVy!@!y}78+fR6U7aJ?GKF>EUU4}qqie(P;<^4-A@B_g~l33 zFEz3faE#{Hh-Y$#jdaWLP?vNbMjP1$Do-ip*9 zyR2*M8nAvj(eo`A_J;AV4z{7J!*iVrOL?w$uq5ic!NIyvLk`<6*san&j#+!axsESs z^vdH#>eU$g;EnVZjondpp65ooR%4Hrao#-|J5Y8Z@(yV1w`G?Cdr@QTpEuD58hgEL zJ21IG(h>SQG;cZAzMnWkf0vVZ?e`s4ev`++ie{9bNjIx3cO*#^1>RW{Atha4))FR=RH5Lv7+nCU-8`KU_UB{#DE<6Z|lvZBO$ zzk@YZjPX9;U`JNOy$?EAQ^geTLk@OiMXh(AgEdvm_Wszx)}!2`4wkAo#`~Cqtw*_^ zI9RHp+50$UrH|D7_XMpMOs#vKa5yioSnhp-&Tw)5oGw;akXI}}r|)WvS1doLyEJyh zm}+{GUews4F?HanO&09+5Rao@(o&trE4g3NS9BiFhQFd~bso=# zzoJ`p9-n+YOONTivavripQQsjk5_rWrZ;sSukwCPA83qMa?jDyRZ16LtvyF)Dh%U& z39u_1Y%@Jiw+ePSO&oig_j#&l<8qf!{n(w}7pPBRvJ?Jy`i5Za1^bMDr`sHCGrqw5 zn1h|=eUaW!7+o^tI)VU!_|VMmLY$PQRlE1lun=hTqf5<5dlOdhif1%HK}ev_Wm*emFxH|Yh9y*u_M?_2ao z!IYG@X!?4t;W6Sp&>!ec!BlJCrcWL0EbrSi;RIWk^S$rTEQN^$-=$50DGRtf21f?V$C z@l4q)@N|K!XFkv6LLUn8tIXB>OE#(&m8;4=2)Zfl<+E~@Hci^TA9RC;x8n0Cs&&CQ zOH=76(tM+1LzC}#Kp8Fcrcunf3ebZ)9)2R?Za}+6x0OCO9TjQPURBqNQu`|+-F~BF&4<$!McH4~b@~LBHV9~tJ3YLvpNc)7l6sZRm3MuqB-h^0t5I>@ zD7E~v>AR$q+j^hZ>H+b|1H%8jKu(*uC1MQ~-JQDfaoKDb-4cWlo7ZXZ*2C?3bTDxDh<_PA4&eIh|==$7!sl3Q`VU`tl%?$Q|U z4`R4YDWNLBN<8H<0h9_ne=-68s_;umSL2s%zKiqTdvJF9Fuo-nq#qNXO+O*<8Ni>J zzY+MVP~H;wzQB(K8V2)+1V#mp0bFiQ0NhMd4WnwcuioH$oO*-rZ+6kBs(zYl%&%JK zYY_erPciEkDCy6T(0sgUq3r2kO$ZQm~Av#MKtg;X^D z5#KI4Kl-X~k5M`PUF6Oh|A8-xQ=m^kxjgFivxM!m$5=Q%?B8pw96!px$5=PM6!g^i ze%$Nv`d|;}3^U`8KyGIIJmd}{H%b?dUk=LokaMN6e|(4kI^$R4w*kI9-U57geAd5; zJ{$iP|IJ2Wbv4~#B&sj+-(fUWAK|~(SXF(N!L?t*HCEr?FT^Z+3(^~_@A6z{oKkIx zZhT|N7D&;~>h)%d_EbONf5N!3`d5J8tG>_JV;qND_?zj)>fiXEG5%1E6{qpn>Pa{( z<YpH+Y0zeMC*DR2)?x+ewdCH)&?Zv5!LZ;X#4{dBW&T)YwKQ{pXwR}DVr zy~EfQzsUcV@wNDhz+1+3@oIX@_;Gwq;C+M7i{Cf+Z0LQ1Pk}x*3JUuIAvrz$*x;So z#|B%EDd&OyTD%NvMw)P8AO&qN3q;MsCzRnK^&XPAd=63%{>`BOx@s)aG_eu%qKR9)^=5qH(jez|@Q)*)!H4uuBS^`yZX9+2E;CHDo%eMRW63H?o>za#Vyg#MAxKM^{< zMGgtuOqSDSaxJ|k*OC?bPLpdH6#Cgh{|YGhWmCF4REIOiXTx>4cfT6x61pC6oTO_6 z&ZGxHX{4tCkE6c=w$dHoKam~)?4X~A&+?A*78_^zYrGE!L$OKTF9**a*AGf(6~l>i zp^u{}|AzfZzHPp4U)s0Bcc<^CzGr+d`rh)5@hAL^{ucil|H=Mc{!9J0`|tMu!v7!s zKltDC|F{2Bzc&yLj0%(n#stO(5`n`5vjTGiCk8qLsle%h!N664n*z579t=Dm_+8+w zz~2I9un<2JToxP`j0X=1)&!>qX9tfCwg!{Io?te3dhm_lJHh`BP6-_wY7VUmS)rYw zvqO7Bm*8<+{+bp)*H{XV8I8O5Iz;;;V2?$hw1CovSic6*eiQClld#ZM{JupBzLi1r zKZ_>PS7-`;#d|7!4fl;-NA$l8zh`kH&B58sQFx~9OLEpS;5`&}IM2(Ms26#s177Q$ z4Y<@`_#;U_;+>21&ouoqr0e~h`*VzXn|_r4TSzzguLo46R`|bz^a*}0yV-v$U`le& z6-p}j0VunI9|KTKdyM=PD zP?XGTjMGq7)up7pY+MD(pUPO;|CC+pNM2vga^5fh02HI*e*jA=m{XOVQ4#Rkqh{_{ zF1v8-Zcx-1TsM|SqI(Q32{X?L0@VmTWh`r}bWoOYk4@E6s&}p%dpRU4$|q9FH|~3& zFr6cd2di8Di)JQL0YLo9mEZ+{emsF>f;tK?h&7UlSW^O6hEEf#%yN{k0Oa2d9)t8) zK>iN&IKWD*J59X#$*=K%{M#fG0ON@4CQ^q0PQfQMp*YT{iBI1MXR{=R)Z zU>$D%`R_-~2Aqz#Wr8{va0cR*iM*o$XVI~Mv#9~_2+RlkyR6NCa}Xi<_Cgh$9cp`4JuyZ2|@MJm-ume%pq)vPT&qSFWu*MdF+prQgQJ!H6w?8Is z+Xj$(Dxis5vNMtH1~l=6_a3AzK>SKS;<*XA=K!YZJkT?M{5MMW0`}2Y0k_kIpzi=Q zad-1Iz%#L0GjV@&Dd2gyCowT2d=qdl;yJu@M-+R&Kzg8CeBuW1^6t^N=>|o#IwnOCapH=0b7lkptK2G zYs>~^jlkoLBSBvWi0=g(bCEtl;0EJMpqwc1B;#nLPd1K4?nXe9HW>{_w+rmR)7&O) z7T9StgPsJ$H?xdIfLo0gz|)N508clT0S+4ctn?m0lfG=M0{n{6YQ%72yns%q3e)?+ zFNMfhMFjzayo0>2_u&c8wi-;fbi4N&Idwr&zcBs~v6(CPGDv;1C4_j0AEHG}ES6{} z9P^f0oqb)&W2mRECzY-1u+qu8R8KaU-qPNY%+z&ubx})OGLvm=&m^1Lv+cBe4f8Eb zw|6IZSm{%#d3&-ayEK)_CVP@;o!ba0)Y7mu+0(I$T3VCo?WqnBSdM}VQ(dTnR>J~w7R;I9oZCqE=crZz#3--ZOCMj-J831 zwe)PUgrGHU?(WU*(rGS%FQ&O>90Ni(R$k+s<3UUX0?Iur-LW9VE>t$paH1%0V5 zsf6vuUiEnd$go**nhmAQpr#~zwmoa5SEf@|nk^v39I~>MG`%5~Cpb&8Uq#`bJ-tChArfP33!wz4|4BCQjxsqWscq>HCJ168|H zo2hjdhD$fC*nA2+keYk?x@m2DSD$iOm06eb&rIDS9$Tpn;$gO_o?05M?q0NDb61j< zwWl-N+PfC)TAkdY<+U`WGQCztvRfLvte&JKbFJT+%x-K*Z|&=bw`Yhk+sk3Nb>EJ&jT92OR)dQzEfNavcv3S*E62d5nt@liWR5GQL*&$jlS&MvoAlyCEp zK~PM!cco5G+R<)JPnXr+X=ApLWFRu4G=wW=h9Y?lvCB1D2x{7I+^#__>=R;I?VBlt zNS2vrqo$NZx^|3rmZ$?NvohL}k%p?Q_B6*pyI#0F*K7~Fj07TSgpfolSH&*DwonW; zJE+>VNf5;t%w*uc*^X`0lF=kR8z8Fo+7rXtWIDq^db|GYRTBku^rcy_Gl5`Q+G!&# zO&gb`I?`6g+LEQA8CH)a&1)PYU{Nxw>uTOfbsdN(${@BPY!X`;PNS_nV+m7B=J-@k zr?tawA=jD9m^q`>jpVZen>k~7TaKZzIhUS0+m)V^OE0r|mbcB+)a7lnoRq8746OI1 zi&4+ImAUkc>CKQpIo8?FvYHho# z?1>*fVB4i7BjytVn@%Tk*+_}WBm?G>Pnb%5&QYH*QA>u+!*G^B%>k1LC(I$AE>ke? z5uhp)*tvG|hu~=XPzvTOyBSB)b`I$qH^Ko=?Xh>Zu7G`Y3CW0w;-W$X{3NldmQ^)f7Lc<~}5Te$5> zQ`mIqS3wR^yZSmgNGDJ0OJR=CE0mrNs|Pum)b=DTx3Y+pJu-#0o|@|I1$%2>2d|#& z)Aqz^Of@b<9&4waoljOoa*t>iM|Py@Q#*wozGxVmL!8#XP}vS|5=)y=D$8(M)h zHncS_TCuvNxs|f^A_=a-aUe-p#PQsSDUJ6x_H?WVL#Az8I@u0qmc?S7!tgs8umjdD zymnJUq;K;{=m%{9hgaOBb(_`K)rq#Q=vlF&$CjUz0hUZ-*5!qRYdUAtHKi{{T+U+k zfd#RwvFo^MxDB^KSXGj#3sXC@*qF)qcj3aO^VsHCUGPda*=EtuRv%2&VG8KV-L=`$ z5rcU5xu`GINu16iAhIS6iq1(;V8S%kRavW-8e#2h5=!wVOD&>@gh zl9mG*SjWg-QHDUO8fHNaV1BPT69PeY1KhAV7hAAFfE2<*;;c3I$x{En3}YliZFx`M`b<} zJyn6!c35$NR+&kd1k~{g#p!u}E_O1*qN@f?g zXSOx+S%KBNQK-CwMY^R2QzAALz+?+2T`t2ZCEF=Ik8(`mO|;q{r1V0*)3pO@NT=I( z$tD3^#hX_SGY8pYwqnPpb}*Rpu>y2$8MqQCofbDnqK6MTw)Ay%Ij+E_(BVTTxffM8 zXnG#v6kKRaVJC19E{s@nTA!L$oT3hcE0dMWz&bm#l(o07ZH$Q@F-0((y--^kXIiw> z+GA%(bUdB||DlIWT5daQnft2$?*y zJasCNo8=a|1af}!&SVEpb5vaCc8cAhoL(L>PfJFZ(s^pB$T@AicoGZQt0;Tv%DJf3 zR+D*LDCe>*Y)v`ajdMOmwNhTiW;?A`y~N8{%q-X+AR@qYDw|L4bV^qAwl;#e>R*Je z%PHsBAlK|%ld-Rsm9aF{mgg$$R@wCY7{q+8sZTF6>PVC8YtG9M4eTEW~p!E)HD ze9D>ro%2-`%4ZZ^9TGR(btJ4s4Hq+{0M{=^zN?en7WQM3##T$*a$(x)rd(=SGP}*{ zv>V25!E;lFTLZM&<E)2&#d<+2)=w(>5gD}^Osj%rKFTMG=&=HY-L!b|7&F1?Z+&h@z&m}fha-R=+q znKR@H)yiy7DdBR?R@WiN%Q#PgnU}Wjvie*F6@DDflX21_mpctEi>>MDZtp=GJ0(^@ zA6c{W%$2hn#;D|CrHbik>%y*f{J18FDm)|5a+GGL=S7HhD%QX91DrVFk<9`g&uHA% zjw4CMZc$p~R6Fu08 zkd@sAJ}$XBxjiLE{1D8sAd@>o!v%qTj$bFIzBne(_m*}7V-!<%M|;<@_Ks~StlH7T zJ*b}P5U5g0EKs>-bH=w+Z;wPlSdtvj>i%z8fqM$iDi3$5|`W$t^hN zhxcNOj>~A?nK$pm-U(q#My)ztz=^PuAeAdsV1#UYsz*)bEqoccz_PlM?LDMVWwx?O z)eVKFKn3SChZh-qe3aeB;s}cM;g$rmv%QGm+Y1!XOA7lgLkq+q=l10CB=$%W=(+YT zXe}4`*5*^}jh=J#)Rbz+o->n8b!7OsUXETNTuXCNnsJ=H%dw}q+F2_Zk?Su1KaI-yl24Qd10|5g@$tl#RI*e0 za1r}MCTn#&VF-hO1CN8#HhyrRU7lXx?Y7*%>myKg|F~jv24f)Wie&InwFSURP~Yxv zv5$qMS_nZbqYU3$P`7k6IW@`?6%Ll8w@FCC4nZwxxKZd-@ojm|MAo2a5FA)=jO=8W zTGoOp2%-Y?kZ|d$fR9?FOEUMk7+~wdIznw^9@B&Za3ArBp zAp3Ay8=kS_QdINz%P+?>e%;J_5IIg>^-wv>Py!}E*{xi*WEoOfXtoVcX6w3(Rtrxb zp6tsKl{X32foJ$qZtbIOLdRm>)}y2WJX`T(A8XZvvKgXLEui$Ey=l;3nK5ph>uCp< zSYz}`@L1CNwAhICB>Wx%>xb(Ok&!|Q)R0rB=<3L*a!Xg%?Sej?s_t=I-)X>8TAK#s zbOJ+Pj9DgHSa^nWH8@!Nl(KHsB9zKf6YvbQ>w-SGKC;`4hf=rW%V)J@c;fgo?yZor z1>8H3&n?~nP76;tCQ+^nm|Y81wW8)z@q}g%q+)nT{%Y`Az-Tnvd<&?m4;t~@=4w33 zZI_PY8O-T;_A-uN_+^`Ifo@$WK?OMus*2;O)X(EIW_F>>W<0Cfjq=<-hvQk*I!I+o z2L8Z3rg-Y0DQi#o<_>evLCVhfyJZ!}!OG71yJZyzo)43@x~;nmtzgfzptG|421r|u z(bk6NVbi*oc1UYZh5dVx;#PH_56M$URF&@&Sjk`{aL=`))l}U83pc>_ZRojX$mQQY zZUt<>yBS`y5q{AON+Wn$z}p760(>-XBT|cyT7jHqc{hMh^2#@YUrAUb`7I)Y#@Hju z?$=YG2geVJo~V2LBz)GR=V^>hsnrzDnZZxxdN4j_^Qh^Oe$B!MdV!^3p(N7nc=w23 zbs@#R$K$#OBY@WqW-b9>@OC4W2BXR)**M1ok&TBG=Om z-|B*m<03mJVI@j*!0%P`iG#0CbclnWwc`=SZBB_#bHrecGXi@AZU)AE*oT_A1h*}V zKBG_%QW6hGbBUZ5cFb`67~j1~A{t}7L|Xyzs0gIQRXfVLt!%9()UpG1(Dc!@7)?X- z4E(`$jz?_c4wUKvR3lw!&fg%6OAE19!<^6vJ$a;Zt5|zglE=9kzwo#cdt|dcbze`4 zBhB^mzhi{1Mt_dS@Nu3|&(TKpsA6LU`*=hL`Bg# zs3gcW)-#yRfLY8~g~uPA>+#2q#^+>w#=S(bxF3J!y*Qc(K&$B7*wLZ5M?RyIx#qcC z!O@(W>Fd6VOwx&O1`Xl%yVAJnIUDLhH|@FU-d zH3i567>Tf^^L;@n4J}!GC*F(kW`ji=qz57lgXj$utrsZPTrA1OZ0pKU+(Z|}3SnHB zm@OP_;KsA0Vkq9sywPUSx;a)1*#e@?=-k-g+0qHcT&fub>cerb5s4j*CP?4SXG!ys z(Z+QJ(S+EB2$E(cT4lyI#5S0I6WJ|zFB7FIg3vhDS;ZY0+rYJL5c&o#+sVc-W1a9A z$lU-A?(SYcJ6p7un~lG@3IJjj@12stn&8=VSfVmg2^fj6Rm=!ef{`E^77ImU=*%L> z+a#53Vo}o>%z`TxarvSUS{9uii9}}w*n5x?FPa{!RTPy2-GM{bNUWAsna*GqoVCb@ zrpQn*V`l`|bg;QpR>-Dh`}@$Q!9lM-I(RXI3nX_c%7Gy80v=DC0hu5%WD@%C1~t;Y z0!__G5c)-sg=Qje75CGc*ecWlB(@m#Wi+lVIdpj~^k!ADe3W;dG=z zLlyo21$20}(ucqPS{dOEu7wbz3WmW4L+Hjv(v+$QL`ZoF3zdV{;%hnN9mF^AF!cO9 zP=T**ZKx+Ne`C_1rvzVKJapaB&s|@%wdeVl9-s2j!cSh`M)!MKJndJFyJhvLjeUC;K3%iq zulJo%Ut}Km`i)PodZ>H#o9E8_i@E5y6$`7*Dd?DRb?Dni9yRIt`nCV%dG7H$FF4|v z3Dvjy2xh&~OBiP1fEUSVA{IBj0mLEzLRr(%BsppAPA#I=LLi4g86W8sw$yiz!PgikTJsnA0SdesdJu; zrK1rk14abZR7I*h0d&FC=-?BGGL>8l`U2wxUgbdyG&~-pBEd)?!11Um5{b>P@|Z;d zL^l2>qEP|^%#YuO<#86k2P!j76P;TXiA@a#d=axM!Wv)%di}A%XHYdDDxoT_sWJlj zOyD=Oq7|{hU!!`AIFwd&KYTnGL_k4p;vXgCM`chV8VI>dLjVh{WZO1K2mGf9e2aTv zF^0}tu_`uxCo^CUf}2;uAVFWijMbYAXS20p6$});wATQS%GXFBKS^q6(Y?W;27a4J>zqDP2%m$!-wa zV{q|3zJh=^x+i2J6{`xN85OX6MX)g758@-&qz%#wl?b(77^zZXUoaR(cXh%+I!)2M z(=-dY{@6BEkjsFV8`2Beu=ZP~ve0ZanKKYZ8E_9GA^^lf%srjKEVR7{-pfreqtg+I zVtd9w9``X4tn8jKG5n!r#EU9;mOeRsi4O8)K{WaXy#n3f;dD$ zWUP|=7IMUh7=IDn&B`7;oGN*d1fx_2#Wul+$wfMK5mv4;fNtO+BjuGSAFoC5eJUDN zS9du6tE2KvH}bELzUuc&ZF-R!#h>2>w>)9210e5Hye$OBaIR3_dY&)Qc5acfIl zJy>O>vG^avpE?=5)43gpCmN^5@r3M*T7bE6KIO%oXnZA~R@N1T56(9$z68fRnfUQ_ zaU4ONno6HKEslfSZSBdfcw=3>ZHF~2-q4lYnM}nS>f&oH9L{Gm*7k$Ro6hylh_A#W zoT=V;W4b-H6>R9v_-ekq$i#7FB@e1%4~IW4?vs|l{|uZB$m43#DEuYyARCOvvvJzY zvg6b3y?DmMIq1R}D;`tEUtM@y*aYn6bUcT_@6mG zJA~r%bF3q&5etl1V8j9=78tR>hy_M0@c+66_^-tge))n1^Q)58BH=WD7@heR$ky&UK5D}?hw?|Yx}z8iZqd|y56d>*Uiut?sd zyI)N}3`pgZ*M<5tlux1goS9#fWl7&AXPJCs!Y7!{J(_Ub?wt<726W1uXb+cEC_K~A zZuM^#&O!M%Yi8ja@&-=jEu0|piE@wojtBY6aYoz&y|TDn;FE7GnDNUW{F@|p9iMYc z2EI7n^YH5=Io`E6jpg%reGiCyz8#s3cRjRW$e(jT89>&l90h?`ih^=m-+lR1FF8sp$m+=Aag0GTSXeTyccceyMV1YrN*6uSR>OUdQLln}zaAbPM_P|9HrV zqs{!QB&R}t8gLpY>i&o8<#Tt|f%)3NWl4U6)X!)A{2NmZlDigpd}E|;DEW5oAJuQV z)7}}7wo;$w^Q|b?%;)TEJtd86W{p-0jV;RU;M*p?nMk8nz9Ycy1zZ#J`a*d*-&ykg z3bzzDI(X%LkZ)DgorrzD@8*u9ZCg-Rjz8zK8^o7ZKq_m>KEl3a`>=C^0{TDiQ`7Jp zJopt+$hOe3KKPvLZa7bWqWLl&@_C1jiZ2=yO;UdNZPPy^LyS5CMl3L5fe{OgSYX5g zBNiC3z=#D#EbxE31s*2(OT8B#`G0#uM)V)Cz=#D#EHGk$5etl1V8j9=78tR>hy_M0 QFk*ob3yfIc^DOZH0B8(6)c^nh diff --git a/Mono.Cecil/Test/libs/nunit-2.5.10/nunit.framework.dll b/Mono.Cecil/Test/libs/nunit-2.5.10/nunit.framework.dll deleted file mode 100755 index 6856e51ef08a8e681896c3a84ccbeea8975d5947..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 139264 zcmeFad7KB(&AnIt4Lfh083Ga+FOAwUQ_1PBm9LfCggq+@r2m|eO+;Bmc#Vq48UYbeQ4rA=QQ>=@b8b~vRrkb*yx;f7M}C>xb=G_C zx#uo*>(;Hk4?f?x#uyKOAAV@e-T39d>5{HHSq^e@_r1+#b;DC*?@r8oYV7P2POS7S zDwmEgANi@CqmMlKPnC{2c497<9cNX~+Qpce3DR0#nb9>o1V;d70W8O{})1%m{jic8+_@#Bkx2WB?68rgUjsP9_!eb7~HT??$0IvSZ z6%q1pXXrhMSJ2y%R9qyT?wF-kUlmY2NsQF^6;{Ohe2GvwDnK9>diG z&pqeW`?h=HoUTXaZ}{z>ZTa8>Uwi+A$p`PX=reErWziF7Uv%HY?-XudwoS{|o?7(& z(Q~FSi_20g5;I_9Neo5nT z2Rnsf#$-_#w}jj2>>zHdJ=1I2Cne4PFc@HKz~U5I!BT4T`J4fAmys+gwF8;|AdyY= z_c)5r>rbfzleM+ddoQTN~520Efglve1P%olov@t2fc<)5VEsU|( zL!i%dDxC}rS)Q*8e*JNN2BR&pX5o~#PVBf9fnXV z&88xavoYP@n#!jlEi&s!DN?R)T($1u8^#(7DRr>FQ-%)~m5WFUn^=GO$ldB8=Y^3o z99O(h=(nPNTW5JTKs}^cp28MFbvn;QQ$%-?cdt(kq6@`&6s@b!3}a zG7Vno_`vniVbMpxkk6&oYzG#`b9Q2PYRwJ-(3V;=-3P?xVj?f9n=(rnozR*q9-CSN zGgZ7=u3f(Zc z(1YZ9lkS|`m{!VpCw}13$f@Ui@ZpDwYWIq!)$3jA^G(He z^++b2DQ!s4Wjg0JWt30d*1r~A8!9)IE1HJhtsK|uEFdDJ*OPK^9)rHCHR>(TotK>7 zIXCO1LfJLCO+}3968Ga#Lm6q!*JqM*o6@Ndyj(;7tJ+5Qf=&!cb#*SF(x=y{br(dB zYF(geUy=EUXO4tk42Lnj$&G+EX8M<>&(Dh8skw?VZ|^Yo#6~9_%B%?yZi|pX5tGL9U z3?ij3p5c`5L{H)d{V)(ejv)Nrb*SHJKX2y?J-%+4zYq#$VdQlrm@yFu=7X+weVFpK z*zUS9J%||fifK%Mc%ku7?b|U8K(Iyo_9`E;wEeZ^tLfXTyw$$l^49I!eSY;J#{%@U zM2ZjnISMookD3h45eOj=*w!)B@$nFOF!XtSBlWlQ+}%*Ajp=-M-&N@nVlG=ubckZ` z`?{@fDJLZHEg{jZcA>+dZfH;*nR61tM4CT3=R}Di6w^zj#slY^gq)5+%4iHnVrRV1 zD>e`c+2E-S6Cyl>LOixC=;}jdAyms#i0}{!@gy`axHY7Q(0|Bd?SYi)xs^U31i$g8 zuT6iK!7teY3XBTM4@ySihK4>GfqGOht8)i2L1C}2gqpe}IubvwmWNV;pXhWHPPLtE z`y|)QK|EkE2-=O~_PK5`rNh_YrVz_#iyOPC%a`1W#?jY;tDAU*K@$Hl!eZX$xv7rp zQ|OX0LQsO^BG6CNxgVP7+adK#2+oMb&1MlELc$Y?bz&Lo{QbAFj;V@iQ$JuHMbpww z;R|$v+AEF;wF?^qlfWw^v6WD*t&@Eosb4~3WG19e~Jcf2U9DN;!hp7*OfVvS}dotgiDo$ukwx%v`OfSizJFrtT z4kRg7SJ5eUwBn*Y)tYKe%4~+TCo!^;U2?`iKEfHG4H?y&xqLB+I-Fw+lyT{$RQ>~o zgaA{m1?QcZnkVC14oX@Ztb8gn_i`0(2y*$>0F7KMo`^b6!1Srw|c9+X~OE^?16%Jg^QE zc&L+j$3)$aw|fv&NsU!Z*BEW6>c;fc%O%=Ew{#_RxY4aT<=^t(}IUggv zM;>jl8!d*+nEUWYZUDRNicCmVdq@ycT*!$_b!S6j2tv}U4VX}GuW_By2nQk3%Q|q_ zFUUF)T3V?oVNxX&DkVZn$7I;2e;WP5sFh5rOxr`>0PCbQR+UmG#yEo+H`;dTT559! z=*+%cc@vZ&RltaY&K{F(lh(DY0q|oE&c1;4*_aNd>Cj@(@G(s@Kxv&1=-@B z<%0qgoWWWyTt_knk!-eDET2@D3|7{%vcd^q#nKjhkuZt91DSz{O9?Wui{^xPGU!IP{FlJ}%HWo+66f_w zzbSbK{iZ8%sxg;z{Q{_*?bFavVJdu)@BbMrfj77lei%Zq-7$OPwHmhP5doj>X_~Ca+e_N1j*mRW{XI)RE}OraI^Cf_e`Yrix>HWmnTy zPC(TJ1+(aL^eR>&>Si2B>{`G2nl6VXhC;P0z8h;yKVS&cvHGr|r;GC1?P=fT7{m(u zakS+n7%H^W!uZ*gl7%t2sj=AVlrWFZmN1}mo@g&$e8w2=)iTX@2!u+iNTX>{~>uNeh>7(vYh>Z@QnpUq-fp7o6-;p1Dq5-K^1 zK{Zvv5SwjJ7Du-x1=r-HGlgG(fU4$=7`mX`+T%fFmf6Ktk6 zUBbjOYhL7x3X|LH1gtz)rB*`9TbC5p#<5H+?FADA2Q@x%f0;l`Mqc>^a1|~U9F)=@bKwu%5wsfXiKb$AM#_w3R%d`xe!($nd7X`G ziy5&W&@b1H%&76WBSn#c%Aj<%zbV>sadk+%8+KC>w4fFCg! zzJ$ReypX|+=TAWgCg*GyY9Ri`mAdWh-kHmiFqw!13rwsip7? zT$05jtiRy54^!Z`@r$}fKPt_aMsEsB0;4HZ&**)`=)FQl)8;PNto@xcKn}@HGm}WB z`a{F&$z;{zUie)YGq^7`+n&QIe>#+dw)1A>ftw2WrE_q9@&;{$QRCCx!e0YrZuK$K z;H*G`_J;XAG+WJl{rHpX!C$r29o#R-S>tg_I0~WJYC7EA&5-16ygNn4_TkvS_fpbAFs>{4fd8L&N)b$9!0O|hkE;NWUVrlYhSE^`e! z{}5KI_3L%D8s4P{+un#nR!yp*^d3Cho^%H2{l08#GXDWbUPPlXa;0bOe5Ljam1{8( z>UO3f%O_VXsB|nad20H@4?jdNk=BOR&`KLcVWzdgZ)%-bM1p(J!x^)q^b>eb1lJ6@ zX8eujHU6<~XX966(f16@z(lawE&rAwD3hn+C`4o~847rMQ6mxsW(ida)5mSd*28fJ z^9I+ffPNZd%KL&)!E`>0duv+>XqTO-@{u4YN~fxr-ee~PT4g{kpGd8iz~DrwRrquf zCMqPHDt{s1Psw9aX||(K-os!|AMA0YzaKmRg2B>^I|y%hC>V!;#$t!Y7tAGBO8aZA z3grFj+D@$m2@@dFf&Uq>+RtrhHr$!F=k#>~PB5mQzEF*&>2!wN$&(%#`)Ekb*oR)m zOr$&}ypzyXsaZQhi(B}!_E4~+&8kn8Fon*V&c@Wn+iPrdal7uKgoZ{kWvz{lilE$+)I%dOIgQN|{R(G%T12P>~&~5i5?& zXVHhE&D*h7@~g&tJIdnIWo%ssUB=QXeILio=R3C~lC-`@2 z^a1-V;fJ%xQ@W1UT7I;`>hePdUc#a=h;Hdd{1&hilAN@}EsaphAa!V4bj-HC?scmh zp#5%XOh^M3l`mmS=US0tj)$JfQcsdusSBK90=j?ZE(o`DL)D%tOG=)jAo2><)Y3?> zVW&V%8PZw?n{bk9(V|Z-u^(-&1Ule2H;O7=HZzRmaINKl&2wq03HXKU@zU z6|w<+z|jEx*bLc1t`g=ZHMWdaTZE1=(dvdR#JDAly|@o_2B_8#5s8seDCZU-S@;{v zq#erRd&z&!Ba798$B1d@ttU_^7fBTZeF;84z`YRrh5=$_?N|nZ&|G~4c#yBpgK-8G zVw}aW+n>^lZDYWHlRLmD|eG&9FmYPX}{9Td#BN9_E*V){gyue z-_Vc$H}ucc(xdj>TgN`egXX^`;ZH0In^lcuKNYHj)l?C$gB)~d-MWSGRZ)~r^S89h z9K>Uofx4OhRuV()i?%%5z*d_6l_o=m`lj{GC=%&>YI0zK%- zV|p;LmU3kS9`xcLfoEr{=c%CV7e@5-z(2}UjqyqyX5R;xor_&-0(}?N=u@7MzB
jGx_)XGKVSL!mZ7A z?}9$BR{Rx1;BOrQf7KB9t0VX(#H5U;Zs8iA;M*hk!nHmcF|76|{<QMj4CT3P+%btl&ek z0mH{6D`SjX;m8unSMZ^H1BOt(GM=~!KgfJP$e7|*IHXve z8rw3C$S@-4z;7}xxD^f^fennAq3|+BxD^f&5&oGPOB@#dEj|zZ!e5yHHH88aw=~z+ zSglj(|J@3Qh=|U5co%Qh4DfqC?`L#M_TyQHKIwCsj;i*&b zVV#H8>XdQBt#BBL=#;U;t#Igw;AOmUD;zE?-sL+FM#cy`L$iAJ*j2x8!W`V~yCtr4lx|@nt3-TP;buUh z*OSF-$~%QyfyC(MbdJvsQdMe@8TsoEEXQb#L2hl6avT>3bqcT3t&(+Q7Wy*C{Ts~P zZ%XdURR#oYTT>O=fdY$)Gly!wb-D)-C67_mslH`p9_xU z=daK2w-DMiGKh&Ef`jd&t4{mSzCdHylij3}F=XrO81Zj)JmL=+qQfy?#qVrw{|ix7 z`cMGRt_HBkhIx`FTVgfnfaNB*lYm`}sa2vPgN8HkDIl;23Nrk8B^#8J8l*B)+`{t9 zIMwJ3oD3|o0Bc)X_Nyq$?x#ts6l5qZoAsniBZQFY7^Hak0SHY&%Ve8xMmc1R!}EI@ zRK3^Iy*>#kqwcwM3Xj3(y4y?qiFH+rx(e>GZC#&5s7~D;r1@(NFwgcNPtf_?UhJz+ zN58OcI{daSc{eK0Hwp6vZh?gjXxb9HSXPpD0~dXp=>+CJ7-91udZipRnI!Ki`}a89?_iSvNWG@YkCjHLsT&>KPWco&PFsA#>6hj^Po_k?9jBELynos zHSET)ze)Q*8WbYFgl3m5W-8Cc+QJCvjP^5YYx@~RX+MJj0jqPV-V4!bEvDNl`?4EY z!pqQe-U?tga@yU2JhoT6$yT$kk^P|3^QzJg7>^?F@41 zM@Zn3#`4$(|H+t=-OBx>V^?cchrSmQvM;RZhcR|3&qjg0l4qFz2mc}eL;oTF!~Y@w zBmW`)qyHg4PJoTL^WXXB@p}BZz@Kj6ZHZHvl8Y|JXQ*!0x#u;?hrwrvJ+Bcy4sz?o zN6U9Y;;&L_Y}eSwL9d3-mHAwxo!QV~J8`S~Uk}6B=ph&sp2u- z63jXi%!a@IodgRdB19$^Glj_eA~HEtJj~m`nRh+x(W{nu6pLGI0Jb!em*}QYwv@RI zzw_9acuBnUCj4|pp%+P3Uw})>YjE~OyZ(N68S2E-SI(O_w?l^4rE; z_8BniJLfgbs@O_&MMYsK<|lzY&H($}(gtEW>*PGxeX!VFIt0T=Qc~Z>-TZpp75vSf zocVAQMv_FIG26CFmrIQTUe-@OmF?-n2QDlna0NCHnqu zFs2G0fGep#&0go+@hzUVr{ZoZ84`ocNHmj281R!g7`w^Th|)%MvMF|f@~bMv3n)SC z+zQ(|r49EgOKP~)fT#Ualm6o$% zbV9d*+w3h{ih2p&^-EpfQ0k)5#WAD}1a*e@072_a`*d4BZ^CZOJrMI^KvwN&Oz{rz zh;W($gF!)K0-detm~1ciz~6{+Bi=D@&~m5xnzgi@GGj-+r-|xgxL@F^Iy3;YZfhMFI2vWSL|ZS zV;XVA#$CRcS8TZD*LcNHDNks^6$7Ju46o?w^5wju54A7UJqW0L_(!&nR~i}A!9G@9 z>sNXu?UOiPYl2M{e*_94BE+K)u=s+9234akL{CQOm~T#iBJR{oAtUwxgUev3jERx` zw8Ubs=aGK4VTq&YP%WElPtR3ISu0+Y`C$0T@JL(2{u*cSbV#)&T>Uizp9k38eN0nZ!oSR+=w^AF zlICR&Z}-~pf{KMR#~pseAZ3(Eh2}LJ-kxkrwBk>cH26#qIzzIPpLvC2P&`i$9Kh~$ z*__TbANGxCKx!}U2gP3bg}p1Rz4B`Y&ZNCNh`shQHx}ajN1KTY+e}z&=0%k;p^PEB zNf*0$0YzWnPeOj?6^^ZEwlz45twwh@{u_V4BBb7DW5Cm@LI(JUN>~k<@HIp76re> zxl$Vd(4GA0?)jyKfF@uJC{9G2+4CrvRYSVFPl;*t|1xrvunZ>eOJTIYK%qS{&axo; z57XU;DtoahT~6gNPVYeO2K2Bws1>Hy#r(8xv*v;W#wF95wmE6iKSw6qIes1%ha+B9;rHD?k*>sq&aA zbWEx|t_sabm3ynu?y2&mDl|1!-l_`qrOMN)(3n(t1|U7GtAvtdCls?dU`}chLz14g zrc+@#Xk_XmIB8Aa!f1gD<=`;w&(QA8arC(aP&O6BLu0Yuq%|5a5H_UzSV%ePFLMSc zZ}n&m+x&Pe30QxW^5Z}=^v^2L^9}KwrW)5ghya5TUe3jFIOkGpQ#yyq9NyeP|A}!r z)8MvxhhB|jehbcH4M)=RnY?>7fCWtwRf3)#N3*RvOVD>#xtYnJY&E{JYr3@*${U-Q=!5qPnWDRNV-t zfV)YkW9rQ+Y%cn45x>$8l&ShdW%5n|vuDUKh0GR|DW0m%q(IfFfdD4i5MT;{Ek$5A ztq}@TYbFplRRowqU@H+ozMmB=Q((6itOOJNJsp0-_{zAQ42Hf&SAG!!2wgr;=xm&V zXV@TPPM__^<5sfuhuQc9Vi+E{y9G>mvyD^UQonL>v~T#b+u`JmfRTUxJr5*WJt4^< zhq79_pRJ2r!!90}llW`L-=_G32h5bSkW@1{2aw~=E1ZTbA;{$=i3d4-w6S=yQ_Yie z4rJIE2p4BT(wQ%^=%+%`R%qVz`Bu*a+}>L{tD(@0d>V@_qGpiBVeKPuvE6 z!u*83+zib0C4VEn#9I*{qc;;@l1yI)Y*k+_1F3P!8z?3W_?Uc&^#+5E-Ap+h3EiQY zd>#;e`8i~{&@V0N!a&tf6eR2wWf z@kq=0EPgQ&^~=dYC@5(MXb0eL%8f{9CBh#Qi77V$w7Ib(K~WdzfxDc#jzBeTk#wDT zMQlQu*NBr(riXl{gyxmSKz+(W=ahw7$XvtFg~ae! z(J|GREq150=nx*qFtlF4?ecPHb^fz~E>(95d;^8!31dFqS zat&S2!0c@pB%2{_C33c>FHxMfc#BF;-W*vxI0IQo=7I*CwesTUTt@ zEMT;%aQBz>tLiWoOyr6O_~i;}O7Z_?O>zBaTlBA(f3gqm=Kz#(71 zQaevW=gaw;^wFGLjMT|RQyW~%=3F?R1)K6Z%02Xa07C3{a@b`f7X?hQAoOh!nm5FR z0Mi(@U@VJxIw>ezNU7qop{E28VVl4rNm8c;d_)S7y@s9?K!mZ^o@&DqBd>T|7es(( zm9?ka(ymsM`ov~}>qQZ@+I5t;oEH4Nmu_1mh(Fmh4h{E4| z0BarC!H`onSm{$hj@VtZS>8nz>g75XG5j>dC8HB@Sa63Cd zK_h;!$2DG`vLw{klGb0mSIv_8nc(5w;?WEmNejD6bR9z_OWT9_$H zz5^xB0PDssCt(&YAlBQAa9kwWY|U&?ApX|cMyx(AE$k&ihl$WgE5zSgA!0pw>{-}H zgt&C2+h3T|n7Ts5dW)GB_7x zioVZh6_%UG(&R4L7(cX*ztJLXk%64KvZ7!fvcEkqJL*`suo#HFbucH63g=KUbeM zvERU)+$`0yFl!WsKaDV{$6ycDRsi%E70Fqes#Dy+@WTQrIn|~Q-xt^dTquiBf0S|M zdF|%S8Q(FX;l{%WSa>eX-YIXFAg_fmK2yQ(5x^GCCnn=}K>9N2b3?03*uuwtx8L=O z@G9a8V@tYp9e!=~$h{2e-QXUTbssC!p?E+|V{`UI9uJ=6GfSMfgV|n^PdayKX!SPl zs4Y6nXXpEM%!gpg@Z6rOu^`PdpszPQYQy!&&?_9z2v4Nq4`wO6$ z3Q7Y5^CDTL8R3?`28!(9$J_q6ludvB+7#pQhJ-9lqr9F@UGZ48KZA3Mrko9mTe=xS zd~%ADHJ-%?7&=+QtD%)}dZg~ibW5wMa;af4xi~E>cL?M>yHP>%&ET2vlz+h^%P@iV z&gG(6wtCr!*C-&-PEdv|_cA zGWX%Rm%t0;{BBpvD72|daj=tFJKSKsxrFtXtif|}y}-j>)I|}&fV)tA-usNXeMMq8 z9AYN+@KXZI=@%USQMeDyd+;0p_Nh7e#}+YLC6x|@x&B-!$#YOJ zHlp2?w?Me)!O1>5ZSPN)XM=!~j2Ggkfab1~U-m=CBT})XA?K^hVz9lfK@IdzGt16{ zcss(Vp*Xe`CuLpK=;UREIjsRtE~hiwinV1{RBJ|#IVbj~j>yXA7%JaFj(os%qQT1a zjsRp66T7YUY-_e}uhwk&3|fXcMYg{M(3t_$RP2Y$3=m9l6aNaIt&w{#X4I6CM+}xF z#Z_)pc|)c&9Wsa?@|=}XuybBDclq#^zwJY~hE=&FKM8>L#qC2rc;ygA%iMLMnCktw&P}g zr~CP7M(9KQ{ODzWq(t_-KL^NZ%m4$+H@>O36SkqNK~aho9_K}^YQfW)lTjwIQI}uk zbZosh?}9zc;h!$~um|q6yAQc4)!Du2RjK8SM>$|)KePa_$+`6W%=UZ^#!z=#;yH%>7;Qn8IRPVtkkU zVS#?9`~YP9Q$4w#X%GcL+h9ADy!7q{e!{|V%`vscmHQZ(`Q(bD8e|HGc@qX*1Uu&6 zJXc6gf@_ee5TF;!@DB$!YQwt+%>f6y%EwIxp#fbm(}0Z!xnp3-hG@ycA+23*;8c7?BR3>TRw#mr};M5)d&O;vdIkc}lp(<3MQa-HR(+M3F z{}qVZzQ!}Kz8To@O^<0=BO; zrCmLYbnp^TwF;a8UTaefzQr&H_DO%@dqcEMM8R~RP*LQGJi90}T(z9|! zpNy$tay`w%nK=Y9yH7knW$Th%zHi=E5GVJ5Spf%Exz;s(0)5?TAP|+@=a@v-BZi2JWSfxq>e?i z;!9p{(j*+f-gM;bhUs@Qow34O@a*=<=pWIlR8ei4_qIItvt5O z+r#pYR^}u8GW&0YMTQG3RM|GK_m*c$U3Ly$!y;+Zk~Vrd^}Nj1omOHv`tFNy@jvCEuZpH?D@9L`54FA?|)I+?!dK(OUZ`) zGjQfCiM1sd51i0+sHc1hGSzNO@5ngy3NyDaOF1~7O}RAVg=v9a(EVotrsyt%|i&{4D}BJ9~X0KpnU}z!-Uia z`yQ>+P|;MjtHbYpi<_t{G=qe1-RuCPWWgWr^5pQ&-nA@+KQ$A*#U``KO~}cbRC@%t0Tcl9q|eo%E}DyDbVei#w}}o{~E21 z`TiXGe!lfR8R+{%>iV8D|Lb9z{cQ7Nh$K5&?a$*|X+`OABGobeP^5EB+`XG6^iN)1 zqRLmk$ExK$06w_WSs+BaaeT@IsNigAa1|6{#(Fc23gZ7u>SH2Bn)9fgAepG*JEhhz z6(v(&dfBb`DJGZQf*-qSae%7jVH>KqaoN`c3S%;IHVzqWKCXQ8Matk5zE67{(bH8e z3hdzcHo`A!gl|NQ&*Ay+>XQhcZmIYYys&adluP#gi3t*C>ymlmBgp*tBgj1Y5oDhF z&tyIWc78mit`CMq>l@>?_-9%98ARuD)^mC1;kaVOm+#;eYZy11p(!#RO(3e4F>t5g zvJbrlf8|yfp8>Wp%vF&eOK3Xfcc93h#b{qLHn794^Wf93qQDuTdRZ|Q%jC|OC_AqX ztHoPJA+=J+-8FjgQ6`GJrJukh{s_aFdmhrk%srF?rx0p5`U18Q_D|YId|TVYw#p~j z!ip!ZhvFgh`nJkMeRRy=eb%A(r{IN|`U$R|g@K=2fW`WMmn*!{hkXO48)hZ@nq}WW zg=F)~`J-o1PgPv!T*38fj5PUvFE2pJE6*XAmTqRsPXqwyoNLVY`TWhpx|tZU&00zI zZ{W%~UPM*a2erKag?{mk=zk}wU%~%c|BHeBe~s!_ z@W0mot3dyIQT+=Q6Hzl^|RA19jky4Vn66`bXnM_{wCC z(|CZ6HIJ0h7ppX)dUy4g7m$N-Svvs+*(e5awvK#o+s~Ee{~#X>*u`i*idlC)X-NJ1 zd~h<3eqi`EL^_tSB+z@KSl@jSY~W!8l3VzPR0N;7V^+a;^Z8vPxY$m1(~TybHJC%C z951PP*lDJn!@8!i+2HIPlVBU=xbsDsXRz)vaI-%yd(tmhnr#(PdPg8D$5`Uc`Kkiy zuAzrAAiXOlAJ2q5=xfcFY2O<3^!l9?E&(>eP#hy>Mya)ob61`*3onAQfC3gRku=WL zl;-CWrfWV@);08uJld24IGI_s)S3^MJnHin8hi(G9KmuzeZE50XOn(1L+?XHr z9b~NsF$oq0*+5>uWgMo5)QkQN{jyhm7%5xWk@OYk05P9ie#tn@F8TKi#V>|b*?Et! z4S3IIed4t>8?i-1uc!S$x;(8DpGwv#_b)g=+E*?A!k}kVV+gWwjPQ`v@Z4`&s{`oa-xkSVd46OF3XP{oEd z1lT|Wtd!%j!e%SNm-9IyBF~}Mj)({%EJ8#e0z0)vu=%|z7sdL*5$wmPf#tYXIxRb% z1qeT99}&(}MC7~OL2+SV2GSq z^7Yh`0)+=-cPmdLcS?Js0s>oNXkSqj9Vl65E3w))i?+bDq3FKaA?SgA@x%9Od?grP zN5J!6N=1FeEP`UxA^Ex2k^(cTKHHon zZD94OT>FoEFv@qeXPi6`f3Lb;fC7oiSQO=RDEL zv{q-F7S9RS;hFG0Va^DDw`f|B{8%wA4LaBPR49;8~8>0@4|P&M%1JE>gv!UIvK#OM1QT$ zI4!I*MvLfVyK{9ksIfCn3+s&0B0AX$+?CQ6YIMeFVVyBrL?^@E)t)laM0Qy~d zUpM@$aXp?g>a$H&r0>vCqCCJL2gOJk>gMt9o-o$t(O|2<=88NNGjtwlNUZDWqUM1W zhiaw4`|6u0*7sNhi%L`8UQRyq;sSqnTea@iSvOeXb?s9ZoW5JF9|aBuRh}PJ_+_df zp0+oRl_`qMM6h)f^cuZ#hkPDa)`&$eSZS-uO$^EDHP@P73@@T{mx_L8S09_QZatgr z79u{w=fGj$k!2kvOB?2gdIP(UstUXfe6?wYys&lH3kry$m&4rycbHWRX`4&f!0ki} zT3CoJZl&_z)-=pxpZoTn;-fwJ?twV7uD#R4_9`GMX|G5Hr4JQyr?8L$v_9GghWK|4 z^D7{s!9H`yO!f#1DIh}FQaQBH%&?FGVi|?PC6Vt}27#pkxVOkwgG^zx7-1GWV-mAs z5(+aEUq^m1<^y8P3ZqEMTzDgFqV4A9h)l?niU=C1-@ne3=lJ>wD(*t`@p~$se)jv_ z30Rp7=<96Tq0K_IZ2<$7gC6V%YoP15Xhrb({Ydm{7i#{`BG0T_;SV-^pdOUV7V_wL zAr&!1WZR67i)X9|=}Xt0w=&wiPmJdsAS(Q>O{@wR3U@U^6lQ(1Xkb=^hEplVtT4lg zn(KvAIVPd7zlY(XkS}SNQZ=t7F-e8lhkN`+WqglROL-9R6yDbQX!hFfUTu~bK0G`Q*%(lAsFD5OlrdR2 z{r|{!RlOg-?^L(6MfxtJ53JWByS$Wb1`_G;gnOZZDG%e zTcQZQTNbvZ@Vwe0zyDXZoEx`A5kvNz;>z>mLW+plU(c7q_;LF3qPQuFSRY@0?6zDI zw?z@#Z^Ss@zvZ`MZ*1t`HtwHgU|_Eo&TR|60W9Ne9a=9s{h?^Zbcl9 zn;#B5^og*;&r|5-z42|s=y%I$tJ3DLgLeEnXrGDEYVFx9X3uax&*~nBLhw;@v03|v zq30nVYtR{Uzo+j5SwC_j>ql}QgTr0;D=%1m6Wud6iE>qWC%G96f;hqRMg*Aeh|}R9F+<`XY~NtR3@#*DU{G3$j3zF z3=?6$ZS83PdrLT{4HFB&W^j%u`V@X~DdnFrr{`o0H*-HFTb!kDVBg$NdzXEScD?`+ z>qC!yn8D!*pnV%Or-WW5yZ9Cq*?%(<)0%drRi1<2#%D{o-@^;ta=?X-3n(SOZH)F* z!cN+3;g{f(47PU)&)~Z7D@tIGEni9TuL1MkV`KbYN?G?@bax4S&ZL;bDLkc@A#$CZ zRp`ozOn(U8Y4l`G?lQ`F?!0VLBGL^U?nsd_KcJgD+{| zb8|W6lk#m1=E;+Puz2|ja=lt|g(Qy1_?_lDr}8QY%jvxeT1s{~eWmY+Fb3B-|CAep z8xV!T0)d_Cy#mje-q55|5i-3Zf8ELOYjGh(NG5E1@l1Xj=U0SeLjJm${5~$E2+4#E zIiATM%#;QO4OoM(as z+d$4T+~YLcq1vwtKWF6@^&Rd{Q9mZb)&d-m;4#^X<|}Q_8Nj3}insc|SH-*hW;wrw1N#d(ydAV`HHdNm zsV)WJKmdH)BA`g;UV079y@p@Do+rhZF@$~Cm0BK5`l|0UH#(J0hz}C!3^1+AAO_4; zBI6FyY2mXaMuuo~9G3L+)I(>5`NBHZMWZu^lA}YzG`=&Ub`_f7Be(P$hO;^7f9c84hTE401Oyhid4u|I1Imn6*+gr8A(%ixC1uPTG zP8Z&2Wj*(X2lEGkuO$uF*RF0i=V7X~m(D zR9EQ+{~$@u0MoEPD0{8S{;;m>MwBJV8DLtK)pvbtEHj(({;*PFR*n}D&Tz>d0*}1Q z!oFq{^0l(WmrwR()=aiIYi&p0Uz#4^u6M+Ef2?SxlUz?FF)YR-h@%r zRw(apX29m_g|9FUUTIA4f;Vwk3JjLjKh7o?{r+E(A2e#hfhd`-Y|$HG9q8Y)!Vj3M z$vt%FK3V6XGbOL++BO;+*EM~a0tOeg&3P#+`072oQ<_&RyN~7@nHN)5 z@L}2cwX*f*&Xg5=SoTm~)*pf9ILm$x?+?C;#3^)O9D^9f7gy$i3D{JJ!NsfEvesD` zkJb@>-PJ3|CxRJp^fku;#5%_ZW+1gN0Z(ouJK=FzKAkVI31QUR8P6b{^0SPFN$g16 z@tyPh?~a1}TC%S(8GFqZL-k`|ZE^5fvENe0^zMmV3cDd*_`4^66}7vdyux0B+6UBR zVUGxoW9vDv33FJ^UwLrLvS(oYysmlK<|GP>QK4yAVwjUk7B->3+`@SLv?M(J#jG)p zhv@v&atj_)JPlDT2s-U<@;BSFa!|_ZN2#3>p2uKZv6dkpd?*;-_(~RLiluxA@Jpz2 z?YT{apN+xKh2UP4th6Ds>kVD9YzSNRcXgtHI(|MdbIMdO*h5cFf=#+4j;~ed0r%5s z&XhcPLf^hd#o+Td^2O_XcUC_(Jmt^uVsIQ$Rn6AOzp$gI`H67s2814?4mHT=CL#(m zgyS2+!BHT>K}2CE;rNnp>>B161|38cb|y!0Vfg!6$b#ezNZv)rd+UMjfqs%VCV5vO zPqe=HUEqsh&a#)QuEtR*%U-F1@=e}fz@{4*KYBVi%8viIduT(gy;$`$ZW_={|Xspz}d+r}o79^W~)(Ubd+P5C7edq6A#=(Rx3$!K+_@Nwv@-m5tHwk19) zr)PjS^nYvJ$EM@(zp=>J|GqDj^HX#-bj!aFGD5SpXJbw?v(J|y1^2*7vkyYzMlJL2 z)m137dsnf{1ZaEdujK;9IG0QWbxdg+FX4~0G)wIkomu$mzda)0o_ zKI(eR!LioTidyl}?RF1mYpc3+OdZZU_6>!)s zWaeEw*)pwJ|1KWR*8BHk%#Sxsj7F*D9(hyNf%saxVT@6}}1@3(-kd3z)Lyx#`0 ze%@K~#PV*A;!N*_1~1N(^MN|_R@w5HC|Br zfR6+D({-7PwD>%QebBF$Ci`U0Qz*YP<<}q@^_~2}Y;f6WqsUiz_E-;|{f6Yh%-Gx{ zw%&_Mtg3*e9oWq^6*~Cc`x16-~W*EEKQ!GUK^v%X>w9J_4t8k_ZI<<`sSX@5wX+=Kj3RegEnJf=_oSeA7=B3gSu~MY#0OJ{lw<{ zcsO%s-*6ZHUc(=b)iSHoI^##A%3@|Cm^fjDKV=Q@2l)LB{-96Jl%Nh5e{J~N6Mqf( zBR^xDG(t}|J=K&lYbE`)q;E?4fuwD@OfF?M%XK52mLun`l72_hyM__}TS=2Ge;JlC z$F~x5QQH}9DYL5M+>Vr4-9f1zbP)e@!R#`e*Y^x3{!ye^GcQlhH}b@s*~PSL1Liwr z19J9s3#NzZNj=1WXY83{o6WmpUl^M*f7y?6Dd%-V8mGn*5?+vbxu&zd8Urp)g*r_=|M9=XL1Tcpems29elMk?DQpH7Z3 zlh6WvXu3cS?(s=Gz(S6JQdLHfVLFqEI>2STTeAEN^~jy8ZZIfUT8N6t=mF(0NMhl#qK1u9|B4O z+F79Igw}&6Y_#)_7TQf9*CA&Q@+7UzLVE~Qu+W|YZEc~w1lq$wGtG6Vv4a2^oNltO z(2f<_SaXm-pAo1J-?d{7UlwR0zGg<~MuE08XA1Oyg}x}z3l=&{pg#cG0$w>=pnqEE z9D!P0rF}`D2^Lx@(Ds0mkULN8Jit8;-Q(8SH+MR6KLbz>&_#%n7IQ8rIe7Cnk-H4E z)qrjn&N~I#!F*e24+DD8OgDE3?OCDCFy9s08-N~%-|rRZe=T&MKq*gY_Y0HKe> z6D{K`^q|nT1oR^6>jzTr*a3=q-_1NCv{^#i3lPh2sL1VQ9v7$#=uNEhJ|&zN2sG3D zQlPH`dK=O7yg)y&&`ScX6=-ksvOxb5Xdm-yfx42^xvzO$pe+F9(C*%n{B{=TK=ZD6 z5F@K;NgQb27w9-Z9f>*Sp8|bOXmiZJ1iC<=gUpAbY&MXDZ#(-MQVWv@N+XBh~8kXRGqrEX;b&tP;+r0L=yTb)h|Hp>GK7O+ZJ0 zcDq3DS?F5=CDTf~L!dT5)UsN%bOT}zcL{AvK#Ku=SD+aJEim^AG+UsP%>5#Fw8))g z9uQg?(2B%K<{^QWS?Cdg&IYs^C%Zo;(3OB5#5Y-gCeZCd`?PspphpF&n6&~uW1&|i zzt;if_Sn!Xh095&p1J#qJmzysL^Z=k7p4Oft&`*W)3Ui)7uL^Xf zxj>)~1-i;yBBdRXWqwziD}>f7(6#0&fu>vNT7eD$)a6`jZV+gZg}x@x7c6v(K$lwR zHi1?FdeB^JzA4Z>fL5F9%v}yb#QYRc1J<$c6WXr;<;=~1Sew5S&fCn7h4vnxotDF&^Ca^dFA$xNm`>qJ^J{^^P1ym3blPH8VfynZ0woKRFp` zDs@S2jG43i>fBhQFElc}QLb-AnlSg~wn6%&@V_eQJA(hGTxXi8XU4E`=@eN41;>&YqT=kQQ6UAe}7fmXdDMatkoqBlYds37m75?HEWJ^O5;}TpyXA zfs|$RBu$t-N02%Psb`KJF$QS`X~IkyNvpOS$(mBjXN{yc4j)Mi7mR$$8*6SJN$=f< zG+}-$=}!ft{Lcv|OEKB}2HGZ@ze<`M#p~gcj+b;RNq3WU4pNr=S7;rjj^9Z--btBb zMvqIS%!1KlaDRUC=#6n*8I9O8OGo$O`g5cEQG-iLL0u@R`nfcg zK4E#snn%Vy1nMJWAA{zJI2F^gmN*+e3p~?mguI@fvwW)!nLfM$)9)jNw}C<1-0&?} zxW|U{(vgy$iqw;sY&ESLjlojLiR0P&zB<0Qxz$`dek#(t$8X>4>wmm!LGxs@^#poj zsCK8VOxqFLd$`5zxBRn^-Ea8{(QxhrQZJeCm*#}Ia>9E^6~ole@zWdaFl^59zKxkq zk@SCCcs*UNcb9aQq;rr~rREAh(<3%!dOXs}=H!jX;927t8)uPzS<=ganQU&x^>`a4PgC26KW&Q?jsNZN-KwTZ(uvF_0S{s>Li^k8to`pUt%9H?&yv;q*G zPng}u3N3R)E)VDkg)Hra2(&1Ga^PHH<(5LuHCG0-Hb6HA&~|_x37{P6_gO2~(!3My z$KJNkgy!u4HEpQ2Ol!`={&5zX)0_h|$wG@jOPk#-v;wrWnQfsb#++)Q zyPJ2%Xn4Mb9&O$m(3KW?8gf~)+CncwE^8i8NIcPKo(`ZK_8q@rIrkWr=PKbwVzqEK znS21{Kr1MeA!p7^4`^+G_6ndJpd&2jN#JZYr&{PU!*YODSm^Vh4Kr6-=*yrDGpj7b z99qnS7Pd_V`+q05kM83X8)RUW}X^$Dppkf8OXH(Y8~(EBs3ucZ5u#mfTsT*O}4ju5i1@u zg{Jv!U}guL73>N-Er2e>n$4;Jx)kdl&j!#nW<&F)K#v;g+{m1>v2V*6W}LYtfNsNF z>X`t#6RSU7ft)H=G~W}5t?FLvWqUG!?lcok&nCXk2hl=L4WP%ccJW34{SVe0_U2N) zw9PZHx^q|n<*>JXkwTdTEqOD|oE4%?Gna*+?aZwK)P}W+J0j4%5$J~z=t+e#Y{lD~ z*DQ2S3)esX6yn^0M&jS2xyxIAAzzbKXjRMeA&70d%E?w-h3-Tdsu1(5LJzjA4M9%| z=X*i!*MK&u$o%N*ikWWa2GE6ON3$Y;E;T!u)dIcVKs$FePg;m}?rL6B&dedL6+mxW z=u@qK#hOZ?Pjbkd)|v-2-9l%#<^atU==BDcZ+CNyrLoW2-7L2>mUa(wsim>c+QZyt zA@*5&nujgKK5I|2#zO3u_A+l+i2c%D=3RkaZ=jcEnkH-{LD@5`m6@hXpw}Dd&%Mng zOS=Si?ro-7=!Vv{*j+N)LbtcR59kOhM_=!2PPMdqK-<@>urzvpmbuc>9)ZqT<}rof z`JCC$JQqM-Vt@0lt&NHE#JOd;y5!afc8louZ-Xv1Gy7S#nL7NI?=39$n4ynHw(;afgVom zEzmSPW#hL|k8PimSYXZ<=#osieLhyR?zYf!K%X)%Tj<>O;}a#*gh!){kSp33B^H_4 z7P>*8g%-L^pw$YQJKIkI=W78pnE15m*os@bBT| z@g3h!oNxXX$hG0kmZoW>QD+6vIE6B&c07@|(Cn;``C`W!Knnxt*~CTW;sE+h;$m}u z0KJp=ig_)7-cMX&nzmyOE6i^@(#}^+pM~D($T^ppnF2j*XxZiF7=g6juP_yXw6s^6 z(?XnAn%Ub^r*d9pjuuEcuQn$IPzCFOD+SUVt}!|QtK79_0~wqt*X>+qrU|5+*PHJM zq?|XHpN2SZG;fDEZ!#UztG0a2OcF?Kx!KHCC{q~T>)dP>DFlB`0(5NvO>tJ4H377X zbBn=%kAG*Ht%vXL+-f!uNG*!~_fFA8)f>fu+; z8ZZ8n*kM%E^)PS#yg*uxtxJ4=R*79yvT`UbfJu^IN&knSWWi z&mzC)Ov_%XWf^GCn|_5v%kyTYLZambv(Q4H&To=IGfiinbewiBtDp=??fp%BOd?&xqeZ`z$X%FNp?yKf33(X!* zXqAP2B(%pZ^b3LBPzd`|J`2vwK3cw~n@)FsZTb|-a18&onQ3YH_M<^NA%Mbw)s5f<90^BzDe zEHt(A`+!y{WcKNN1kjTfn$!8D`?`7CLWg$#-2JWTn588;vGaNN4Ku|;%K-h(9Acp} zJ6~~sZ2? zb93)6=30d^|LE*>-Zc+fTDogn?_KkTgc-yH#5mX&0TwV|7&Jj zs2k9G=2Q#anw#bQ-CSv*$z8L&_sxSAn%;Gg_Yd=$h4ujSPm`IgIpo_9^ZsS}EHtO< zFz*91%R=}pajAaWlwNW zQD~9|S~>})JF*NYLEKT%L0kqE6xS)*)shOtl~8V?!93XO{0nZ~0E(Rj!-UR8+3LzeNGL_8j{4RNZ>oyJ49 zk*5%iha96+qoM9xW0XQP9`cN73ekATH|E)K`4#Rq#wvwqbhI@#C`6;9z}T)(yZrI) zcE(o<(O7A3_)e2$p|R4zC{(B<{}1j$qg){xIUS8D3em{vWW*I3oPVaf$hb}+8b`&( zdWC2lbv9m5h{jPDW4A&yj*c>Zl!#}iZif4GE{ktz{=1@^QJ~O@{1{MIh1MeOXk&;% z4F{}{%!eDv%68F&^wGsBdx){%zw$n0Z}_I#CCdqO&6oermkM%Fae zf}PuI?lPm4k=#X=8Iu&E)$dSamXyQ_cc*)paj{0b-Q~s|8hz;=ZoHt;KiwmY&onYU zBMomz;2+f}+cV0@)2N;2Bx5oonfn-HnMNaxu}0~1N=I>Hjd8{&3Q@_%8yVFyj`qb9 zjABM|XEV{LQgO7SooGCz5T&a$UUj6aGP>807TMO5jB-Y@1t%HTF_I;lWNcQ5w47qR z>`32!03QN?=UKu$y&sowmp#F0EI5f>ft%fn5I!b z&*{d+8kKpb80$3}>p8>NsnIE(GYv6|bjmiHYIIkKPQ|7fzQFpIZL7r1?PAo#zBS33zm3ljoq_lTnOlF8u_g&jSXkZlC^2q+Pd1ij1wjMU3=g7E++Rw8dHFhfWV*4f56GrV^ijyt4#RxIFimh&oF^|zo@j?4b ztu4kXg$@8cZR}OZ)!|a>8Dq;lnL}=eE3IdZ(glRB61g3&x3(Dz|7fFItrv~03vG0- zwcWU9k&Pa;{%R~g*G5lUuNjliv(Zb|o5rBUHhSIKX<)G7-%6aS?6Tf7MlK;FZQ^~S ziV>aZd~CgML>YZz(D}>z#-{U0Qr7lEV=E(){MP!=*d^oO`92UI8s90@)Zw2%IMkzb zzU3W05W9^$h3-JyZlhSCEggQeJ~9R=^k#=&fJQ0wc?Zk;u`x}dgB^lEQH89+@5LTt zsYE>D_82QJqWqdf`@&4`KI1EejxKEL{nU8kVi`B6u*kdL7=MXGV+y-_zc7|7bXs9= z@0Ui_r7~`Q;Xv=-jl~LGT3F`&+8Diz;$%yFYYbr|`~6#E8YA)ysp4B>sgy*!O!a+9ByRpKwU}%oiMze$#su|8=K^og9H8Q8o=!DaI3&}|&$MJ0S1a>7 zhh%HB;Od0VbaQ}0v=YcLM=_!ty0|jUX)2C#$TAN((q)@@eN%P+^!JK zRe9!T4#|9zKKW?Rac#_13Xx=6^HD~!%?ixz4#{?A*)=j9NwzmnSBOg8!HhDJJzZ#C z!HBdh^%k0Il_b@nlUcqpp{2;YO(D`!Y(C0JYUyn5W<*++dpn!HYZIkD$~;dYDoa;$ z6(c(1yw2Ord_tqu-lNT38r|#dZvIOm=*$p3OzS$*Njda0dYD-f@x7&L2{DKkHC_@}$(ubhzo<7FBP9bWuW6j$Y zA}#&R7Z^z`1I!N@Ni74+Pc=#v1I$Ab!53`z4m9)roXBCIIZ+|X;W#tINNPFWj3lAO zj&#SHZ#vQqGWTl9R5956${~4zS+gq9N++6Y8Bq>+631Mx;;7Ba%)A>Dl0(gzjHKi+ zGp^!DvfSL|kQ{Cn+(hZ5BtH1TNRFzJW>g`n-zf7QE!o9YVLmF6FQd~g?@8vXj&vuP z%Wjrsp*yH2n_CnjEu+mt3Q<3dF{@USr0j>W=2Av7_pzpL4aE@}X^b zhtU>=9_#c0a(|DJoDn9O|B`X2!(havttFk?1hvE|W(gx|iNSc2X_ShiexGbMDnu=K zs(FD!@-%a`L-KUtybvbE-Lnk<5LXIa0YR zbIibP+z&jC8q6GxQhYJ9h>^^_(Ih$hUe8>G=w45Tn6DAt>q(&9*#*8onxzRXVxc*R z(Mn%_Q77L*^K?d6iOxk`fTA)^99MKS&{BoUib{RwnkyKs5EF`y^({6JskoU%LwpyQ zLvE+CtrRnhM*1!?Pu8f5?_zU`LQzOwY_8U5r0-JmZjHM5E;FA{==1a;K;jOm^YiqP zzRS%Njk@@*Fbfnq8#=Err)f0Ox7?hqQ5WA;<^qMzEgB7Ukw#U%Kbb2uI>Wcpd|RVg zz8lQ_8a4PW29Ng~PU=FxT=C?WcuJ2K^N~2GFkDGCgzV>Z4S7`LJ?`d;` zMt=WRbEig`{%xlFZd+#u|BGg!M&0~>F^4F0eo-I)b~CEcVE8LAD9a@>gL~V-l5PXMPvORnRtZ+|5l1i ziYEK_nn8`G`9CoW6nZ)De&45NAB{HpJ~u~cwApvSJX4{SMfdx@G~*g=^nGPss?lcO zH|A=EUW3kW%||ra==+DcU8BvugXYHy-3XmOng=!7=sRSl-6uxyRj ze=(2Ks2(qGjn}Br?{>{l=w3*ATnja-$0tp$)~L}RaNVKM3wbmBDXvW#)%(+2FKN{1 zZ|!nql^6ouJIaO?r-Os zq0tTgLf1l#*7-ZRu2yJj*8Tn>*R2|D^mlP>&}gKutLr(9Hv7A|-qL8BzlZBnjb8Sb zxDG1x*P{FVyg?=o0-9OUhdO()*$D;TB zC%dvW+UFnZI!dDh{_(D%8h!7tbe*BmA^#-TJcRNo;f2nJXM*IAiyJ~d01O6*rOEvo5f3<6^Mu+?>Tw4{&?O+D3aqZS9C2+m# zkVYASRj#}ZvMjkB@&Y%x`f1cLaEoiaMqLBzTv3fm0=K&^)~J8rZr56kP6*uR+M-c; zV7+UXMq>gSTn9C(3T$*`J#6QGT40l_RHJZUvum_Qb%8CeSsESdd&V_aqjLh!yDre^ z+`wO4f70lJz$>mhHChpP-SwnKYXWb(Uf1Z}z`L$}8a)#D!1aShrM{0`{zqgvrxlxl zJ+7lQN(p@GI$5KPz~`>0MtOk)uFEy*82HL{pGI8+-@5*)QAyx?*H;?#5B%s#-)QG| zLg0|Ak4EKzpIwz2jR~0UxJFe0kNX;pP78S5k7yJQq`2SKs4kG^KB&>=Kx=pYqjrAV z0$J|kGpoqh*8})N4Rmt9snH{WF75*wmHN85U7KWn z(c*jY{lRRF9trevAEi;LuaA46LUBm;bC1{Pk-z}=OpQu?$Ggu}=sfh%VD}9gr3A{{ zk7$$;D0jc6QAuEg`)?Zc51ixe`#z0c4lHoLq|yGsLia9>z6&gN|4pNx0_VHM6S6E9p*=5f z7ig3cxWqj`ql~~Zca=sZfh*i|H0mF?+PzGp69U(`@6aeOaIJf*MjZoxcJJ1xYv3mL zA&trdtKE50!Z>~KG(QAXem_gfm31m1Fgqf!6ByY957WLcKMKHqmAtx;a!L-z=cItKQ* zr)$(T@QM3ejmiU`xo^;DOyGd~5sj(>e|Nv8(P@FN-G9?49QfWH*kb2i7dYtdqS5Pt zf4YZiv9J%+B4fzs8LEF-!n*~j6i{BvPLC=_MW&#{R5pm%QZS7(Ajg3MtOmwJTGX} zG0@$!SEH_h5|4Ps&b>TP>M77@OrW1glD%#djb`nLmF)kob1Va)-KDoz&KAojb08+^o-YNf1t`UU8C;;lRa^b zehQrKxlp0^QamYVc&^i^RZ7TnmqxiMHJ&FJ$+MCfo~?{76!#Z*N}1u=q0!MPvpgSY z)Hh|e=YU2hq||$U)@W49*`C&0sSc#2G9~V5uhF!Wd7e^@W~VIh4Ap3E$|BErjV?%O z^32fa@|2~Xg&O@+T%X`IdXcbFv@KEjq*ZC(mGwX8Er5jMJ#WcfF@ZqeZ?|o;4a>>Rau3 zNTX|fw|HLAXpL{3$Ft4O;eOwpp0*lo^xfm>t$FIGm()zy?ekjMa9v1 z$OE3ZLR7zpJWUEcR=h6dVb9eX-J7z}bF)T|q&((%M4>l}pH6wwvrVJtQ=am?rqL@Y zPka8R&}Wd`>iJot=Tn~Z1fG{Q`mFesl;=Hd70T`KcFIeh?iziVvfVRSqx~s=^^Dc% zo0Qi)Q#AT1KA*ZJ*~pFE>9+Mn`^XOc!g zrI=P!q4!dTd$V2ZU$p|t$$U@PlhjS7P4)?*qK2eYgl3gsjBJnLhP z_NTP5{;ttaDeWxlMOlZVAlcE%)o6c8kyWhGPbpojV-=d3^-9Xo)<}(>Pw8n@YV>qU zFRNOizZSicQfkfD==qes)&&|popOwIjY54ozmjsSb(==drwp_n)adDy{jDhUp< z-qC1aaESGZMni+ctREOjn;&k8mt_40bv`LL+{#mEMCS>?5mqT9DLK*_pyFtBjI_op zM5Cj^I)jmXy5VGNmWs>mFgbX#wLqil;5h3djiSMc)^!@igH_g(8Z8P=w*I2gM*r#7 zE`_EQPY#}8eXCJ*Fl6BodSz$PV2zcfQ9L-qI!>cS!LzK98g2B~T9Xx;nzb}oZ$&h^ zJlJ40YP2F4w=U4=et)C2QlpLjdDbl&jr1+B9#rVBMN5N!v|iBY^5D7F8yc+$F1Ge+ zbicpJGPlb*(7DD^D@~)3z6-5Fg--4~Ie3vZPowJKW!9@2MT1vZJzkbtPVO8JF1Jq5 zXi;#5b+Seq{nuJk6sm&G>#YqMRR?dhg0Dy|Rh^^3)z&PH;=x<2^E6r%yv$FAqjkYotm8Dg zFSx@Rt)2lD-u=JA?bI>lFGkqYVn(%IH;v?qPI5B0K^80n!Cunj!Nphv{yPRO^eydcWpK>yQMk!?F<^fGpsC908pm_?-%qa$1 zu25d?(Li@7RFqo^v_+xga*qYtDG{Ed9t8B2LZ{>oOa0vPy}@M>XXKug`h``fP$YLk z>H%wjLgxZ~X^mIt!raNJf3s#ObY${mvS#(2KcCfoe2bmioPQu|hj@{{*yJqd%wq z!`iCQzT8`Yb}95t?p>)rSl>y6=cpe{J!l2rlDVhlofJH16)V&`@6psBtw9P^zFg6wZ4&^^mnxp}M>`Qh%~mDRfTWd#OKL8x*=a@8i^8td|){>oL4< zCZXL*@{!_BX@>WpBhK{Vr6c^KbR}t~H%lVee7`i8cPpcnzO9`*`P|;!5{VBw4@+}< zi+9TUeb9Myn#WtlNak*NCuoHCF1^zv!Z!}8(!Aak8l9Hr^S+_b51pr{rFi}CkWM*n z)4YX@%9B++A8~yp-MupPykR#^!0?8caTE#6@-|#N+J60LChOfh`ve?^Db40-tUijS1Cka9*B82C`9k# z$Gr5tWO`13-sneu?@L5q42gLsOC*MNsZWb};|gsKo|6{$uF~k-v_|iv3Z2yD+_ZDN zZzwboXs-7wg+f5{yeITkPGhnwmn)Q$xh?e)?;Q#a&fk`LsrMyD(mpTqzLtbO)2P(C%-iE*%6*%Up31%4 zTdoj2m3z5&yhL~^x4(6T_b!F#Iozwfn>D&xT@6j5?#J%1D8lBhbKJPMxHb8Q{_b!cM;sNgq3T^GW zL_Fv{z)0HlL*5miQw}SAuXo)Se8~H#LbT3$$oqyuA9cN`)kEHc3jM;U;0u{9yBoy~ zQK)aX%Yi0KBxrTR*iBz1RZ)3F~T9-;R)SYNO(?!354sAv9lAg}tmZ{EXJ(n|WolRe4U-_$H z8M}*R_A`AcgK{Bi;%j}$VVC%pWez&zySFBp-k_#92GoV`7#^M@_0Q}`l2K6l)|(x6 ziMM+EevZs>3g=7TvcXrzn9BAErW5BY=KOlSTDIqZm-98}bqLhNw-hN~nftHnN$p9J z?U=UI(6Z!jaKA{My*Sl+<{aw?OTMIK%6a6R|M?QEGuO?+*TWCk;p znx&q(tcUpc?FZK5jFmDathp|gG&p0OVQ22nuv12AJ5sD{lN%iMeSyQ0U(aPb5`7(# zrg)R(-)1V)${d|#pt>a2;G=1U_nSr5sWLgp@8Oy(96m zX`J2!>K3+mwG5BzMWvN% zm_KlsI4;GJHc8fEs`)Dsc8Sp)sMnmFGmzGeFZNPv%s?1@%GBwX<}*k3;}Q;> zaN0o29+VuX%)cW{?PJf{9~V;l{~gp28+sGn28td5b#d?iI>(+doqD8akh%PJe#@Eq zNGq{VxSUS!@mo03>pD}(auWZ@t3Kz9=1kjiyvuo9u5c3TAG@7pUQP{1;y8P!rA*7% z-@=hInlpE2+e&XQ^K$0ck}rKbQ4`;rCTo%NmrT`iUH$tw-hJJN2L`F6C5-u$`(o$4-^d-%@i+j-BdC=`G)F$9J2`+qDWXCkT#R_vh3 zWp2(lxYkmVzW#ssRL%KLNjqO^f4gk5B(g^+{M%%j=VI5rIsf02d!jwX72363EsYzVo|an?P-k+D)T zIj?`8o`hz*-xD0W%uY{5CAY1&Ip4X~vd6o#rqVwUN5(qklgIM^mgeU9{%_ax{~P7` zeYN=CN;MzjG(9vz-4)^`F*Aw1D&eMY5+&od4Uay9DPy zshlm~4F9JM|I-@I7I23DV;lcz4QC5D!~e03-`g6Axh%O2oAaG(FnbRo&kf}6gThjS zGd5Xg;(WuvuXfodA$F?f9D9$D(BD$C&7m`j^>x^E!M9sj+QSZR zhxeE|$DK2ru&89s&G}AybB6z~rrOPx;Ow0Q#}E{jH2I9~-!0S9&Sj1XzFjKfIK#>9 z{C_8v)0Uj!=JsP-Y;(TTmYm__`u_hjmGikEY61M>Z$F|k{M+gOn!5KiTpbOQ#h%!_95rKNe-*c|6jpgZR!d?5BL?^Lx&xl%>VirBYi};tnI$&#+iioWW1x9VslI zSeAFCo%FYiN~()2zab7GU;DWo`2@(n`{^C|+>R`#9Jxn&dS?-jT>12le5&Dm=3Ky3 zhA-l<+}9-PZmMUB61z4-J;`JHqK;y*=qc9YSNz)Hnf~=+3I6T@ugsutiB>S30QygH zD$@{iB23R_I-hA1(@U6M#q@g6C1MR|2EO`zT54Hqzo76YqpEujena=v?!!cHgWdw! zWDLoxZ@tNQGAC+oG6r>yx1J#AeUPU)?Wy9m?pKR#BW7d4L zYf0CvCU88mwiStUH%c>Idb6y2KH|M#mDI7b6W2bQJ6po$3u{DTY z;Ju3VTyL%``8xY+ad*i-KsS{9lua!V$k`#D%o&lhAHQQ7HTR2mN+uxOwPaRK6luTq zT!pssnsJnKzh@!B*XOJ;|537r>4uy;p?OcvCeS7L4dK&LKhL2S$iT0#F7GuA^yXe4 zaBF-GeooH8oK42Py;5_V%#FP=a>+uD&s}5w(5nK}EUn1RH`|s@1}!c<1GH!9bkP2# zvp|QG)`E^IZ2+B6IyZNRacb$~nLCW*iWVa6KT4W%dz+`0Zb3gDS9B$FR^)z!(%u3} zW&23fl-_}GtaLrcZbEnobBcNp|C-V*xi2E^4#fV@>n%{T^sU@(;Cz<*H0Te^Kg9e) zxi2E$w7eb0n$mW74QWkjr@R-j|Dw9dq(~;Jnh}!T>(36 z%1?K_*ZU&y?@Fz2O*T)zvRhDceLmT3hUn-b`lD#o=kfd>MSh=W^2x4tAWVD%<9#qF z#To|1ZZanJc|U)kE70-d{0dG>V>Yu*8G91H`Ana}HfR~9Z!-Oe>6c7@?sHU|38H)P zP-6n8EkiD;_`$`~Qd4|HGkm9l-?z=F=1qNfw@=Jrew_L9m|tj+WU)b#T@8|4W)f$)Nt_iXajr8d z?RN0f#6k1cv@~(Zd^Zi6T_joHBFRD*Nfu){3_Y&$RzA_gRRLP+8VlObRS7zX<%h6* zIm?fNdD5g4FvsPJiGArsprcw3V_FRw%s3ykZ^o^lr)50LoIOm7+%eIV zF^p-s`!8tuYJ|6BoDUkzxRvR%O!t7k+S=veaxxvpv>Mctxz|f+mj;NsvK}|jX)`S6 zadT|jTXXtaM~i2fR^&czx(lXtd)%Cqy%=97N0?M@fo*T$F{O1OMszRJwISwDXMQ#FnXav2ewg_)n9p?WOyYFfSyIPcs9|+vmZih ztY*4}X>pYJtE0rxy7G#dQ=O!r^I57c*VWbPLnsdXjO^;Z$dHs=J%yc!=Eli6WI8}^jah&MlIHg_9bPLlVjl?O(hfIzZ(>T1CY0Wt-KbK;c&ZY2b z4sT&PWFGOSFpYSvU%;sra4t-@FdgzomS?({>DoV%6XZoPu&-YbbNUQV&@t0-K2HPP}v5v^H4bm=uj*WyzzNOdjI-Pe-M zi|fed_g+UF_YFjg|ID#}CT-=bC|q+R(WN&LU3)Xpt*eRdT|?A;E79V$M0c-+wzgv3 z&vflyDO~d^(efP}evRnT*NLuugZXbU z|83^)Wd1uux4uhs?|aPom^pixvzMs*6QaeR5-tCXXw812OFt*N_6wq04>0FTre70v ze?yf1H8EYn^n9jEnO?y3Lb0Irxvkr$7p0F&uS#E>erNio^ykxGNq;l_{q#FB?#tMe z@oC0^jBhf2%s3{qB6D))w9IH`W9E687i37e_h!3t(sOci+UJ~@ zb5hPJIdwS;b8gGol=FPfD>-lG?8^Bir%i6>+>+cOx#My#%)LH$TkfvhFLTYj%)I`2 z!}2QgYVyv?o0E5A-aUDn^IpsQAa8G8*ZdRmC*{}XU!H$!{@wWx=f9BucK#RnU*-Rj z?{CwlO-Y+!ZN{`YrOoMW=CrxB&0TFCZnLe;&NiR5`KHak+N8A2YTKr5VcYI)d$%3X z_QbZs+h!GXEEri}VyEoE4%v&7Z=dkvzX1MA5vf=mF9Sn~`LmEr_Zh0r9->1T?WB7`3vs}W}* z6h){OYZrVkLChC%u|PCpU)qEn>V^14oXf=pVmU&87FUZ~#h=7Fgzgl#Vefi7K2!dH zxKBJR?iY`W2gPIJA^g7d2L3Q;Bo!|jh)bCsNUKEn=QQGEwIW)~w6xV^gpcEJm4n{K z;rkq%U9A>Da$)O)&i7k?49=&m>BV=a{=Ye7erWv#Vt-+dQ~s^=U%>w;owPaA%CgB) z$&yQLpQn=^r?$=+l(sa3>Ln$mHmOhLuFXP^x~XBu0;4`gm1_r4L31e!*m_fajf&Myrpi^M)Uy= zZ(=I*eIf5s@L$eb4*FW&O3fqn85Cj-({)V8 zWfAADJU9*XJJAO?you=z4*3`I4j}gByl+5X%R30VGw)~6B{}Xi>iq!dp1jte|H#V$ zwekx(fA935#4%F!Xm@@rkPTVV`#X$$&k>yDtGbfFO;`_wp!!cwxsQGF5H z`KW=QvW~Jx2BlKHWQ|Vj_9w)i%5*l<3%Xt3%7h1Xu_q;engWlC_xPEn!K<1`PP7$b z4EWR(gww$@LHsO=of?o`Z z_d9XkXNuvF#Tg;u4KW53ci|vq!aH{cogj_^ohZ72R>GT`@YFp)C&90q;uLsxyqPWf zBJCOQ@TQo;^h|hpQ%r@AH^eli)5Y=NgqT(f?CRm+2ZIw9Cn7up)P%n;LwFXbiQV)t zgwFys#cY((z+5mK;aV{g;W|(}!GV3Yf!Uz~;j_ib2seP5m?Or3o`ZUrm^CJVzkumN z)W8&fWV#47FvYpz51{8^Uv7xSpeE*)(-B?*YKrqwC;F+oGZ0>m+L-tazYyrPn5PVJ z9jJ*pCk%QU%8qw=QEGhC0_8Qurzoi@zCsyI@f}KMiq=L9G}mYZ%`@hL78vtE+ZlfZ z?P@Fn?Pi<@dbH65+TA!Gw1;s4Xo+zVXfNXu&{E?v(B8)7p#6+1LHiq5fetYK1Uk^T z2J|@NTF~Q->p=$@e+C_F+z5JtaWiP8u?Do-xD~X!V+zC3)MOxGHJL3o|uY*2syoppVfSTeZ<89CnjCVly81I4Z zHQoo^XM70ysqqo$XT~1T{l-4f&y7z(zcBWL9x%QD{nGdn^l!%BL9@-Tp*aT>ZDoE7 zI@tUk^aS$<@K0n~X8s7y5T--Te}O*?)D-3BPY4eOHN^hgTSyKe?8?*3f_%&Hm1U*whQ#~Qjww`Lx0#6vUoo6O! zd;A`(DGEKaK|A8tU`^48KZ1_; zECQW?-+4tZ;1^xd3;4Cxo}$Vq#u&=*6dOG<*JMVs;#mu`mS$a)wKD6btj$?(Wqp~o zB|u$ryvPRpK~TV-`8PU4>-wqo9D&U^VVyjMGtTsHi3 z2|VRMtaXQD#XACjBk?y1f8*hqCgATZ_>0;2i{h^i{-Pd#_hIFFKmH!Z>h=+F1*ro4 zoby?(u5YR9H|jdjkny*w>pFG4Q(a$I*EiMmOLhIbx~7;ieX6?7RM%Q{y-HoLQP=C$ z^+t7Fqpt6(tKpLRJnHIK*Hm>)SJxZW^=5UwRbB5@*FEaGPhIz`tJf{{`_(l?UA-Q~ zS67#%%Au}ab#14v9n`g>y7p4n-s;*{UDv4Vt?If?UGG)b`_=UUb$v=*pH|mr)pduu zzOJrss%x%KmNQ>n+p6n8bv<5P2dnGJekng+T^Ffqle%7@u9v9m-2o|oKdwIazRUpr zEc_iX_GSJJf0nf`a{#UdxDN8|%j}L-Ko9) s;idf~4WfA}|OOnpsbG<<@nYpjdJ zOJ+2LYQuBu8)lc(M5AI@C?1|!-!Q){9&d*dBlUF&=9q9S7Md9z6N*>Q62s@s30KF%HN)pshnvYEDjKPdII^giSy$f> zPH3vAtBy9-gprmm3I6zKC_baUp*F!8))y#fr4rgs2}K*jjs}_-s;jAY zl(RBaJ0}{hnm;Ej5H-`GaAJ5)IOJ%Hi6}*+AzV{dQxkDCZe=*$qORagsyHlnPNHNa zG-pI)UUD;4Hb&x(LR5uA4dwN79r;y-V~#>q5F8eYg{juU28m2;PGx;#Lv@ngSiD8v zB&?WRxMVdd<}f9i6;3i;>X-UPM7=L zN6!fltFMd28$uWx%|}g1A}S^lVKJ#L7LJdbeijCT(3uRM7m3AV4yo}C;Te&64u%$W z@P>wBk!lAX+Zc^HU{yn-vwR~$(U=pD4UKgO55;I`nD1be)zvuAh)^VoAvK=7fEd@{ zh#6KNjiN3X^oM0u#KX0*;b%97oFyAxJ13634wDd`2jh(s9abHfakRFxsS=+W@L&E#!XOX0HWIJ$|=y*wNZ z&qQVp!yVcfiK3CjICxU>o0aiU^=wCca}0;xfZSmhFjJ?ZM1&*th)^|jQZw7*$<9Z} zp`hW|`nV1!x?Z!&qEQ{Ltgj7gFt)xf0sat)&(blK;phxGoFjEJHJ9cL4fN>K9C(TP zxiJmp@X-*1M~BBX=pbs>+lnz_fh-iH%j>h5PKen+p+z_db3FcPR#W7~<>qL2dSWJR2ue_zyjve-1(3dHRp}3CypbXy}~$*Bd_PBheMX zz!fyaV>HH`s_SZ+vnGaThMjYq98-=ol7SwYm0ZlK`Y4=GU3D1i+OW__&{E2geE2+g zm1evOj2}ulZbq|+GWe>Qb<}ht8tR>0n~12YcPIxNOG;S2Ud#%)Vs+rU>UvtV#vB#%gF)_SQ7$qsvSreeigBs}$~P%?qHWO@+A$@XNH&Hb2SVGW zvG6mZgnYD^8IDh7$fPE*4dR$`2X=&L7@naP=a@^?9<`!wM!gsrj`Mh}p{-jiu@9}TZ^Qz>HiCn#&^%E?ff@=; z49yjo>Uru?Q@so~gdICm)j&>;+G@$2D>sRA3{bO_HOxe@>*BI%(owJ?@(tRaq;IW} z4a_G4s@W3BRZ^YIP9m>LJfw4LV3*W#K(VpK?Ytu~TTR57tL+82Mk?b9cAr!wb);f< zmxA+II0@*oQYx8|G#k##5v*~9RZSe3Xq~nS-f_!O%0aFZY6QSVxS58^?@_ z7LEzDTdXpSEfCzF>;+22QDn~=*fJcG;Ih*$fiK6_8ncingQht3x|{~kg0!0!lg3sK zuM+Tw*ocUlNNf%k$6Q!sUk$^=r8kj2V!GOnREFdB&V=e$?np!Ba$w~RaGx1JsLSOgfkkL5UPNsF?_>RRa_o^^>d~Ujl}sRsjfyO(6|Ny zqw8m4ii%=g!{&_50$*vt!~sZ^&7f6tvx7M2kwQt!69|lU*^16elX6xJrC~LjP`8Nb z*p)e!Ga;P*jlkfq(NZEBo)H%fk(smNVuo}3Pdh0wnj$B1WJQdZhN7mPn^aWuPFBq` z(jw`UNKA@R&$payOGbw4Xh)Hlb(8iY02M8E1}!)wrH>kf+_O9Kw#&rEq`axLtQt(u z;W{=-HlPF?I$w}ksK~O0hR}Q-;Za&8k?b&bmQ@Y&Cx&b5VZ9PdEqoRru&)P~HuhoY zk~~=yI!O@G__&ir_-v4w6oNg;4GLWCIrXzK1(e0+*HtU`!r@^!jF?Uv@1fzDkvb(d zysk!t>gUAJ{Pq?xCZbpfjc<(2QbV>PCQXEGvhJxYs8T8vE$*EC|K zoV4LjQh~u+JsT|_WcL8+ju#driHn^+WO8~)gOhS+oQl{Q)`9tNf+w)xB% z9j=?H28TUilcI_`7*1k^rZ;#f66b?`3kT>Vj01cICgVb5`6>^bIM{L%#q4I=C%Ny2 zN1)wkSxh+2Uz}leyaKth_-HH{u&!2TF*@KB8B-4l8kgf{p!3n5yhU*YdCX$P9ZBp_ zXj7mdvcV8hhhJ1SKI(!lY6f+@}41!Mu-`>LPqK5o{(v=0^Bm$Dym zf{Ei)IxrN6>AU9rW;a85eK>}ERjsj@VaSzbN2wU7r4vfmMlR7F9qbuxKoL_heyhVZ zVRW5zn@$FG1o=!m0ZmR$Oz}yBj|7q!wgyO28sB~7g|DGC=& zf$?G76v2{)!sVg)k~s>iH5nQcsl%-}8Lm`~L83{mLyW3O^=!Jqz>`b^&H;GQB%6Uu zF=n%5LpdX4lQ`nhAkKK~f^`*?-UP=f*dmfzEQX~=CC(0X0g~<^j10%Q0p($f&PKIh zQtNS(+0DgGC7a1^BD;B#nnpH@JQk4mA4C~$2}Wz-Xn8fkS|^5aKO@{Qry(3Ki^0e+ zGsBhO@(Jol7`p|nL3lZYrTYna58J1;bEbfhk0SOEi4+=!)@`6_vE? zrA}?O=p7!b4)Kv&yrDiiY*q-y3qf8gRbZBY^_9h>-8JVY_dA5c^8^hZB~3xQX0Ri< z78fHTbv0umv06Ia7+)WY@WQ(yrp}b9e4-+DxWj5$>;aqTR z6vpHmt|QG@UYk}<~ZqerZhVL5f=!PL-mE|Ozn=%f)NhEJSYS#jEM$KH*-B$t;&6PDAKpAS5^ljH$;5Fei6jukIfq~j4S*%Bq-u!hBL{38z7m zz9J^)@nNC5`a0T!!9T$^>>CRdRI8T+(_X(g^~fyP;Ak@;N7M|Q8;f|oV*yT^y$amp zrw1GCjn70Ju;3f{3LDbR_d#IMTI&|DVrV%&lF)!55O_&xRy3(Tz_TV5v zeXmDzCx+$85YKreB8JThSI?FiVU(+J%+az*shsxqk`qX_YJkHwB{nqbE(kR&o1wHi zEFay$lNaQIkL&}6Ex6p=nYrrpT+Pz*Q4uu~>o z`ru#S{%f2bvcdB&YH7(w+ORcV%EB|zjd{8c#p_$RvqXp%ykKCROL4SxrhP6+$Q>2= zK7DUSMkF&5TLf~rQlbUVx#7SpXzxChKSgE*_v?;(^j+3e|-D{ElPHyp&W*}|-xbZ^A?}-72XOFOl zN1MgM;Tk>zq5JA|e`Z#kcS#LMAaB3Obs+Xkz?G0zdpY|kS4QxCnvpozrEt+?GcLd$p{SyI+p>{?!F}cu(GP*Bgajw7+xtRhVi6O9TwSPc_NFe-VZpo4^y!#Mh++dUMRs+eLbow16k4e}V4hhk#`Mw#9s5sMB;d6-f_dw(%3S(2ra zB`EO-j14~U(E;LOr-vI)b_h3~B!egbS^{o`?*od;*%6$P;D|)tvE#9ghhW6;h6Xy< zp*=blt~EGX$GyNBj>e^Y_=vJeqpPNlt{6Lf>geHPM^=pz<7dp%cTpHfXRDrVQ0u`F zwd9TLwH~3wQjZWEpj_4wV1uUsI|4Z=3yl-AHuD_OG+#0g$Nyn^T8aU?RUXTv!ak|O z!GH6`sa!Jfx>70SFl*(ITKIBUu9hWREwOa2l53ZNk-gqatbAoFCGfBi7U~SC`w}CG zP!*1a!|+t+)K~L?Y;tUwI`&WILK;f|^{7VDtz6OwQ=t3KI7~c}=9XHItkKp6?~8Mo z=zNR?vQ7PD3E%Qn5q$GjKaOdq;73I&vD;3h88*6-7L3tI$oX)lodCu(BQmoQNA{>& zB9R?U-h);hh{TOuEIke@b;O9OhEPqoHq8u9}e3A!!BVE$EpE979F$Qj6RaVJo0+?(-1Rhf4d0a4i*u~mYiek(*|!gF)j3Z~?0bB4kEAc(vyu1xc-ZQy zu=5*l%W|2qQ04g>Z6wNvvU7p{-p2~H#v&m(f7z9$^@QRKoezgv$&@@w<(yERy)c!} z9^jD_>L$2telVA(EgE4oTCiAy%a;-8)4Fr;RE4OJ>s}bkIT3p34E_br$8t$I9X$bn z#{lpWQC%G0m#RdM;HIZ)TBAVQ93)AX^YDbH2JRvHE)?=}Xf`;a(J5jjB zGrE2*GMg(OS;BD?o!?`C;1U0lYQEEt2Ww+-$0NMDfUtySQ865o(d`(X$x$zOB|(ok zu&YyBa}iG5v9<5s(h>mL)Xs{~7~ESJics>*wNBVIbwaFX7Hl}QojFF$nkoIohW0Q9}%Frb8306GyJgdG2`wMkj z0w?@9HAWv{>atHM$A`nS@qh*z1CK~2jBrkf_B(Z0AJa`iQ5g-RKT!m7e!O_Gr+d1M zT7!pYW(jQn?ISZRYG#wPnmZ|G9^JF%W1TT{{#-U4gH`U7?2Q7fC5*~z7lOLM7mW_h zPkLln;*+5g2M*zA&A1seVmQ>$uA>$Q`JtI%+#fp!CQ_@;Bls|K4!MSEJ%`uYGd7$6 zt$<+JXg4ahI&Mi=G`1168J7z^GG1)Y`38+LL6nBQ9;zsNL{(fKfs$s#sB<_KH3s+X zajS~ra8xGfTnY|@E*LU&!SJrCR}(hwZ^}Ugj+(2h>XmF&y-Xt+(7_B`E3jLb5y8s> z^J$Pd?}Pwi<%}m6`4I-b>8Wmi*sFc=IO>^y`}7hwF2=Au*_J7hV)A38cC9~p%Ic5a&! z&H~Gp%Emc!>KmM|ZJ^OH+^}U*x?mo|KjD~PK4yUR7+%I+>^nl+ue$yi+2Axnn z)xIA;3^yiY_`CoHYW1ve?1br4r_7__~e&o9X=$dkbMG7Vfz$V z@*R^RG305mt|Io)3EdI8i3ryMXNZwY`xU!dv~<9|?z%V~J>W&wnh4zSPp-%TZU^uwIZ_9wa zDWy)wgA(e{O^yO-ez;pBjhBW3G8R0A)XIB+WQKIRoQILRFG#yk7E+ndfv4mZOfx4+ zQ$QS+RU+@wk;kLE(wO47?Z_f4VmyzqcMGv!tHH~{HF0_uDYFb;gurtJczbR--uaE= zO#I#8^>>@H3pCeNggh zl%@`~pjM$;QTav3LCC)joG@bQQI2yEs=>SAf5cl|i}39YkuoR|&a}f6-&@AFZO)^( zJ~GZn$VS6IiV9z$#6{*dL!tmIgkr;k5QWxayvJ2OVL}GEiGw0+N&P=BWNky zgvI9_LXMopQFe(6*>2)^YyGe#@842$qNH~$_g>^ zq$KrR1?-WmfyM>d-*j$s(P|Jd^#HXQtgR!JpL&nR62(v(P`x8+)QNOy$9PH$JhEre zoj8<=Mi`ArvhzZO>1xZ7>`b(sY^8{@4mpZN+rx1Skru6(9z*`qkq>TC1J8hOadHYJ zuNAe9v<4bKqMJRgliP-Rj_O7&8pfAv&~L{lBaF=`A1W8NkDydW)oSU3P_Cr@Wqx=xhug%?t(rYaHQsWUy(Y&i*_@q1juhFNWGz%H@+{&gveGD*o^l+6G&KI@ z9Bu1?XBbGDXCQ^_6*&hL!U7K`FD+SW6&=WTwoIvg=7itl2Mh6jKdmODpQ8Ss55HK4 zeBfs~mmx$wWqU&^PjhK8(mAKt^_ju-A*-SK(zqorPxEt29TDV!mO1YaNJITegmtjr$g+OFSa>a5Sko-@^P_NTCk?CZt=zO^LAzMkz@2GvOl6BfSQmk#?vJI(^ z$Rm>1qS;%vbO}Pvlq5@iGz0(1R%_{_Wj~Y%vG@|Iid+Ut$5V*H%O$F;xU(2`mQ)B@ zzEZX1g1}bzdx}EKG8CmzR)RXU7Mh*;{-q?RB9vnP6~Q_TLaQ-xdD zNlQJ4E1NSfE}`die4a>nrr^U%L`#{5m`-Pk#SHj$OtH8_7|s>+988l_PzoyZabhw) z5{&wKOJF;&p883!m^tWQavO32Nw@_$h2Yp31A?|Y(xH$;A}2>KWCl{#BON(;Y4>x0 zDNNQveKivnPs>E&V6c`=LTEPr>M;h$SsdNF(C0onQ1+^M&;}Ux8rLaArA3k;v zHgs4{^-LZy(jM&zm7G=x_GWARb!l?3VYI83#*`;*v{29{jV!1WN~xpHA(dob;$ zvlA|y`dm407c9lY_R^L%(X!3SUU0yyrX4KD%c^)0(0rUZ+t9W#yOz?z?B$rqPH30g zBkBdw^Ke|dg?~>el3SWQ9ND40Wfkq3mpG}Gu0cW+(ZZq@-kkd9NRy(hBW=0(NFcN2 zW=QyHn@%=K+YlK_Y?cHz+%y&u+loStn9P=&3(;*5#%c1FgM1Iwl}4WJgJE~ajBh4q z$0g<^yMG)TRg^{^gow^9b4qBCwuW3flNX>xJB@2vP!{4Np|&rUQr%E9ye7mgKvo0) zaFl&?L(3@||6~F3U?zf(yJ`DIZJm-wl0!K<;*1|X@GH8C2BDou=2x`j+BQmlFR`o> z$CqIQ9R8T1x&I+cp}w#eN1~gp)3)V=-e!_T(o@(zRxZt&ZHBug%TP|_6%(GBj=gB) ziq6TBXBmK9Q>X0neVw}zVEu%fz15*oBq4lV2<+zgHr;otW3hHocBRaGa`D8zG zjL{O+u?0Cwjta8!Me1MJn!#1_&9ReMc=VJK4}HgvLrNerJqZb z0;Q^@8K?QoM`OX>khPq_TF!=2vz(3Pd`Slzi9XkJC2}LXlgEK_6HI+WX~<5aoJJm< z{ra3to`iZ#wz1699>J6^d$SYE5T88X9$u^T#5AJl7*=kOaNv?^dt*ML!JH(II_(t# zb90+>X%t}%)Pej6Z6s(bV*3kPsZjsd;t2Ne@zf?_Y8j^`pF@Yg!?{%Cx2e`K*bwy% z-ZJFc$wLs?v$8FnD|#tpe@G?ZMoE{ z_IP__x7@OlwH)r4!S-Y#vt=4lX0JqA9@x^s3LR3DO;P@Go7;RIqvP~p>KJ?^j{GO` z0c52R{r{_@dfVI38jV(A#*h%ozh(!y{%CK8bi7($s>|2rYr_(|^X5 zc~f6p(qY-?8^@e^R{42LP8Yt73#Ocs-*5LNrj_O{G>kMHKpOZ4>3ME} ze{O?_Nd(_q7A`BJn+Nh4-Q0zONqQb(NOvXNRix)Zrl+USG}6+T`k1CtE(MgRCrS1s z=(7rqjNTc?xU6;sBvepf6}mtH45M8E%1~umsl-c7g{;f)`B<5cK_C#2Q7jP*2B92@ z3h`4ag~CK809^sP3e&U-Ov|Lq2U5NinK95pjv3w3+*UiPk^n_<3<5|hYneV65gCg& zxUGz)K@_VmTcF28aSb!0X@IvBI$O6F;H4F$2oovf|2|>J0I6vjP1S8$;qw+E(F#-r zrDz%r-HSJ{?#1iTavmQS3p{R-G(SPs=eE)p@AU}e*cR24Lq7r1 z&vo;qah+g2856i3O|NG3MsN7g2|kZNbz6G{G_{7N*3_D0v9S7 zqPtn8_yF}1x9p7#*%=|OI5chN4wc>d28VZYwyQXNkmwTblqFfDxM?*RVaAdmUz)ng zOAmP|m6v|p!%IflxsKvOjJDxuhU0BGo?(>@s|e!ruf6%|&gf0qEj}bQFHhsli{+)O zy!4QlQoc0pl$TxdvYYHVV~NNJXN0NYmbkh3wljT|=^IRU5^Y+=;e$j`X`)nVl&3re zYV1))UAC4RX*m~ix!v*0ogEKgkAtS=8FCynfyv{5GDBh>YCa!44RtAe4cMz$=W1K$ zYNt*Bt#h@l6HL~L*HtuF|>g=hwaeU>l_aOL{1 z_6kI-&1k2t6>`+9l{sj@gPn&EVyHkEHWfTg#pPBub+1cHxcbkHtyD+9-u^Jn%NlJ{8Vk;%2Y1*WzN#TVmO5DaYAGOmoM55B} zN=2&FAOh_Jh)O90flwZTno4O2B|;T_iPRuPZIGx00s&9J1E3(4kKg~ytk)(kO%YGk ztnK@G?z!ild+xdCUeB5Js?{*>xIu*=tP=2EQ^&1_Ua{g8OJ0#gS-LW6B1h<8VsWU^ zsCOr|;-V<zxA10YnY zTJ5DO6{SMTYIC(Y^+&Q?P7`66CQ79=5d0FHi|r( z$%~qZoeLA86e!#XIb*VBl-8P%tg$*0J>GQ|$(k~nT5T!aAZhkE18a9oB@9~U+Ioky z%?)XX8)C=kuG6?}bZ$er*ijg$j3%UQYU@MEKJ!Ga{bWHa>@#fk0e>#sWNHYR@RCzt zC$1s@Me;;Uo*Oa6XwUX3=EmYEWRg_?K#4jwNHR=fnu;paCxt+S1Fq+?cLGu#aC2!g zst&kFiWLLo)7T>x8D6AbJ;U7HL$j)ruMZK|yL$jBJGq5i=y<&}eUcnbV4$U!0Zp1z z@APL#N)VN#1D2Jgk~UTwSR0aBl|!^ZXqgoCE?y{AghXP|-AL(f7~M7$aZp34T2ZwE z)OEG?QS$JE@-$NdNs<(vC~d@|QFr^uY8FVa(ulOQ>ci?y&`MeLaDyQvR20SPMpR%( zF5hmK$DA@Gva3Mi$-JU84AW8)Dh)%GmP% zu;xvESQr*doRR@*{5i; zr3kZ&$jmP5dXr^kc3F0dWo33*cAI5oc3E~>Su?v7V|E!eY@=Yr&QgS(r3gDqAlO-o zu(K3lXQ8B0I}2sc_!M5S@S=s66f!=QUslNY6t1vx_GfS-gzPA6fl@GpED`cIY1?_m zHlh>t_BRajM12kQ%_{3A*JO{d7=03G5Bh$QrrlEw-y()+al{g%)b>`zT5^i3wxON6 z?SH#?7<{|C02u*i6r8o;jM!vy$YRK6EIez&H+!Cvm6QX?4tdVPS8TUDXW=Uv)VX|K zhhoq;`Jw{8*oRcD`-uxG=V_1@b^0d1{l2M|L#Hl3uWc^>WX)asj#egqe|GZC@~^)z{?fCL-F`Ixk7tg( zI5I!`X6dIt`~0gr*8S$|C%^ZBYhQkD{p;VZKD7UhH($N^^2WD*x5xQW?#|rKZ(jd{ z?bkeT=*f+*-Maa2FMX+1^)7tvyRY5*^1khV`0~g8>V5jIts9$9ly?n%tMr|Zf8vHW zT08!jd;QhtpStbmLmxhw4CEI#^W_~7=Q-0}6+h1dhkHK9?zC6BbN?QmUgim97dCht zfIRHJ9ADchT6m$mlaB@3Mr`Wy3lxZbISJ{K-Q1KX493wG@)`RUQG#1w@===px38U$6vl_02i&;m8f(6VH5u97J(*d*}pFfxI)-x=)fJ6%d! z!S_6_aeTLdz_CZ=ioRE$Xy)FQm?h0!<|XjJ(d7Dvus-aSeLrXfNu zVoO9EYnWx!D+d|wOq{$TE8|p?io%K;M#`uRYKWuO( zLrI|40yluE$XZQB9<)+zHOy8}@N*mrt?vQR|H03H7}Wd$3dcyqzR zixyr|$VRC0%L>^D6|S)Ib@Fodz!~je9=vTOVABlL0Te znAxpo?)g{jAdl29g;+Oz`${Sd!8Qx06?T$w<&|!~WhGy=+8Zr2Lb^ssHz6b$#4io< zR|ex$5TEWK&BZeWM%S%eY_^XfG0plBiOLZq1|t+fW|5H7>H=6%=Qv-WrhYd))5JPBZ3e_5*xMMeG#z$u=YDnRBrh;7LQO5e40-z#r1{7#eKbhcAHVvskkBoy*8(0SwX0vq#zKhJS|`uN%^YhaRyhBu3tFC_<7c#9n@Ve zJ+OT3>VqSv4p0~nLR*^yd$l$f`i0tDRnVf!D?^Of;`;>s;;`fw!hW^{6zl|wuwNVi z#om$P3NXUlpf(5EpsXNNKqJOT$K|lZ5{Iwnb)DDY2vr{*fJwvJv-UCZ^*bXit-DnvN25kvcr0u>Guco05Ta%nJ1^k{5=xP6q=vXcjPB5u6ak z*DN%_{5Ze-!$GKuIUCtU$^(NH6Ie)^ zZ_XwreJA)2gw`6TlV+6>7ph4Lp4r;Xv$9#(Qh^f|j@ZuCJ;jRTxcr$tTojA_R1 zSygiYU}MMHC$Z9XZZNfeFy18>x)=}sm{H+`75B%-Kc^e6^Zo>IH1Q#md)7`|HTUyu zSL{01r z@rKcO`tX5O@zma#FV4)yQ={>Y1M^JA!2^#ihi^>%j>p^f@VrCGoF2tWq z@d#!Ab|ERegUAJ|+?h7=z`mSj?&NWP^R%b#Mn|pW;35YRzQM*GuutDpU?@)I2LW-R zss8}`m6-mbN6L8IzW1{lw;gzZ!)!=--_3JBkG3y7{!jhlX946yzzq@Ks_xOI*N2>) z^i~bI;4E@r0xsrnol{)|y93yHp!@WX^Qin9{#sC@Q1OJ`0>o#Nvx2tbhFl8fiRG@+ zr%sL;y>}VO1txK5=)cQoH_%+KIZwH#!LtP%a>(Kv-f@R`gmH@Ehj4tsX=0hO7?-{c z&M>1GH?EEIuz!-8plk!}G-rC3gIqkefirP=8fC=cyTZ4c_M21c<&1MboQN5x-plkb z_~!}btf2P@$R(9mXwk1|5Zp9S2dsXIQaORh%{RuSM72AplXFnwqO5lTT`hfM3*#LJ z&o=s%bZU;(v$!qpCD_!nDB5mi;;6=vJP@LpOWxJQ6&+9?Suz)iWXttj&Nmtu<1%pSx)z$C|!0E~eRWCQa^_!v3f9|2Nsc!`k;;s^pHFyv^d>;4nsJLB@fM0~rT0 z4rCn2IFNB5<3PrN_bdlIr^48d>tLIGG7e-M$T*O3Amc#Bfs6wg2Qm(19LPA3aUkPB K#)0=F2mTF_u(`ni diff --git a/Mono.Cecil/dbg/Program.cs b/Mono.Cecil/dbg/Program.cs deleted file mode 100644 index 260b7445f..000000000 --- a/Mono.Cecil/dbg/Program.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using System.IO; -using System.Diagnostics; -using System.Linq; - -using Mono.Cecil.Mdb; - -namespace Mono.Cecil.Debug { - - interface IFoo { } - interface IBar : IFoo { } - - abstract class Bar : IBar { } - - delegate void Action (); - - class Program { - - static int Answer () - { - return 42; - } - - static void Main (string [] args) - { - Time (() => { - var module = GetCurrentModule (); - - module.Write ("dbg.rt.exe"); - }); - } - - static void Time (Action action) - { - var watch = new Stopwatch (); - watch.Start (); - action (); - watch.Stop (); - - Console.WriteLine ("Elapsed: {0}", watch.Elapsed); - } - - //static TypeDefinition GetCurrentType () - //{ - // return GetCurrentModule ().Types [typeof (Program).FullName]; - //} - - static ModuleDefinition GetModule (string module) - { - return ModuleDefinition.ReadModule (module, new ReaderParameters { - ReadingMode = ReadingMode.Deferred, - }); - } - - static ModuleDefinition GetCurrentModule () - { - return GetModule (typeof (object).Module.FullyQualifiedName); - } - } -} diff --git a/Mono.Cecil/dbg/Properties/AssemblyInfo.cs b/Mono.Cecil/dbg/Properties/AssemblyInfo.cs deleted file mode 100644 index 5789c5e55..000000000 --- a/Mono.Cecil/dbg/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -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 ("dbg")] -[assembly: AssemblyDescription ("")] -[assembly: AssemblyConfiguration ("")] -[assembly: AssemblyCompany ("")] -[assembly: AssemblyProduct ("dbg")] -[assembly: AssemblyCopyright ("Copyright © 2008")] -[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 ("6f6c7314-315c-47b7-928e-e9ad1330ff1a")] - -// 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")] diff --git a/Mono.Cecil/dbg/dbg.csproj b/Mono.Cecil/dbg/dbg.csproj deleted file mode 100644 index 5b79ac114..000000000 --- a/Mono.Cecil/dbg/dbg.csproj +++ /dev/null @@ -1,85 +0,0 @@ - - - - net_4_0_Debug - AnyCPU - 9.0.30729 - 2.0 - {89A775F3-64AB-485E-B958-60C25254B732} - Exe - Properties - dbg - dbg - 512 - - - true - full - false - bin\net_3_5_Debug\ - DEBUG;TRACE;NET_3_5 - prompt - 4 - v3.5 - - - pdbonly - true - bin\net_3_5_Release\ - TRACE;NET_3_5 - prompt - 4 - v3.5 - - - true - full - false - bin\net_4_0_Debug\ - DEBUG;TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - pdbonly - true - bin\net_4_0_Release\ - TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - - - 3.5 - - - - - - - - - {D68133BD-1E63-496E-9EDE-4FBDBF77B486} - Mono.Cecil - - - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC} - Mono.Cecil.Rocks - - - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD} - Mono.Cecil.Mdb - - - - - \ No newline at end of file diff --git a/Mono.Cecil/mono.snk b/Mono.Cecil/mono.snk deleted file mode 100644 index 380116c18fc37e37caee38d5c7f00553381fbf9e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 596 zcmV-a0;~N80ssI2Bme+XQ$aES1ONa50097b6`6O^&^nH5>Uu78=+UptljwyRbd@W# zfT1jrG)GMY1|&zrehz5BfKzYJJU_lK`N?_CnS^!a2I$U$-CGYe4Z#kRzb@|2hf5@P z3{ZjF>U2l_+WIGZBHl;V|LR1Rbfo$G&xFxXX$X^mC{4Z7Uq;RU5~00#T8$V?4 zm0(Z@pa!7K?(Fv6`Sy%zIG6>&?npz0UV%?bgx!7tH#C%jM34vHZxVr2-GyqR){Wb_ z{XsWBT$ZExT8-J6M|x?bD~-_)p-JamyVJi9497FdEQ65@I<~MMyg{tluUqokqOaxj zlhqj9JtQiyyKdy8TBK}e2S{tm<$7FGKad_^`^?rYM0;cj^51yOyC%wV#(=?x_-cVmn-um!xGBCj903_NLpqj#fY94K!%&o7 zw|E3wgmzMa{N+PDQQ4BhoE7KBA!Hxyi2D5IJ4civ7g7A4#@Va i>Ut2fuAI+%0QCxKtaJZ4tp|R<30%KGIZqYwf2q$ - - - net_4_0_Debug - AnyCPU - 9.0.30729 - 2.0 - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC} - Library - Properties - Mono.Cecil.Rocks - Mono.Cecil.Rocks - 512 - true - ..\mono.snk - - - true - full - false - ..\bin\net_3_5_Debug\ - DEBUG;TRACE;INSIDE_ROCKS;NET_3_5 - prompt - 4 - v3.5 - - - pdbonly - true - ..\bin\net_3_5_Release\ - TRACE;INSIDE_ROCKS;NET_3_5 - prompt - 4 - v3.5 - - - true - full - false - ..\bin\net_4_0_Debug\ - DEBUG;TRACE;INSIDE_ROCKS;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - pdbonly - true - ..\bin\net_4_0_Release\ - TRACE;INSIDE_ROCKS;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - true - full - false - ..\bin\silverlight_Debug\ - DEBUG;TRACE;NET_3_5;NET_4_0;SILVERLIGHT - prompt - 4 - Silverlight - v4.0 - - - pdbonly - true - ..\bin\silverlight_Release\ - TRACE;NET_3_5;NET_4_0;SILVERLIGHT - prompt - 4 - Silverlight - v4.0 - - - true - full - false - ..\bin\winphone_Debug\ - DEBUG;TRACE;NET_3_5;NET_4_0;SILVERLIGHT;CF - prompt - 4 - WindowsPhone - Silverlight - v4.0 - - - pdbonly - true - ..\bin\winphone_Release\ - TRACE;NET_3_5;NET_4_0;SILVERLIGHT;CF - prompt - 4 - WindowsPhone - Silverlight - v4.0 - - - - 3.5 - - - - - - - - - - - - - - - - {D68133BD-1E63-496E-9EDE-4FBDBF77B486} - Mono.Cecil - - - - - \ No newline at end of file diff --git a/Mono.Cecil/rocks/Mono.Cecil.Rocks/AssemblyInfo.cs b/Mono.Cecil/rocks/Mono.Cecil.Rocks/AssemblyInfo.cs deleted file mode 100644 index 90543bb5e..000000000 --- a/Mono.Cecil/rocks/Mono.Cecil.Rocks/AssemblyInfo.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// 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; -using System.Reflection; -using System.Runtime.InteropServices; - -[assembly: AssemblyTitle ("Mono.Cecil.Rocks")] -[assembly: AssemblyProduct ("Mono.Cecil")] -[assembly: AssemblyCopyright ("Copyright © 2008 - 2011 Jb Evain")] - -[assembly: CLSCompliant (false)] -[assembly: ComVisible (false)] - -[assembly: AssemblyVersion ("0.9.5.0")] -[assembly: AssemblyFileVersion ("0.9.5.0")] diff --git a/Mono.Cecil/rocks/Mono.Cecil.Rocks/Functional.cs b/Mono.Cecil/rocks/Mono.Cecil.Rocks/Functional.cs deleted file mode 100644 index 0e61b47bc..000000000 --- a/Mono.Cecil/rocks/Mono.Cecil.Rocks/Functional.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// Functional.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.Rocks { - - static class Functional { - - public static System.Func Y (System.Func, System.Func> f) - { - System.Func g = null; - g = f (a => g (a)); - return g; - } - - public static IEnumerable Prepend (this IEnumerable source, TSource element) - { - if (source == null) - throw new ArgumentNullException ("source"); - - return PrependIterator (source, element); - } - - static IEnumerable PrependIterator (IEnumerable source, TSource element) - { - yield return element; - - foreach (var item in source) - yield return item; - } - } -} diff --git a/Mono.Cecil/rocks/Mono.Cecil.Rocks/ILParser.cs b/Mono.Cecil/rocks/Mono.Cecil.Rocks/ILParser.cs deleted file mode 100644 index 6f745bc12..000000000 --- a/Mono.Cecil/rocks/Mono.Cecil.Rocks/ILParser.cs +++ /dev/null @@ -1,236 +0,0 @@ -// -// ILParser.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.Cil; -using Mono.Collections.Generic; - -namespace Mono.Cecil.Rocks { - -#if INSIDE_ROCKS - public -#endif - interface IILVisitor { - void OnInlineNone (OpCode opcode); - void OnInlineSByte (OpCode opcode, sbyte value); - void OnInlineByte (OpCode opcode, byte value); - void OnInlineInt32 (OpCode opcode, int value); - void OnInlineInt64 (OpCode opcode, long value); - void OnInlineSingle (OpCode opcode, float value); - void OnInlineDouble (OpCode opcode, double value); - void OnInlineString (OpCode opcode, string value); - void OnInlineBranch (OpCode opcode, int offset); - void OnInlineSwitch (OpCode opcode, int [] offsets); - void OnInlineVariable (OpCode opcode, VariableDefinition variable); - void OnInlineArgument (OpCode opcode, ParameterDefinition parameter); - void OnInlineSignature (OpCode opcode, CallSite callSite); - void OnInlineType (OpCode opcode, TypeReference type); - void OnInlineField (OpCode opcode, FieldReference field); - void OnInlineMethod (OpCode opcode, MethodReference method); - } - -#if INSIDE_ROCKS - public -#endif - static class ILParser { - - class ParseContext { - public CodeReader Code { get; set; } - public MetadataReader Metadata { get; set; } - public Collection Variables { get; set; } - public IILVisitor Visitor { get; set; } - } - - public static void Parse (MethodDefinition method, IILVisitor visitor) - { - if (method == null) - throw new ArgumentNullException ("method"); - if (visitor == null) - throw new ArgumentNullException ("visitor"); - if (!method.HasBody || !method.HasImage) - throw new ArgumentException (); - - var context = CreateContext (method, visitor); - var code = context.Code; - - code.MoveTo (method.RVA); - - var flags = code.ReadByte (); - - switch (flags & 0x3) { - case 0x2: // tiny - int code_size = flags >> 2; - ParseCode (code_size, context); - break; - case 0x3: // fat - code.position--; - ParseFatMethod (context); - break; - default: - throw new NotSupportedException (); - } - } - - static ParseContext CreateContext (MethodDefinition method, IILVisitor visitor) - { - var code = method.Module.Read (method, (_, reader) => new CodeReader (reader.image.MetadataSection, reader)); - - return new ParseContext { - Code = code, - Metadata = code.reader, - Visitor = visitor, - }; - } - - static void ParseFatMethod (ParseContext context) - { - var code = context.Code; - - code.Advance (4); - var code_size = code.ReadInt32 (); - var local_var_token = code.ReadToken (); - - if (local_var_token != MetadataToken.Zero) - context.Variables = code.ReadVariables (local_var_token); - - ParseCode (code_size, context); - } - - static void ParseCode (int code_size, ParseContext context) - { - var code = context.Code; - var metadata = context.Metadata; - var visitor = context.Visitor; - - var start = code.position; - var end = start + code_size; - - while (code.position < end) { - var il_opcode = code.ReadByte (); - var opcode = il_opcode != 0xfe - ? OpCodes.OneByteOpCode [il_opcode] - : OpCodes.TwoBytesOpCode [code.ReadByte ()]; - - switch (opcode.OperandType) { - case OperandType.InlineNone: - visitor.OnInlineNone (opcode); - break; - case OperandType.InlineSwitch: - var length = code.ReadInt32 (); - var branches = new int [length]; - for (int i = 0; i < length; i++) - branches [i] = code.ReadInt32 (); - visitor.OnInlineSwitch (opcode, branches); - break; - case OperandType.ShortInlineBrTarget: - visitor.OnInlineBranch (opcode, code.ReadSByte ()); - break; - case OperandType.InlineBrTarget: - visitor.OnInlineBranch (opcode, code.ReadInt32 ()); - break; - case OperandType.ShortInlineI: - if (opcode == OpCodes.Ldc_I4_S) - visitor.OnInlineSByte (opcode, code.ReadSByte ()); - else - visitor.OnInlineByte (opcode, code.ReadByte ()); - break; - case OperandType.InlineI: - visitor.OnInlineInt32 (opcode, code.ReadInt32 ()); - break; - case OperandType.InlineI8: - visitor.OnInlineInt64 (opcode, code.ReadInt64 ()); - break; - case OperandType.ShortInlineR: - visitor.OnInlineSingle (opcode, code.ReadSingle ()); - break; - case OperandType.InlineR: - visitor.OnInlineDouble (opcode, code.ReadDouble ()); - break; - case OperandType.InlineSig: - visitor.OnInlineSignature (opcode, code.GetCallSite (code.ReadToken ())); - break; - case OperandType.InlineString: - visitor.OnInlineString (opcode, code.GetString (code.ReadToken ())); - break; - case OperandType.ShortInlineArg: - visitor.OnInlineArgument (opcode, code.GetParameter (code.ReadByte ())); - break; - case OperandType.InlineArg: - visitor.OnInlineArgument (opcode, code.GetParameter (code.ReadInt16 ())); - break; - case OperandType.ShortInlineVar: - visitor.OnInlineVariable (opcode, GetVariable (context, code.ReadByte ())); - break; - case OperandType.InlineVar: - visitor.OnInlineVariable (opcode, GetVariable (context, code.ReadInt16 ())); - break; - case OperandType.InlineTok: - case OperandType.InlineField: - case OperandType.InlineMethod: - case OperandType.InlineType: - var member = metadata.LookupToken (code.ReadToken ()); - switch (member.MetadataToken.TokenType) { - case TokenType.TypeDef: - case TokenType.TypeRef: - case TokenType.TypeSpec: - visitor.OnInlineType (opcode, (TypeReference) member); - break; - case TokenType.Method: - case TokenType.MethodSpec: - visitor.OnInlineMethod (opcode, (MethodReference) member); - break; - case TokenType.Field: - visitor.OnInlineField (opcode, (FieldReference) member); - break; - case TokenType.MemberRef: - var field_ref = member as FieldReference; - if (field_ref != null) { - visitor.OnInlineField (opcode, field_ref); - break; - } - - var method_ref = member as MethodReference; - if (method_ref != null) { - visitor.OnInlineMethod (opcode, method_ref); - break; - } - - throw new InvalidOperationException (); - } - break; - } - } - } - - static VariableDefinition GetVariable (ParseContext context, int index) - { - return context.Variables [index]; - } - } -} diff --git a/Mono.Cecil/rocks/Mono.Cecil.Rocks/MethodBodyRocks.cs b/Mono.Cecil/rocks/Mono.Cecil.Rocks/MethodBodyRocks.cs deleted file mode 100644 index f141f6084..000000000 --- a/Mono.Cecil/rocks/Mono.Cecil.Rocks/MethodBodyRocks.cs +++ /dev/null @@ -1,407 +0,0 @@ -// -// MethodBodyRocks.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.Cil; - -namespace Mono.Cecil.Rocks { - -#if INSIDE_ROCKS - public -#endif - static class MethodBodyRocks { - - public static void SimplifyMacros (this MethodBody self) - { - if (self == null) - throw new ArgumentNullException ("self"); - - foreach (var instruction in self.Instructions) { - if (instruction.OpCode.OpCodeType != OpCodeType.Macro) - continue; - - switch (instruction.OpCode.Code) { - case Code.Ldarg_0: - ExpandMacro (instruction, OpCodes.Ldarg, self.GetParameter (0)); - break; - case Code.Ldarg_1: - ExpandMacro (instruction, OpCodes.Ldarg, self.GetParameter (1)); - break; - case Code.Ldarg_2: - ExpandMacro (instruction, OpCodes.Ldarg, self.GetParameter (2)); - break; - case Code.Ldarg_3: - ExpandMacro (instruction, OpCodes.Ldarg, self.GetParameter (3)); - break; - case Code.Ldloc_0: - ExpandMacro (instruction, OpCodes.Ldloc, self.Variables [0]); - break; - case Code.Ldloc_1: - ExpandMacro (instruction, OpCodes.Ldloc, self.Variables [1]); - break; - case Code.Ldloc_2: - ExpandMacro (instruction, OpCodes.Ldloc, self.Variables [2]); - break; - case Code.Ldloc_3: - ExpandMacro (instruction, OpCodes.Ldloc, self.Variables [3]); - break; - case Code.Stloc_0: - ExpandMacro (instruction, OpCodes.Stloc, self.Variables [0]); - break; - case Code.Stloc_1: - ExpandMacro (instruction, OpCodes.Stloc, self.Variables [1]); - break; - case Code.Stloc_2: - ExpandMacro (instruction, OpCodes.Stloc, self.Variables [2]); - break; - case Code.Stloc_3: - ExpandMacro (instruction, OpCodes.Stloc, self.Variables [3]); - break; - case Code.Ldarg_S: - instruction.OpCode = OpCodes.Ldarg; - break; - case Code.Ldarga_S: - instruction.OpCode = OpCodes.Ldarga; - break; - case Code.Starg_S: - instruction.OpCode = OpCodes.Starg; - break; - case Code.Ldloc_S: - instruction.OpCode = OpCodes.Ldloc; - break; - case Code.Ldloca_S: - instruction.OpCode = OpCodes.Ldloca; - break; - case Code.Stloc_S: - instruction.OpCode = OpCodes.Stloc; - break; - case Code.Ldc_I4_M1: - ExpandMacro (instruction, OpCodes.Ldc_I4, -1); - break; - case Code.Ldc_I4_0: - ExpandMacro (instruction, OpCodes.Ldc_I4, 0); - break; - case Code.Ldc_I4_1: - ExpandMacro (instruction, OpCodes.Ldc_I4, 1); - break; - case Code.Ldc_I4_2: - ExpandMacro (instruction, OpCodes.Ldc_I4, 2); - break; - case Code.Ldc_I4_3: - ExpandMacro (instruction, OpCodes.Ldc_I4, 3); - break; - case Code.Ldc_I4_4: - ExpandMacro (instruction, OpCodes.Ldc_I4, 4); - break; - case Code.Ldc_I4_5: - ExpandMacro (instruction, OpCodes.Ldc_I4, 5); - break; - case Code.Ldc_I4_6: - ExpandMacro (instruction, OpCodes.Ldc_I4, 6); - break; - case Code.Ldc_I4_7: - ExpandMacro (instruction, OpCodes.Ldc_I4, 7); - break; - case Code.Ldc_I4_8: - ExpandMacro (instruction, OpCodes.Ldc_I4, 8); - break; - case Code.Ldc_I4_S: - ExpandMacro (instruction, OpCodes.Ldc_I4, (int) (sbyte) instruction.Operand); - break; - case Code.Br_S: - instruction.OpCode = OpCodes.Br; - break; - case Code.Brfalse_S: - instruction.OpCode = OpCodes.Brfalse; - break; - case Code.Brtrue_S: - instruction.OpCode = OpCodes.Brtrue; - break; - case Code.Beq_S: - instruction.OpCode = OpCodes.Beq; - break; - case Code.Bge_S: - instruction.OpCode = OpCodes.Bge; - break; - case Code.Bgt_S: - instruction.OpCode = OpCodes.Bgt; - break; - case Code.Ble_S: - instruction.OpCode = OpCodes.Ble; - break; - case Code.Blt_S: - instruction.OpCode = OpCodes.Blt; - break; - case Code.Bne_Un_S: - instruction.OpCode = OpCodes.Bne_Un; - break; - case Code.Bge_Un_S: - instruction.OpCode = OpCodes.Bge_Un; - break; - case Code.Bgt_Un_S: - instruction.OpCode = OpCodes.Bgt_Un; - break; - case Code.Ble_Un_S: - instruction.OpCode = OpCodes.Ble_Un; - break; - case Code.Blt_Un_S: - instruction.OpCode = OpCodes.Blt_Un; - break; - case Code.Leave_S: - instruction.OpCode = OpCodes.Leave; - break; - } - } - } - - static void ExpandMacro (Instruction instruction, OpCode opcode, object operand) - { - instruction.OpCode = opcode; - instruction.Operand = operand; - } - - static void MakeMacro (Instruction instruction, OpCode opcode) - { - instruction.OpCode = opcode; - instruction.Operand = null; - } - - public static void OptimizeMacros (this MethodBody self) - { - if (self == null) - throw new ArgumentNullException ("self"); - - var method = self.Method; - - foreach (var instruction in self.Instructions) { - int index; - switch (instruction.OpCode.Code) { - case Code.Ldarg: - index = ((ParameterDefinition) instruction.Operand).Index; - if (index == -1 && instruction.Operand == self.ThisParameter) - index = 0; - else if (method.HasThis) - index++; - - switch (index) { - case 0: - MakeMacro (instruction, OpCodes.Ldarg_0); - break; - case 1: - MakeMacro (instruction, OpCodes.Ldarg_1); - break; - case 2: - MakeMacro (instruction, OpCodes.Ldarg_2); - break; - case 3: - MakeMacro (instruction, OpCodes.Ldarg_3); - break; - default: - if (index < 256) - ExpandMacro (instruction, OpCodes.Ldarg_S, instruction.Operand); - break; - } - break; - case Code.Ldloc: - index = ((VariableDefinition) instruction.Operand).Index; - switch (index) { - case 0: - MakeMacro (instruction, OpCodes.Ldloc_0); - break; - case 1: - MakeMacro (instruction, OpCodes.Ldloc_1); - break; - case 2: - MakeMacro (instruction, OpCodes.Ldloc_2); - break; - case 3: - MakeMacro (instruction, OpCodes.Ldloc_3); - break; - default: - if (index < 256) - ExpandMacro (instruction, OpCodes.Ldloc_S, instruction.Operand); - break; - } - break; - case Code.Stloc: - index = ((VariableDefinition) instruction.Operand).Index; - switch (index) { - case 0: - MakeMacro (instruction, OpCodes.Stloc_0); - break; - case 1: - MakeMacro (instruction, OpCodes.Stloc_1); - break; - case 2: - MakeMacro (instruction, OpCodes.Stloc_2); - break; - case 3: - MakeMacro (instruction, OpCodes.Stloc_3); - break; - default: - if (index < 256) - ExpandMacro (instruction, OpCodes.Stloc_S, instruction.Operand); - break; - } - break; - case Code.Ldarga: - index = ((ParameterDefinition) instruction.Operand).Index; - if (index == -1 && instruction.Operand == self.ThisParameter) - index = 0; - else if (method.HasThis) - index++; - if (index < 256) - ExpandMacro (instruction, OpCodes.Ldarga_S, instruction.Operand); - break; - case Code.Ldloca: - if (((VariableDefinition) instruction.Operand).Index < 256) - ExpandMacro (instruction, OpCodes.Ldloca_S, instruction.Operand); - break; - case Code.Ldc_I4: - int i = (int) instruction.Operand; - switch (i) { - case -1: - MakeMacro (instruction, OpCodes.Ldc_I4_M1); - break; - case 0: - MakeMacro (instruction, OpCodes.Ldc_I4_0); - break; - case 1: - MakeMacro (instruction, OpCodes.Ldc_I4_1); - break; - case 2: - MakeMacro (instruction, OpCodes.Ldc_I4_2); - break; - case 3: - MakeMacro (instruction, OpCodes.Ldc_I4_3); - break; - case 4: - MakeMacro (instruction, OpCodes.Ldc_I4_4); - break; - case 5: - MakeMacro (instruction, OpCodes.Ldc_I4_5); - break; - case 6: - MakeMacro (instruction, OpCodes.Ldc_I4_6); - break; - case 7: - MakeMacro (instruction, OpCodes.Ldc_I4_7); - break; - case 8: - MakeMacro (instruction, OpCodes.Ldc_I4_8); - break; - default: - if (i >= -128 && i < 128) - ExpandMacro (instruction, OpCodes.Ldc_I4_S, (sbyte) i); - break; - } - break; - } - } - - OptimizeBranches (self); - } - - static void OptimizeBranches (MethodBody body) - { - ComputeOffsets (body); - - foreach (var instruction in body.Instructions) { - if (instruction.OpCode.OperandType != OperandType.InlineBrTarget) - continue; - - if (OptimizeBranch (instruction)) - ComputeOffsets (body); - } - } - - static bool OptimizeBranch (Instruction instruction) - { - var offset = ((Instruction) instruction.Operand).Offset - (instruction.Offset + instruction.OpCode.Size + 4); - if (!(offset >= -128 && offset <= 127)) - return false; - - switch (instruction.OpCode.Code) { - case Code.Br: - instruction.OpCode = OpCodes.Br_S; - break; - case Code.Brfalse: - instruction.OpCode = OpCodes.Brfalse_S; - break; - case Code.Brtrue: - instruction.OpCode = OpCodes.Brtrue_S; - break; - case Code.Beq: - instruction.OpCode = OpCodes.Beq_S; - break; - case Code.Bge: - instruction.OpCode = OpCodes.Bge_S; - break; - case Code.Bgt: - instruction.OpCode = OpCodes.Bgt_S; - break; - case Code.Ble: - instruction.OpCode = OpCodes.Ble_S; - break; - case Code.Blt: - instruction.OpCode = OpCodes.Blt_S; - break; - case Code.Bne_Un: - instruction.OpCode = OpCodes.Bne_Un_S; - break; - case Code.Bge_Un: - instruction.OpCode = OpCodes.Bge_Un_S; - break; - case Code.Bgt_Un: - instruction.OpCode = OpCodes.Bgt_Un_S; - break; - case Code.Ble_Un: - instruction.OpCode = OpCodes.Ble_Un_S; - break; - case Code.Blt_Un: - instruction.OpCode = OpCodes.Blt_Un_S; - break; - case Code.Leave: - instruction.OpCode = OpCodes.Leave_S; - break; - } - - return true; - } - - static void ComputeOffsets (MethodBody body) - { - var offset = 0; - foreach (var instruction in body.Instructions) { - instruction.Offset = offset; - offset += instruction.GetSize (); - } - } - } -} diff --git a/Mono.Cecil/rocks/Mono.Cecil.Rocks/MethodDefinitionRocks.cs b/Mono.Cecil/rocks/Mono.Cecil.Rocks/MethodDefinitionRocks.cs deleted file mode 100644 index c2f758d2e..000000000 --- a/Mono.Cecil/rocks/Mono.Cecil.Rocks/MethodDefinitionRocks.cs +++ /dev/null @@ -1,88 +0,0 @@ -// -// MethodDefinitionRocks.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.Rocks { - -#if INSIDE_ROCKS - public -#endif - static class MethodDefinitionRocks { - - public static MethodDefinition GetBaseMethod (this MethodDefinition self) - { - if (self == null) - throw new ArgumentNullException ("self"); - if (!self.IsVirtual) - return self; - - var base_type = ResolveBaseType (self.DeclaringType); - while (base_type != null) { - var @base = GetMatchingMethod (base_type, self); - if (@base != null) - return @base; - - base_type = ResolveBaseType (base_type); - } - - return self; - } - - public static MethodDefinition GetOriginalBaseMethod (this MethodDefinition self) - { - if (self == null) - throw new ArgumentNullException ("self"); - - while (true) { - var @base = self.GetBaseMethod (); - if (@base == self) - return self; - - self = @base; - } - } - - static TypeDefinition ResolveBaseType (TypeDefinition type) - { - if (type == null) - return null; - - var base_type = type.BaseType; - if (base_type == null) - return null; - - return base_type.Resolve (); - } - - static MethodDefinition GetMatchingMethod (TypeDefinition type, MethodDefinition method) - { - return MetadataResolver.GetMethod (type.Methods, method); - } - } -} diff --git a/Mono.Cecil/rocks/Mono.Cecil.Rocks/ModuleDefinitionRocks.cs b/Mono.Cecil/rocks/Mono.Cecil.Rocks/ModuleDefinitionRocks.cs deleted file mode 100644 index 5aaf73ce9..000000000 --- a/Mono.Cecil/rocks/Mono.Cecil.Rocks/ModuleDefinitionRocks.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -// ModuleDefinitionRocks.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.Linq; - -namespace Mono.Cecil.Rocks { - -#if INSIDE_ROCKS - public -#endif - static class ModuleDefinitionRocks { - - public static IEnumerable GetAllTypes (this ModuleDefinition self) - { - if (self == null) - throw new ArgumentNullException ("self"); - - // it was fun to write, but we need a somewhat less convoluted implementation - return self.Types.SelectMany ( - Functional.Y> (f => type => type.NestedTypes.SelectMany (f).Prepend (type))); - } - } -} diff --git a/Mono.Cecil/rocks/Mono.Cecil.Rocks/ParameterReferenceRocks.cs b/Mono.Cecil/rocks/Mono.Cecil.Rocks/ParameterReferenceRocks.cs deleted file mode 100644 index 554bdb909..000000000 --- a/Mono.Cecil/rocks/Mono.Cecil.Rocks/ParameterReferenceRocks.cs +++ /dev/null @@ -1,11 +0,0 @@ - -namespace Mono.Cecil.Rocks { - - public static class ParameterReferenceRocks { - - public static int GetSequence (this ParameterReference self) - { - return self.Index + 1; - } - } -} diff --git a/Mono.Cecil/rocks/Mono.Cecil.Rocks/SecurityDeclarationRocks.cs b/Mono.Cecil/rocks/Mono.Cecil.Rocks/SecurityDeclarationRocks.cs deleted file mode 100644 index b84696fc6..000000000 --- a/Mono.Cecil/rocks/Mono.Cecil.Rocks/SecurityDeclarationRocks.cs +++ /dev/null @@ -1,174 +0,0 @@ -// -// SecurityDeclarationRocks.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 !SILVERLIGHT && !CF - -using System; -using System.Security; -using SSP = System.Security.Permissions; - -namespace Mono.Cecil.Rocks { - -#if INSIDE_ROCKS - public -#endif - static class SecurityDeclarationRocks { - - public static PermissionSet ToPermissionSet (this SecurityDeclaration self) - { - if (self == null) - throw new ArgumentNullException ("self"); - - PermissionSet set; - if (TryProcessPermissionSetAttribute (self, out set)) - return set; - - return CreatePermissionSet (self); - } - - static bool TryProcessPermissionSetAttribute (SecurityDeclaration declaration, out PermissionSet set) - { - set = null; - - if (!declaration.HasSecurityAttributes && declaration.SecurityAttributes.Count != 1) - return false; - - var security_attribute = declaration.SecurityAttributes [0]; - if (!security_attribute.AttributeType.IsTypeOf ("System.Security.Permissions", "PermissionSetAttribute")) - return false; - - var attribute = new SSP.PermissionSetAttribute ((SSP.SecurityAction) declaration.Action); - - var named_argument = security_attribute.Properties [0]; - string value = (string) named_argument.Argument.Value; - switch (named_argument.Name) { - case "XML": - attribute.XML = value; - break; - case "Name": - attribute.Name = value; - break; - default: - throw new NotImplementedException (named_argument.Name); - } - - set = attribute.CreatePermissionSet (); - return true; - } - - static PermissionSet CreatePermissionSet (SecurityDeclaration declaration) - { - var set = new PermissionSet (SSP.PermissionState.None); - - foreach (var attribute in declaration.SecurityAttributes) { - var permission = CreatePermission (declaration, attribute); - set.AddPermission (permission); - } - - return set; - } - - static IPermission CreatePermission (SecurityDeclaration declaration, SecurityAttribute attribute) - { - var attribute_type = Type.GetType (attribute.AttributeType.FullName); - if (attribute_type == null) - throw new ArgumentException ("attribute"); - - var security_attribute = CreateSecurityAttribute (attribute_type, declaration); - if (security_attribute == null) - throw new InvalidOperationException (); - - CompleteSecurityAttribute (security_attribute, attribute); - - return security_attribute.CreatePermission (); - } - - static void CompleteSecurityAttribute (SSP.SecurityAttribute security_attribute, SecurityAttribute attribute) - { - if (attribute.HasFields) - CompleteSecurityAttributeFields (security_attribute, attribute); - - if (attribute.HasProperties) - CompleteSecurityAttributeProperties (security_attribute, attribute); - } - - static void CompleteSecurityAttributeFields (SSP.SecurityAttribute security_attribute, SecurityAttribute attribute) - { - var type = security_attribute.GetType (); - - foreach (var named_argument in attribute.Fields) - type.GetField (named_argument.Name).SetValue (security_attribute, named_argument.Argument.Value); - } - - static void CompleteSecurityAttributeProperties (SSP.SecurityAttribute security_attribute, SecurityAttribute attribute) - { - var type = security_attribute.GetType (); - - foreach (var named_argument in attribute.Properties) - type.GetProperty (named_argument.Name).SetValue (security_attribute, named_argument.Argument.Value, null); - } - - static SSP.SecurityAttribute CreateSecurityAttribute (Type attribute_type, SecurityDeclaration declaration) - { - SSP.SecurityAttribute security_attribute; - try { - security_attribute = (SSP.SecurityAttribute) Activator.CreateInstance ( - attribute_type, new object [] { (SSP.SecurityAction) declaration.Action }); - } catch (MissingMethodException) { - security_attribute = (SSP.SecurityAttribute) Activator.CreateInstance (attribute_type, new object [0]); - } - - return security_attribute; - } - - public static SecurityDeclaration ToSecurityDeclaration (this PermissionSet self, SecurityAction action, ModuleDefinition module) - { - if (self == null) - throw new ArgumentNullException ("self"); - if (module == null) - throw new ArgumentNullException ("module"); - - var declaration = new SecurityDeclaration (action); - - var attribute = new SecurityAttribute ( - module.TypeSystem.LookupType ("System.Security.Permissions", "PermissionSetAttribute")); - - attribute.Properties.Add ( - new CustomAttributeNamedArgument ( - "XML", - new CustomAttributeArgument ( - module.TypeSystem.String, self.ToXml ().ToString ()))); - - declaration.SecurityAttributes.Add (attribute); - - return declaration; - } - } -} - -#endif diff --git a/Mono.Cecil/rocks/Mono.Cecil.Rocks/TypeDefinitionRocks.cs b/Mono.Cecil/rocks/Mono.Cecil.Rocks/TypeDefinitionRocks.cs deleted file mode 100644 index 74b7f087f..000000000 --- a/Mono.Cecil/rocks/Mono.Cecil.Rocks/TypeDefinitionRocks.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -// TypeDefinitionRocks.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.Linq; - -namespace Mono.Cecil.Rocks { - -#if INSIDE_ROCKS - public -#endif - static class TypeDefinitionRocks { - - public static IEnumerable GetConstructors (this TypeDefinition self) - { - if (self == null) - throw new ArgumentNullException ("self"); - - if (!self.HasMethods) - return Empty.Array; - - return self.Methods.Where (method => method.IsConstructor); - } - - public static MethodDefinition GetStaticConstructor (this TypeDefinition self) - { - if (self == null) - throw new ArgumentNullException ("self"); - - if (!self.HasMethods) - return null; - - return self.GetConstructors ().FirstOrDefault (ctor => ctor.IsStatic); - } - - public static IEnumerable GetMethods (this TypeDefinition self) - { - if (self == null) - throw new ArgumentNullException ("self"); - - if (!self.HasMethods) - return Empty.Array; - - return self.Methods.Where (method => !method.IsConstructor); - } - - public static TypeReference GetEnumUnderlyingType (this TypeDefinition self) - { - if (self == null) - throw new ArgumentNullException ("self"); - if (!self.IsEnum) - throw new ArgumentException (); - - return Mixin.GetEnumUnderlyingType (self); - } - } -} diff --git a/Mono.Cecil/rocks/Mono.Cecil.Rocks/TypeReferenceRocks.cs b/Mono.Cecil/rocks/Mono.Cecil.Rocks/TypeReferenceRocks.cs deleted file mode 100644 index 5748b178f..000000000 --- a/Mono.Cecil/rocks/Mono.Cecil.Rocks/TypeReferenceRocks.cs +++ /dev/null @@ -1,107 +0,0 @@ -// -// TypeReferenceRocks.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.Linq; - -namespace Mono.Cecil.Rocks { - -#if INSIDE_ROCKS - public -#endif - static class TypeReferenceRocks { - - public static ArrayType MakeArrayType (this TypeReference self) - { - return new ArrayType (self); - } - - public static ArrayType MakeArrayType (this TypeReference self, int rank) - { - if (rank == 0) - throw new ArgumentOutOfRangeException ("rank"); - - var array = new ArrayType (self); - - for (int i = 1; i < rank; i++) - array.Dimensions.Add (new ArrayDimension ()); - - return array; - } - - public static PointerType MakePointerType (this TypeReference self) - { - return new PointerType (self); - } - - public static ByReferenceType MakeByReferenceType (this TypeReference self) - { - return new ByReferenceType (self); - } - - public static OptionalModifierType MakeOptionalModifierType (this TypeReference self, TypeReference modifierType) - { - return new OptionalModifierType (modifierType, self); - } - - public static RequiredModifierType MakeRequiredModifierType (this TypeReference self, TypeReference modifierType) - { - return new RequiredModifierType (modifierType, self); - } - - public static GenericInstanceType MakeGenericInstanceType (this TypeReference self, params TypeReference [] arguments) - { - if (self == null) - throw new ArgumentNullException ("self"); - if (arguments == null) - throw new ArgumentNullException ("arguments"); - if (arguments.Length == 0) - throw new ArgumentException (); - if (self.GenericParameters.Count != arguments.Length) - throw new ArgumentException (); - - var instance = new GenericInstanceType (self); - - foreach (var argument in arguments) - instance.GenericArguments.Add (argument); - - return instance; - } - - public static PinnedType MakePinnedType (this TypeReference self) - { - return new PinnedType (self); - } - - public static SentinelType MakeSentinelType (this TypeReference self) - { - return new SentinelType (self); - } - } -} diff --git a/Mono.Cecil/rocks/Test/.gitignore b/Mono.Cecil/rocks/Test/.gitignore deleted file mode 100644 index 3629e370c..000000000 --- a/Mono.Cecil/rocks/Test/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -bin -obj -*.suo -*.user -*.pidb -*.userprefs -*.xml diff --git a/Mono.Cecil/rocks/Test/Mono.Cecil.Rocks.Tests.csproj b/Mono.Cecil/rocks/Test/Mono.Cecil.Rocks.Tests.csproj deleted file mode 100644 index 3e7b8deb3..000000000 --- a/Mono.Cecil/rocks/Test/Mono.Cecil.Rocks.Tests.csproj +++ /dev/null @@ -1,106 +0,0 @@ - - - - net_4_0_Debug - AnyCPU - 9.0.30729 - 2.0 - {C6CFD7E1-B855-44DC-B4CE-9CD72984AF52} - Library - Properties - Mono.Cecil.Rocks.Tests - Mono.Cecil.Rocks.Tests - 512 - - - true - full - false - bin\net_3_5_Debug\ - DEBUG;TRACE;NET_3_5 - prompt - 4 - v3.5 - - - pdbonly - true - bin\net_3_5_Release\ - TRACE;NET_3_5 - prompt - 4 - v3.5 - - - true - full - false - bin\net_4_0_Debug\ - DEBUG;TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - pdbonly - true - bin\net_4_0_Release\ - TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - - False - ..\..\Test\libs\nunit-2.5.10\nunit.core.dll - - - False - ..\..\Test\libs\nunit-2.5.10\nunit.core.interfaces.dll - - - False - ..\..\Test\libs\nunit-2.5.10\nunit.framework.dll - - - - 3.5 - - - - - {D68133BD-1E63-496E-9EDE-4FBDBF77B486} - Mono.Cecil - - - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055} - Mono.Cecil.Tests - - - {FBC6DD59-D09D-499C-B03C-99C1C78FF2AC} - Mono.Cecil.Rocks - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/Addin.cs b/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/Addin.cs deleted file mode 100644 index 5a9f85f2a..000000000 --- a/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/Addin.cs +++ /dev/null @@ -1,8 +0,0 @@ -using NUnit.Core.Extensibility; - -namespace Mono.Cecil.Tests { - - [NUnitAddin] - public class CecilRocksAddin : CecilTestAddin { - } -} diff --git a/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/MethodDefinitionRocksTests.cs b/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/MethodDefinitionRocksTests.cs deleted file mode 100644 index 2cfe0142a..000000000 --- a/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/MethodDefinitionRocksTests.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System.Linq; - -using NUnit.Framework; - -using Mono.Cecil.Rocks; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class MethodDefinitionRocksTests : BaseTestFixture { - - abstract class Foo { - public abstract void DoFoo (); - } - - class Bar : Foo { - public override void DoFoo () - { - } - } - - class Baz : Bar { - public override void DoFoo () - { - } - } - - [Test] - public void GetBaseMethod () - { - var baz = typeof (Baz).ToDefinition (); - var baz_dofoo = baz.GetMethod ("DoFoo"); - - var @base = baz_dofoo.GetBaseMethod (); - Assert.AreEqual ("Bar", @base.DeclaringType.Name); - - @base = @base.GetBaseMethod (); - Assert.AreEqual ("Foo", @base.DeclaringType.Name); - - Assert.AreEqual (@base, @base.GetBaseMethod ()); - } - - [Test] - public void GetOriginalBaseMethod () - { - var baz = typeof (Baz).ToDefinition (); - var baz_dofoo = baz.GetMethod ("DoFoo"); - - var @base = baz_dofoo.GetOriginalBaseMethod (); - Assert.AreEqual ("Foo", @base.DeclaringType.Name); - } - } -} diff --git a/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/ModuleDefinitionRocksTests.cs b/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/ModuleDefinitionRocksTests.cs deleted file mode 100644 index f172b404e..000000000 --- a/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/ModuleDefinitionRocksTests.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Linq; - -using NUnit.Framework; - -using Mono.Cecil.Rocks; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class ModuleDefinitionRocksTests : BaseTestFixture { - - [TestCSharp ("Types.cs")] - public void GetAllTypesTest (ModuleDefinition module) - { - var sequence = new [] { - module.GetType (""), - module.GetType ("Foo"), - module.GetType ("Foo/Bar"), - module.GetType ("Foo/Gazonk"), - module.GetType ("Foo/Gazonk/Baz"), - module.GetType ("Pan"), - }; - - Assert.IsTrue (sequence.SequenceEqual (module.GetAllTypes ())); - } - } -} diff --git a/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/SecurityDeclarationRocksTests.cs b/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/SecurityDeclarationRocksTests.cs deleted file mode 100644 index e7efba127..000000000 --- a/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/SecurityDeclarationRocksTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Security.Permissions; - -using NUnit.Framework; - -using Mono.Cecil.Rocks; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class SecurityDeclarationRocksTests : BaseTestFixture { - - [TestModule ("decsec-xml.dll")] - public void ToPermissionSetFromPermissionSetAttribute (ModuleDefinition module) - { - var type = module.GetType ("SubLibrary"); - - Assert.IsTrue (type.HasSecurityDeclarations); - Assert.AreEqual (1, type.SecurityDeclarations.Count); - - var declaration = type.SecurityDeclarations [0]; - - var permission_set = declaration.ToPermissionSet (); - - Assert.IsNotNull (permission_set); - - string permission_set_value = "\r\n\r\n\r\n"; - - permission_set_value = string.Format (permission_set_value, typeof (SecurityPermission).AssemblyQualifiedName); - - Assert.AreEqual (Normalize (permission_set_value), Normalize (permission_set.ToXml ().ToString ())); - } - - [TestModule ("decsec-att.dll")] - public void ToPermissionSetFromSecurityAttribute (ModuleDefinition module) - { - var type = module.GetType ("SubLibrary"); - - Assert.IsTrue (type.HasSecurityDeclarations); - Assert.AreEqual (1, type.SecurityDeclarations.Count); - - var declaration = type.SecurityDeclarations [0]; - - var permission_set = declaration.ToPermissionSet (); - - Assert.IsNotNull (permission_set); - - string permission_set_value = "\r\n\r\n\r\n"; - - permission_set_value = string.Format (permission_set_value, typeof (SecurityPermission).AssemblyQualifiedName); - - Assert.AreEqual (Normalize (permission_set_value), Normalize (permission_set.ToXml ().ToString ())); - } - - static string Normalize (string s) - { - return s.Replace ("\n", "").Replace ("\r", ""); - } - } -} diff --git a/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/TypeDefinitionRocksTests.cs b/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/TypeDefinitionRocksTests.cs deleted file mode 100644 index 7bd43cf7e..000000000 --- a/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/TypeDefinitionRocksTests.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Mono.Cecil.Rocks; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class TypeDefinitionRocksTests { - - class Foo { - - static Foo () - { - } - - public Foo (int a) - { - } - - public Foo (int a, string s) - { - } - - public static void Bar () - { - } - - void Baz () - { - } - } - - [Test] - public void GetConstructors () - { - var foo = typeof (Foo).ToDefinition (); - var ctors = foo.GetConstructors ().Select (ctor => ctor.FullName); - - var expected = new [] { - "System.Void Mono.Cecil.Tests.TypeDefinitionRocksTests/Foo::.cctor()", - "System.Void Mono.Cecil.Tests.TypeDefinitionRocksTests/Foo::.ctor(System.Int32)", - "System.Void Mono.Cecil.Tests.TypeDefinitionRocksTests/Foo::.ctor(System.Int32,System.String)", - }; - - AssertSet (expected, ctors); - } - - static void AssertSet (IEnumerable expected, IEnumerable actual) - { - Assert.IsFalse (expected.Except (actual).Any ()); - Assert.IsTrue (expected.Intersect (actual).SequenceEqual (expected)); - } - - [Test] - public void GetStaticConstructor () - { - var foo = typeof (Foo).ToDefinition (); - var cctor = foo.GetStaticConstructor (); - - Assert.IsNotNull (cctor); - Assert.AreEqual ("System.Void Mono.Cecil.Tests.TypeDefinitionRocksTests/Foo::.cctor()", cctor.FullName); - } - - [Test] - public void GetMethods () - { - var foo = typeof (Foo).ToDefinition (); - var methods = foo.GetMethods ().ToArray (); - - Assert.AreEqual (2, methods.Length); - Assert.AreEqual ("System.Void Mono.Cecil.Tests.TypeDefinitionRocksTests/Foo::Bar()", methods [0].FullName); - Assert.AreEqual ("System.Void Mono.Cecil.Tests.TypeDefinitionRocksTests/Foo::Baz()", methods [1].FullName); - } - - enum Pan : byte { - Pin, - Pon, - } - - [Test] - public void GetEnumUnderlyingType () - { - var pan = typeof (Pan).ToDefinition (); - - Assert.IsNotNull (pan); - Assert.IsTrue (pan.IsEnum); - - var underlying_type = pan.GetEnumUnderlyingType (); - Assert.IsNotNull (underlying_type); - - Assert.AreEqual ("System.Byte", underlying_type.FullName); - } - } -} \ No newline at end of file diff --git a/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/TypeReferenceRocksTests.cs b/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/TypeReferenceRocksTests.cs deleted file mode 100644 index 9f51cb634..000000000 --- a/Mono.Cecil/rocks/Test/Mono.Cecil.Tests/TypeReferenceRocksTests.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System; - -using Mono.Cecil.Rocks; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class TypeReferenceRocksTests { - - [Test] - public void MakeArrayType () - { - var @string = GetTypeReference (typeof (string)); - - var string_array = @string.MakeArrayType (); - - Assert.IsInstanceOf (typeof (ArrayType), string_array); - Assert.AreEqual (1, string_array.Rank); - } - - [Test] - public void MakeArrayTypeRank () - { - var @string = GetTypeReference (typeof (string)); - - var string_array = @string.MakeArrayType (3); - - Assert.IsInstanceOf (typeof (ArrayType), string_array); - Assert.AreEqual (3, string_array.Rank); - } - - [Test] - public void MakePointerType () - { - var @string = GetTypeReference (typeof (string)); - - var string_ptr = @string.MakePointerType (); - - Assert.IsInstanceOf (typeof (PointerType), string_ptr); - } - - [Test] - public void MakeByReferenceType () - { - var @string = GetTypeReference (typeof (string)); - - var string_byref = @string.MakeByReferenceType (); - - Assert.IsInstanceOf (typeof (ByReferenceType), string_byref); - } - - class OptionalModifier {} - - [Test] - public void MakeOptionalModifierType () - { - var @string = GetTypeReference (typeof (string)); - var modopt = GetTypeReference (typeof (OptionalModifier)); - - var string_modopt = @string.MakeOptionalModifierType (modopt); - - Assert.IsInstanceOf (typeof (OptionalModifierType), string_modopt); - Assert.AreEqual (modopt, string_modopt.ModifierType); - } - - class RequiredModifier { } - - [Test] - public void MakeRequiredModifierType () - { - var @string = GetTypeReference (typeof (string)); - var modreq = GetTypeReference (typeof (RequiredModifierType)); - - var string_modreq = @string.MakeRequiredModifierType (modreq); - - Assert.IsInstanceOf (typeof (RequiredModifierType), string_modreq); - Assert.AreEqual (modreq, string_modreq.ModifierType); - } - - [Test] - public void MakePinnedType () - { - var byte_array = GetTypeReference (typeof (byte [])); - - var pinned_byte_array = byte_array.MakePinnedType (); - - Assert.IsInstanceOf (typeof (PinnedType), pinned_byte_array); - } - - [Test] - public void MakeSentinelType () - { - var @string = GetTypeReference (typeof (string)); - - var string_sentinel = @string.MakeSentinelType (); - - Assert.IsInstanceOf (typeof (SentinelType), string_sentinel); - } - - class Foo {} - - [Test] - public void MakeGenericInstanceType () - { - var foo = GetTypeReference (typeof (Foo<,>)); - var @string = GetTypeReference (typeof (string)); - var @int = GetTypeReference (typeof (int)); - - var foo_string_int = foo.MakeGenericInstanceType (@string, @int); - - Assert.IsInstanceOf (typeof (GenericInstanceType), foo_string_int); - Assert.AreEqual (2, foo_string_int.GenericArguments.Count); - Assert.AreEqual (@string, foo_string_int.GenericArguments [0]); - Assert.AreEqual (@int, foo_string_int.GenericArguments [1]); - } - - static TypeReference GetTypeReference (Type type) - { - return ModuleDefinition.ReadModule (typeof (TypeReferenceRocksTests).Module.FullyQualifiedName).Import (type); - } - } -} \ No newline at end of file diff --git a/Mono.Cecil/rocks/Test/Resources/assemblies/decsec-att.dll b/Mono.Cecil/rocks/Test/Resources/assemblies/decsec-att.dll deleted file mode 100644 index e9ac355408f5423bfea500f79051791f4d204aed..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4096 zcmeHKPiz!b82`<7w^^#KfXbg3aGIh)QZ_5J6cW&-e<(;xE4!^mjdXVQu^pM6X=Y}z zRikU7Mh+$%jF=dE;^4s;4oxH^CMJ5tvnNBmdhkXJ2kY;9v(u%}D4HHH;oH9N|NGwe zeecb@>G&%b(FP#RvAhgiB^4-W{P(CqbJvsCy0En2diPah?0R=;)(OqIz^?{Y&9p7g z^CPpY%%JX>j%N-}6wR7nQMt~}j$O^rlOw>G(S|R7x^yyG?FLfa4;fj2e`t@j-#krf zauhfOnIx$=Z*n?+p=fYWFVKdV*rymFB#rDJC<(!>bhcD422j ziFcOr@kAiaMQT1GU6T4t4ypBy^{Jl81z}**q;o5fk&Wu$xD5(yNG?#WPe+~W42=@2 zi{myZ0E4%Qn!PA}B}i^5WH4(2e`Ekdl>Y%bw(i-P+RY?8_H=ApVYzVeg+ZekRdPJP zFPG2t=Lhx;$RZiI#D}?P&%3}^q-o)cQQ&yhP&~e7J<_6{sUnuhb63$bI(1^0^he5l zJj6YNu3x4sK$S6C0yc8FpF)GI@p8`E|iMn7#eyhwaO#J;=FpABL zGm33^hPaEh2+rYATqAx0Kj-!3gd6G?gX(m7eW*+eq^?>_EDKJK!c|sXGA! zy$Q=r822l6S3QS{vO{I>wW26jab1i#<-iISP^^~|wieoc;5ua#7s5!@Fj0O(*%6NU zK5};C2N<-1rY%=gc0F*Sh1{eHYEBqBz84}s0kueq=lt~pWMXev7{b7@&ywdzK+nVJm#l6mL*%c-%; zx!-OzZe|ye{r0WbrnmRqxWL1frIV2{4P#ShnmF6|B4;!{h&!=nwJXXss_iwCUiO;P zDv<6Rkq3moUUR7KM)g1)@l-tuEVtL3te0KKKB*Q;{yF6xDGv--{dWI>XAkY~Q~863 zHXEf>=ag5oJgcfILww;HSwlZOz)m@rGH0E*c*v8^HXO0Kh zIqTT^2{b-#-Y@b%EedZ6cQ+*W5O8M54~AWL+;TkVr$QB&U#h4z>!q@g)`Xi}Ct3_={yM>5;KBXA0q?dSk z8_X%9mqUGZjYt=@Paesy4`uS;ZJFZSWaVM59>Ugf=2op^(l^f+Z_9U@z5%^kx#W41 zw+2waBlMSQBJJxjcbEOL_#L7cuR?4yg5bTnu80vT^pP(pV7Ja~jP|OYImD{xu%NT6 zVwO>%AHm~#or$JiIw0#LHHma@>-FjSCK<JANyZ%^Lxh}FGt!v+RP|K@A<{)3AQni zO*@|jnuV|sQYl((orI#uBahOGr$Mzc4h%+`HlhW`(1@$Jq3AEGTI|rc;yGdss;{8~ z(-BsO-*sX8q_b0v{i(3q=`6!a!(V&G&@G&|aaoNuLuMRPbrR1am1yGH^NAMLA2v3# zw(1kK<~UED)b)%;)|(Wu2fB!fT``D`3RL(wb`JBocP%qOrd$lHJd$SM`B<^cqGg`m z$U7LF^;Sxbb+(G8LT<*+`G#Lcrj(1jQ=W%0!^fqP8`ybk+{+h?z|Pr@9hA=n+`n8Y zu%d;M5mQpQY{&95mcMSBmfB!Zuug~8^zDtSOD_y>XJa=-#v|s`3pn&!7*OS2U5nK>3mtl+@AQo8y3d)j5vnBtDcpBG1hhy~^~0 zLCgwOQhE!|Ub*{uPBL@WFvD4^ob4!y1%=~pAfM!QvPyvx!z@?$be0obDYi}Qku~F-Ii-9R%h~Ux z2mN$G={+CWV@G<&^TmqLV~^HfblUY(7!5K@GCQA#F4j=2c#1)f{`DY%eF#sT2mS%T C7 - - - net_4_0_Debug - AnyCPU - 9.0.30729 - 2.0 - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD} - Library - Properties - Mono.Cecil.Mdb - Mono.Cecil.Mdb - 512 - true - ..\..\mono.snk - - - true - full - false - ..\..\bin\net_2_0_Debug\ - DEBUG;TRACE;CECIL - prompt - 4 - v2.0 - - - pdbonly - true - ..\..\bin\net_2_0_Release\ - TRACE;CECIL - prompt - 4 - v2.0 - - - true - full - false - ..\..\bin\net_3_5_Debug\ - DEBUG;TRACE;CECIL;NET_3_5 - prompt - 4 - v3.5 - - - pdbonly - true - ..\..\bin\net_3_5_Release\ - TRACE;CECIL;NET_3_5 - prompt - 4 - v3.5 - - - true - full - false - ..\..\bin\net_4_0_Debug\ - DEBUG;TRACE;CECIL;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - pdbonly - true - ..\..\bin\net_4_0_Release\ - TRACE;CECIL;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - - - - - - - - {D68133BD-1E63-496E-9EDE-4FBDBF77B486} - Mono.Cecil - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/AssemblyInfo.cs b/Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/AssemblyInfo.cs deleted file mode 100644 index 8186b506b..000000000 --- a/Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/AssemblyInfo.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// 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; -using System.Reflection; -using System.Runtime.InteropServices; - -[assembly: AssemblyTitle ("Mono.Cecil.Mdb")] -[assembly: AssemblyProduct ("Mono.Cecil")] -[assembly: AssemblyCopyright ("Copyright 2008 - 2011 Jb Evain")] - -[assembly: CLSCompliant (false)] -[assembly: ComVisible (false)] - -[assembly: AssemblyVersion ("0.9.5.0")] -[assembly: AssemblyFileVersion ("0.9.5.0")] diff --git a/Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/MdbReader.cs b/Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/MdbReader.cs deleted file mode 100644 index 2db041965..000000000 --- a/Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/MdbReader.cs +++ /dev/null @@ -1,213 +0,0 @@ -// -// 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 documents; - - public MdbReader (MonoSymbolFile symFile) - { - symbol_file = symFile; - documents = new Dictionary (); - } - - 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 (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 (); - } - } -} diff --git a/Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/MdbWriter.cs b/Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/MdbWriter.cs deleted file mode 100644 index 6f4aa20e3..000000000 --- a/Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/MdbWriter.cs +++ /dev/null @@ -1,251 +0,0 @@ -// -// 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 source_files; - - public MdbWriter (Guid mvid, string assembly) - { - this.mvid = mvid; - this.writer = new MonoSymbolWriter (assembly); - this.source_files = new Dictionary (); - } - - static Collection GetInstructions (MethodBody body) - { - var instructions = new Collection (); - 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 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 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 -} diff --git a/Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolFile.cs b/Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolFile.cs deleted file mode 100644 index 6ad39d237..000000000 --- a/Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolFile.cs +++ /dev/null @@ -1,738 +0,0 @@ -// -// 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 methods = new List (); - List sources = new List (); - List comp_units = new List (); - Dictionary type_hash = new Dictionary (); - Dictionary anonymous_scopes; - - OffsetTable ot; - int last_type_index; - int last_method_index; - int last_namespace_index; - - public readonly string FileName = ""; - 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 (); - - 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 source_file_hash; - Dictionary compile_unit_hash; - - List method_list; - Dictionary method_token_hash; - Dictionary 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 (); - compile_unit_hash = new Dictionary (); - } - - 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) - { - // Check that the MDB file matches the module, if we have been - // passed a module. - if (module == null) - return; - - 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); - } - - 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 (); - method_list = new List (); - - 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 (); - - 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 (); - 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; - } - } - } - } -} diff --git a/Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolTable.cs b/Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolTable.cs deleted file mode 100644 index c170150ce..000000000 --- a/Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolTable.cs +++ /dev/null @@ -1,1376 +0,0 @@ -// -// 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 - { - 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 - { - 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 OffsetComparer = new OffsetComparerClass (); - public static readonly IComparer 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 captured_vars = new List (); - List captured_scopes = new List (); - - 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 include_files; - List 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 (); - } - - public void AddFile (SourceFileEntry file) - { - if (!creating) - throw new InvalidOperationException (); - - if (include_files == null) - include_files = new List (); - - 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 (); - for (int i = 0; i < count_includes; i++) - include_files.Add (file.GetSourceFile (reader.ReadLeb128 ())); - } - - int count_ns = reader.ReadLeb128 (); - namespaces = new List (); - 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 (); - - 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 (); - 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); - } - } -} diff --git a/Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolWriter.cs b/Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolWriter.cs deleted file mode 100644 index db77c2527..000000000 --- a/Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolWriter.cs +++ /dev/null @@ -1,403 +0,0 @@ -// -// 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 methods; - List sources; - List 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 current_method_stack = new Stack (); -#endif - - public MonoSymbolWriter (string filename) - { - this.methods = new List (); - this.sources = new List (); - this.comp_units = new List (); - 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 _locals; - List _blocks; - List _scope_vars; -#if NET_2_1 - System.Collections.Stack _block_stack; -#else - Stack _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 (); -#endif - } - - if (_blocks == null) - _blocks = new List (); - - 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 (); - 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 (); - _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); - } - } -} diff --git a/Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/SymbolWriterImpl.cs b/Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/SymbolWriterImpl.cs deleted file mode 100644 index d9e30578e..000000000 --- a/Mono.Cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/SymbolWriterImpl.cs +++ /dev/null @@ -1,349 +0,0 @@ -// -// 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 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 (); - } -} diff --git a/Mono.Cecil/symbols/mdb/Test/.gitignore b/Mono.Cecil/symbols/mdb/Test/.gitignore deleted file mode 100644 index 17ff3483d..000000000 --- a/Mono.Cecil/symbols/mdb/Test/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -bin -obj -*.xml -*.user diff --git a/Mono.Cecil/symbols/mdb/Test/Mono.Cecil.Mdb.Tests.csproj b/Mono.Cecil/symbols/mdb/Test/Mono.Cecil.Mdb.Tests.csproj deleted file mode 100644 index 708f8009f..000000000 --- a/Mono.Cecil/symbols/mdb/Test/Mono.Cecil.Mdb.Tests.csproj +++ /dev/null @@ -1,119 +0,0 @@ - - - - net_4_0_Debug - AnyCPU - 9.0.30729 - 2.0 - {AC71DF9C-99FA-4A63-990A-66C8010355A6} - Library - Properties - Mono.Cecil.Mdb.Tests - Mono.Cecil.Mdb.Tests - 512 - - - true - full - false - bin\net_2_0_Debug\ - DEBUG;TRACE - prompt - 4 - v2.0 - - - pdbonly - true - bin\net_2_0_Release\ - TRACE - prompt - 4 - v2.0 - - - true - full - false - bin\net_3_5_Debug\ - DEBUG;TRACE;NET_3_5 - prompt - 4 - v3.5 - - - pdbonly - true - bin\net_3_5_Release\ - TRACE;NET_3_5 - prompt - 4 - v3.5 - - - true - full - false - bin\net_4_0_Debug\ - DEBUG;TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - pdbonly - true - bin\net_4_0_Release\ - TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - - - - - {D68133BD-1E63-496E-9EDE-4FBDBF77B486} - Mono.Cecil - - - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055} - Mono.Cecil.Tests - - - {8559DD7F-A16F-46D0-A05A-9139FAEBA8FD} - Mono.Cecil.Mdb - - - - - - - - - - - - - False - ..\..\..\Test\libs\nunit-2.5.10\nunit.core.dll - - - False - ..\..\..\Test\libs\nunit-2.5.10\nunit.core.interfaces.dll - - - False - ..\..\..\Test\libs\nunit-2.5.10\nunit.framework.dll - - - - - \ No newline at end of file diff --git a/Mono.Cecil/symbols/mdb/Test/Mono.Cecil.Tests/Addin.cs b/Mono.Cecil/symbols/mdb/Test/Mono.Cecil.Tests/Addin.cs deleted file mode 100644 index 4865122b0..000000000 --- a/Mono.Cecil/symbols/mdb/Test/Mono.Cecil.Tests/Addin.cs +++ /dev/null @@ -1,8 +0,0 @@ -using NUnit.Core.Extensibility; - -namespace Mono.Cecil.Tests { - - [NUnitAddin] - public class CecilMdbAddin : CecilTestAddin { - } -} diff --git a/Mono.Cecil/symbols/mdb/Test/Mono.Cecil.Tests/MdbTests.cs b/Mono.Cecil/symbols/mdb/Test/Mono.Cecil.Tests/MdbTests.cs deleted file mode 100644 index 757732d6e..000000000 --- a/Mono.Cecil/symbols/mdb/Test/Mono.Cecil.Tests/MdbTests.cs +++ /dev/null @@ -1,58 +0,0 @@ - -using Mono.Cecil.Mdb; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class MdbTests : BaseTestFixture { - - [TestModule ("hello.exe", SymbolReaderProvider = typeof (MdbReaderProvider), SymbolWriterProvider = typeof (MdbWriterProvider))] - public void Main (ModuleDefinition module) - { - var type = module.GetType ("Program"); - var main = type.GetMethod ("Main"); - - AssertCode (@" - .locals init (System.Int32 i) - .line 7,7:0,0 'C:\sources\cecil\symbols\Mono.Cecil.Mdb\Test\Resources\assemblies\hello.cs' - IL_0000: ldc.i4.0 - IL_0001: stloc.0 - .line 7,7:0,0 'C:\sources\cecil\symbols\Mono.Cecil.Mdb\Test\Resources\assemblies\hello.cs' - IL_0002: br IL_0013 - .line 8,8:0,0 'C:\sources\cecil\symbols\Mono.Cecil.Mdb\Test\Resources\assemblies\hello.cs' - IL_0007: ldarg.0 - IL_0008: ldloc.0 - IL_0009: ldelem.ref - IL_000a: call System.Void Program::Print(System.String) - .line 7,7:0,0 'C:\sources\cecil\symbols\Mono.Cecil.Mdb\Test\Resources\assemblies\hello.cs' - IL_000f: ldloc.0 - IL_0010: ldc.i4.1 - IL_0011: add - IL_0012: stloc.0 - IL_0013: ldloc.0 - IL_0014: ldarg.0 - IL_0015: ldlen - IL_0016: conv.i4 - IL_0017: blt IL_0007 - .line 10,10:0,0 'C:\sources\cecil\symbols\Mono.Cecil.Mdb\Test\Resources\assemblies\hello.cs' - IL_001c: ldc.i4.0 - IL_001d: ret -", main); - } - - static void AssertCode (string expected, MethodDefinition method) - { - Assert.IsTrue (method.HasBody); - Assert.IsNotNull (method.Body); - - Assert.AreEqual (Normalize (expected), Normalize (Formatter.FormatMethodBody (method))); - } - - static string Normalize (string str) - { - return str.Trim ().Replace ("\r\n", "\n"); - } - } -} diff --git a/Mono.Cecil/symbols/mdb/Test/Resources/assemblies/hello.exe b/Mono.Cecil/symbols/mdb/Test/Resources/assemblies/hello.exe deleted file mode 100644 index c2e4b9b38aae004609a24330f16a59a3313dbcc5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3072 zcmeHI&u<$=6#mw6Oln#yQAL`nZP+LQMOC%3N+2Lr#3V6oAit>7G%85V+8*qM^{%yE zmjnqE2?@akQK?)wgXob15)~3B4xB3SC-hFMUUJ5KZ+17?ga~m!;y|A>Gw;{D`QCf8 zlcgJ9q7Oipqt^rOaTO}*`R}J4nhVeVRKO3%?vLFw7VnR(HJy&x4*W)7x6GRDd46bC zl^JwB)A7vtm5SN&>&iNDB0mv_UM&NQMjuwre)VQ@+5;4fr;S_$N`MKO@hEW>bS9Tf z|*fDsc|5xxXGjQ5GSN1MR$J>j1-gC;PLa<5aql9H`Z zZH1IS6Ogp&1P+}~^`;ecf*Q>lTPgNqY0^|8dMi+_Pe+Y)lU9k9=SWcrm`#bA?L9YW zQolzfGh%PVt4Pb_C7+||=A0jtx73pDcxZKMexQ_9cU>frqP#QcM{x|;ATEP}xa2NS zPTG5P?0;7~nwjL$`ST}>S&T9?g`wg6%TlsT?(0c*B9}Y0k&4>q#c8qkqs@7jWBg;F&I7&?z7htG*XWSN0HaCH7eDHplBQgd8)M zS>Y3U0x#(~%4iS^l=|s!;GrpoPe(?yw5z4tcnc>fn`2_Tjki(I*UZ2=Wdk-5ivJLv zr{%QfEu6tQ^4T4_9H1g4L7$ME8xE8B&H1gi9XeIVb;9k} zLN=<}4OM)i6+2nt<+v)SsNj}UQ@WGH+GoNT`0>Mc)=y78_&f{4C@_hEbA`UAjDb<9 z;#y|-dSJJgeXqP#Q|-|4y|rfGf6y_`eDurosb3$JzwNKTa`%Pr?k1`Kx2vJA*GTk= zrl3UkgB{yRDal41lXq>S1l&or^G;@p+I3WLlXDqY$u01uU8cOi`Ss}4#n0KtenSyv+;n@Gg99pU_{}8m%_99olV#^z$i2^nG@h&<$b= z>E%%0I3m(-+NX%*H-##BV2UrhfmQDGQAZawMp-9@fM+GA6k*Xf8NdX07?|UZ7T*ZL zwaqHnlvIo<@i`dxu+Jo`VPKKF8r<#bh;7D_EE;GM31DiBdHP9JLXFJR-uuy-)Vlon z#Hg^v0bJ0rlZwt$*I{lFxy>j^W>NgJjGp8pImkK5XHnGkN#Y!?3{rKG`p6q7SXbg4 xq#Kf1vR|aAN=IWB9Q*Z%x?U%u7WV~se-9N8dP0A#fEoQC%Sa=h(EqLie*$+u1I_>d diff --git a/Mono.Cecil/symbols/mdb/Test/Resources/assemblies/hello.exe.mdb b/Mono.Cecil/symbols/mdb/Test/Resources/assemblies/hello.exe.mdb deleted file mode 100644 index f57f16561880fe11072c65c55af974adafa34d0a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 369 zcmWexR{vL7?S-om0|ZFd9yS+0{?>IVYl`IxwT~_~z&3 z>p6pj^n6p2VnR}jOJagjVQLeLi&Jxxax#J1GE#GL^7WF7RTtMRTe$DB%ao15PP32p zOm`CKzoNeG`?u5|6L@{6{Jj8lFBq}~R~DC~<}xrcfgHonz{X(1z{tq>ijna(;}@Va zfr>JLe2AnB13x#Hl(8pQsWeDYGZSM6(?pQN85o#(8M&=Nf-9I9S2C>v3Ia8={RGN< f1!5qVO%5m^1jN7qVKWBO+CU6M-~a^CcYqiG=b~8% diff --git a/Mono.Cecil/symbols/pdb/.gitignore b/Mono.Cecil/symbols/pdb/.gitignore deleted file mode 100644 index 17ff3483d..000000000 --- a/Mono.Cecil/symbols/pdb/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -bin -obj -*.xml -*.user diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/BitAccess.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/BitAccess.cs deleted file mode 100644 index e8e77b0bc..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/BitAccess.cs +++ /dev/null @@ -1,249 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -using System; -using System.IO; -using System.Text; - -namespace Microsoft.Cci.Pdb { - internal class BitAccess { - - internal BitAccess(int capacity) { - this.buffer = new byte[capacity]; - } - - 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 void Append(Stream stream, int count) { - int newCapacity = offset + count; - if (buffer.Length < newCapacity) { - byte[] newBuffer = new byte[newCapacity]; - Array.Copy(buffer, newBuffer, buffer.Length); - buffer = newBuffer; - } - stream.Read(buffer, offset, count); - offset += count; - } - - 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 ReadInt8(out sbyte value) { - value = (sbyte)buffer[offset]; - offset += 1; - } - - 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)(((ulong)buffer[offset + 0] & 0xFF) | - ((ulong)buffer[offset + 1] << 8) | - ((ulong)buffer[offset + 2] << 16) | - ((ulong)buffer[offset + 3] << 24) | - ((ulong)buffer[offset + 4] << 32) | - ((ulong)buffer[offset + 5] << 40) | - ((ulong)buffer[offset + 6] << 48) | - ((ulong)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)(((ulong)buffer[offset + 0] & 0xFF) | - ((ulong)buffer[offset + 1] << 8) | - ((ulong)buffer[offset + 2] << 16) | - ((ulong)buffer[offset + 3] << 24) | - ((ulong)buffer[offset + 4] << 32) | - ((ulong)buffer[offset + 5] << 40) | - ((ulong)buffer[offset + 6] << 48) | - ((ulong)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[2], bits[3], bits[1], bits[0] < 0, (byte)((bits[0] & 0x00FF0000) >> 16)); - } - - 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; - } - - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/BitSet.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/BitSet.cs deleted file mode 100644 index 671913171..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/BitSet.cs +++ /dev/null @@ -1,74 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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 static uint GetBit(int index) { - return ((uint)1 << (index % 32)); - } - - //private static 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; - } - -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/CvInfo.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/CvInfo.cs deleted file mode 100644 index 49c51ce1a..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/CvInfo.cs +++ /dev/null @@ -1,2435 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -// -// 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, - } -} \ No newline at end of file diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DataStream.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DataStream.cs deleted file mode 100644 index 48a185165..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DataStream.cs +++ /dev/null @@ -1,111 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -using System; -using System.IO; - -namespace Microsoft.Cci.Pdb { - internal class DataStream { - internal DataStream() { - } - - 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++; - } - } - - //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; - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiDbgHdr.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiDbgHdr.cs deleted file mode 100644 index 588f3c13d..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiDbgHdr.cs +++ /dev/null @@ -1,41 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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 - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiHeader.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiHeader.cs deleted file mode 100644 index 0ca791588..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiHeader.cs +++ /dev/null @@ -1,59 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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 - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiModuleInfo.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiModuleInfo.cs deleted file mode 100644 index 8ab371711..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiModuleInfo.cs +++ /dev/null @@ -1,57 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -using System; - -namespace Microsoft.Cci.Pdb { - internal class DbiModuleInfo { - internal DbiModuleInfo(BitAccess bits, bool readStrings) { - bits.ReadInt32(out opened); - 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; - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiSecCon.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiSecCon.cs deleted file mode 100644 index de9fde951..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/DbiSecCon.cs +++ /dev/null @@ -1,42 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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 - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/IntHashTable.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/IntHashTable.cs deleted file mode 100644 index db0e41be0..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/IntHashTable.cs +++ /dev/null @@ -1,583 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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 - //| - 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 static 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. - //| - 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. - //// - ////| - //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. - // - //| - 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 static 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. - // - //| - internal void Add(int key, Object value) { - Insert(key, value, true); - } - - //// Removes all entries from this hashtable. - ////| - //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. - // - //| - //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. - // - //| - 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. - // - //| - //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. - // - //| - //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; - // } - - // 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; - // } - //} - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/Interfaces.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/Interfaces.cs deleted file mode 100644 index 82561fbcc..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/Interfaces.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Microsoft.Cci { - - /// - /// A range of CLR IL operations that comprise a lexical scope, specified as an IL offset and a length. - /// - public interface ILocalScope { - /// - /// The offset of the first operation in the scope. - /// - uint Offset { get; } - - /// - /// The length of the scope. Offset+Length equals the offset of the first operation outside the scope, or equals the method body length. - /// - uint Length { get; } - } - - /// - /// 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. - /// - public interface INamespaceScope { - - /// - /// Zero or more used namespaces. These correspond to using clauses in C#. - /// - IEnumerable UsedNamespaces { get; } - - } - - - /// - /// A namespace that is used (imported) inside a namespace scope. - /// - public interface IUsedNamespace { - /// - /// An alias for a namespace. For example the "x" of "using x = y.z;" in C#. Empty if no alias is present. - /// - IName Alias { get; } - - /// - /// 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#. - /// - IName NamespaceName { get; } - } - - /// - /// 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. - /// - public interface IName { - /// - /// An integer that is unique within the pool from which the name instance has been allocated. Useful as a hashtable key. - /// - int UniqueKey { - get; - //^ ensures result > 0; - } - - /// - /// 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. - /// - int UniqueKeyIgnoringCase { - get; - //^ ensures result > 0; - } - - /// - /// The string value corresponding to this name. - /// - string Value { get; } - } -} \ No newline at end of file diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/LICENSE b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/LICENSE deleted file mode 100755 index 7bfc997e5..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -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. diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/MsfDirectory.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/MsfDirectory.cs deleted file mode 100644 index a6669b5bb..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/MsfDirectory.cs +++ /dev/null @@ -1,58 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -using System; - -namespace Microsoft.Cci.Pdb { - internal class MsfDirectory { - internal MsfDirectory(PdbReader reader, PdbFileHeader head, BitAccess bits) { - int pages = reader.PagesFromSize(head.directorySize); - - // 0..n in page of directory pages. - bits.MinCapacity(head.directorySize); - int directoryRootPages = head.directoryRoot.Length; - int pagesPerPage = head.pageSize / 4; - int pagesToGo = pages; - for (int i = 0; i < directoryRootPages; i++) { - int pagesInThisPage = pagesToGo <= pagesPerPage ? pagesToGo : pagesPerPage; - reader.Seek(head.directoryRoot[i], 0); - bits.Append(reader.reader, pagesInThisPage * 4); - pagesToGo -= pagesInThisPage; - } - bits.Position = 0; - - 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; - } - -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbConstant.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbConstant.cs deleted file mode 100644 index 434841b0c..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbConstant.cs +++ /dev/null @@ -1,89 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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 0x00: //sbyte - sbyte sb; - bits.ReadInt8(out sb); - this.value = sb; - break; - 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); - } - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbDebugException.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbDebugException.cs deleted file mode 100644 index d7f8f0fdb..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbDebugException.cs +++ /dev/null @@ -1,20 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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)) { - } - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbException.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbException.cs deleted file mode 100644 index 38d1d5636..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbException.cs +++ /dev/null @@ -1,20 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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)) { - } - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbFile.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbFile.cs deleted file mode 100644 index 9e5602812..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbFile.cs +++ /dev/null @@ -1,439 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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 LoadNameIndex(BitAccess bits, out int age, out Guid guid) { - Dictionary result = new Dictionary(); - 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.ToUpperInvariant(), 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 int FindFunction(PdbFunction[] funcs, ushort sec, uint off) { - match.segment = sec; - match.address = off; - - return Array.BinarySearch(funcs, match, PdbFunction.byAddress); - } - - static void LoadManagedLines(PdbFunction[] funcs, - IntHashTable names, - BitAccess bits, - MsfDirectory dir, - Dictionary nameIndex, - PdbReader reader, - uint limit) { - Array.Sort(funcs, PdbFunction.byAddressAndToken); - 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 = Guid.Empty; - Guid vendorGuid = Guid.Empty; - if (nameIndex.TryGetValue("/SRC/FILES/"+name.ToUpperInvariant(), 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); - int funcIndex = FindFunction(funcs, sec.sec, sec.off); - if (funcIndex < 0) break; - var func = funcs[funcIndex]; - if (func.lines == null) { - while (funcIndex > 0) { - var f = funcs[funcIndex-1]; - if (f.lines != null || f.segment != sec.sec || f.address != sec.off) break; - func = f; - funcIndex--; - } - } else { - while (funcIndex < funcs.Length-1 && func.lines != null) { - var f = funcs[funcIndex+1]; - if (f.segment != sec.sec || f.address != sec.off) break; - func = f; - funcIndex++; - } - } - if (func.lines != 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 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 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.byAddressAndToken); - //Array.Sort(funcs, PdbFunction.byToken); - return funcs; - } - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbFileHeader.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbFileHeader.cs deleted file mode 100644 index e1f56dbe4..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbFileHeader.cs +++ /dev/null @@ -1,90 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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; - //} - - internal PdbFileHeader(Stream reader, BitAccess bits) { - bits.MinCapacity(56); - reader.Seek(0, SeekOrigin.Begin); - bits.FillBuffer(reader, 52); - - 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 - - int directoryPages = ((((directorySize + pageSize - 1) / pageSize) * 4) + pageSize - 1) / pageSize; - this.directoryRoot = new int[directoryPages]; - bits.FillBuffer(reader, directoryPages * 4); - bits.ReadInt32(this.directoryRoot); - } - - //internal string Magic { - // get { return StringFromBytesUTF8(magic); } - //} - - //internal void Write(Stream writer, BitAccess bits) { - // bits.MinCapacity(pageSize); - // 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, pageSize); - //} - - //////////////////////////////////////////////////// Helper Functions. - // - //internal static string StringFromBytesUTF8(byte[] bytes) { - // return StringFromBytesUTF8(bytes, 0, bytes.Length); - //} - - //internal static 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; - } - -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbFunction.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbFunction.cs deleted file mode 100644 index d1daba14e..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbFunction.cs +++ /dev/null @@ -1,452 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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 byAddressAndToken = new PdbFunctionsByAddressAndToken(); - //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 PdbSlot[] slots; - internal PdbConstant[] constants; - internal string[] usedNamespaces; - internal PdbLines[] lines; - internal ushort[]/*?*/ usingCounts; - internal IEnumerable/*?*/ namespaceScopes; - internal string/*?*/ iteratorClass; - internal List/*?*/ 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; - - 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); - int scope = constantCount > 0 || slotCount > 0 || usedNamespacesCount > 0 ? 1 : 0; - int slot = 0; - int constant = 0; - int usedNs = 0; - scopes = new PdbScope[scopeCount+scope]; - slots = new PdbSlot[slotCount]; - constants = new PdbConstant[constantCount]; - usedNamespaces = new string[usedNamespacesCount]; - - if (scope > 0) - scopes[0] = new PdbScope(this.address, proc.len, slots, constants, usedNamespaces); - - 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 block.off); - bits.ReadUInt16(out block.seg); - bits.SkipCString(out block.name); - bits.Position = stop; - - scopes[scope++] = new PdbScope(this.address, block, bits, out slotToken); - bits.Position = (int)block.end; - break; - } - - case SYM.S_MANSLOT: - uint typind; - slots[slot++] = new PdbSlot(bits, out typind); - bits.Position = stop; - break; - - case SYM.S_MANCONSTANT: - constants[constant++] = new PdbConstant(bits); - 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; - - 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: break; // this.ReadForwardInfo(bits); break; - case 2: break; // 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((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 PdbFunctionsByAddressAndToken : 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 { - if (fx.token < fy.token) - return -1; - else if (fx.token > fy.token) - 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; - // } - // } - - //} - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbLine.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbLine.cs deleted file mode 100644 index f6fe3a9d3..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbLine.cs +++ /dev/null @@ -1,29 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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; - } - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbLines.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbLines.cs deleted file mode 100644 index 382638b70..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbLines.cs +++ /dev/null @@ -1,23 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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]; - } - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbReader.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbReader.cs deleted file mode 100644 index edfd9263c..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbReader.cs +++ /dev/null @@ -1,40 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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; - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbScope.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbScope.cs deleted file mode 100644 index c46220b80..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbScope.cs +++ /dev/null @@ -1,122 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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 offset; - internal uint length; - - internal PdbScope(uint address, uint length, PdbSlot[] slots, PdbConstant[] constants, string[] usedNamespaces) { - this.constants = constants; - this.slots = slots; - this.scopes = new PdbScope[0]; - this.usedNamespaces = usedNamespaces; - this.address = address; - this.offset = 0; - this.length = length; - } - - internal PdbScope(uint funcOffset, BlockSym32 block, BitAccess bits, out uint typind) { - //this.segment = block.seg; - this.address = block.off; - this.offset = block.off - funcOffset; - 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(funcOffset, 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; - break; - } - } - - 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"); - } - } - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbSlot.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbSlot.cs deleted file mode 100644 index 0dc89ad4d..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbSlot.cs +++ /dev/null @@ -1,40 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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; - } - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbSource.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbSource.cs deleted file mode 100644 index ac40f8516..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/PdbSource.cs +++ /dev/null @@ -1,29 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//----------------------------------------------------------------------------- -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; - } - } -} diff --git a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/SourceLocationProvider.cs b/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/SourceLocationProvider.cs deleted file mode 100644 index db3f291b4..000000000 --- a/Mono.Cecil/symbols/pdb/Microsoft.Cci.Pdb/SourceLocationProvider.cs +++ /dev/null @@ -1,33 +0,0 @@ -//----------------------------------------------------------------------------- -// -// 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 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; - } -} \ No newline at end of file diff --git a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb.csproj b/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb.csproj deleted file mode 100644 index 5248bad35..000000000 --- a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb.csproj +++ /dev/null @@ -1,130 +0,0 @@ - - - - net_4_0_Debug - AnyCPU - 9.0.30729 - 2.0 - {63E6915C-7EA4-4D76-AB28-0D7191EEA626} - Library - Properties - Mono.Cecil.Pdb - Mono.Cecil.Pdb - 512 - true - ..\..\mono.snk - 0649 - - - true - full - false - ..\..\bin\net_2_0_Debug\ - DEBUG;TRACE - prompt - 4 - v2.0 - - - pdbonly - true - ..\..\bin\net_2_0_Release\ - TRACE - prompt - 4 - v2.0 - - - true - full - false - ..\..\bin\net_3_5_Debug\ - DEBUG;TRACE;NET_3_5 - prompt - 4 - v3.5 - - - pdbonly - true - ..\..\bin\net_3_5_Release\ - TRACE;NET_3_5 - prompt - 4 - v3.5 - - - true - full - false - ..\..\bin\net_4_0_Debug\ - DEBUG;TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - pdbonly - true - ..\..\bin\net_4_0_Release\ - TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - - - - - - - - {D68133BD-1E63-496E-9EDE-4FBDBF77B486} - Mono.Cecil - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/AssemblyInfo.cs b/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/AssemblyInfo.cs deleted file mode 100644 index 14d267990..000000000 --- a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/AssemblyInfo.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// 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; -using System.Reflection; -using System.Runtime.InteropServices; - -[assembly: AssemblyTitle ("Mono.Cecil.Pdb")] -[assembly: AssemblyProduct ("Mono.Cecil")] -[assembly: AssemblyCopyright ("Copyright 2008 - 2011 Jb Evain")] - -[assembly: CLSCompliant (false)] -[assembly: ComVisible (false)] - -[assembly: AssemblyVersion ("0.9.5.0")] -[assembly: AssemblyFileVersion ("0.9.5.0")] diff --git a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/ISymUnmanagedDocumentWriter.cs b/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/ISymUnmanagedDocumentWriter.cs deleted file mode 100644 index 8f47b2c0f..000000000 --- a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/ISymUnmanagedDocumentWriter.cs +++ /dev/null @@ -1,41 +0,0 @@ -// 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 diff --git a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/ISymUnmanagedWriter2.cs b/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/ISymUnmanagedWriter2.cs deleted file mode 100644 index 11466dcb9..000000000 --- a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/ISymUnmanagedWriter2.cs +++ /dev/null @@ -1,103 +0,0 @@ -// -// 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 diff --git a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/ModuleMetadata.cs b/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/ModuleMetadata.cs deleted file mode 100644 index e06f12aef..000000000 --- a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/ModuleMetadata.cs +++ /dev/null @@ -1,796 +0,0 @@ -using System; -using System.Collections.Generic; -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, IntPtr 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; - - Dictionary types; - Dictionary methods; - - public ModuleMetadata (ModuleDefinition module) - { - this.module = module; - } - - bool TryGetType (uint token, out TypeDefinition type) - { - if (types == null) - InitializeMetadata (module); - - return types.TryGetValue (token, out type); - } - - bool TryGetMethod (uint token, out MethodDefinition method) - { - if (methods == null) - InitializeMetadata (module); - - return methods.TryGetValue (token, out method); - } - - void InitializeMetadata (ModuleDefinition module) - { - types = new Dictionary (); - methods = new Dictionary (); - - foreach (var type in module.GetTypes ()) { - types.Add (type.MetadataToken.ToUInt32 (), type); - InitializeMethods (type); - } - } - - void InitializeMethods (TypeDefinition type) - { - foreach (var method in type.Methods) - methods.Add (method.MetadataToken.ToUInt32 (), method); - } - - 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, IntPtr pdwTypeDefFlags) - { - TypeDefinition type; - if (!TryGetType (td, out type)) { - Marshal.WriteInt16 (szTypeDef, 0); - pchTypeDef = 1; - return 0; - } - - WriteString (type.Name, szTypeDef, cchTypeDef, out pchTypeDef); - WriteIntPtr (pdwTypeDefFlags, (uint) type.Attributes); - return type.BaseType != null ? type.BaseType.MetadataToken.ToUInt32 () : 0; - } - - static void WriteIntPtr (IntPtr ptr, uint value) - { - if (ptr == IntPtr.Zero) - return; - - Marshal.WriteInt32 (ptr, (int) value); - } - - static void WriteString (string str, IntPtr buffer, uint bufferSize, out uint chars) - { - var length = str.Length + 1 >= bufferSize ? bufferSize - 1 : (uint) str.Length; - chars = length + 1; - var offset = 0; - - for (int i = 0; i < length; i++) { - Marshal.WriteInt16 (buffer, offset, str [i]); - offset += 2; - } - - Marshal.WriteInt16 (buffer, offset, 0); - } - - 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) - { - MethodDefinition method; - if (!TryGetMethod (mb, out method)) { - Marshal.WriteInt16 (szMethod, 0); - pchMethod = 1; - pClass = 0; - return 0; - } - - pClass = method.DeclaringType.MetadataToken.ToUInt32 (); - WriteString (method.Name, szMethod, cchMethod, out pchMethod); - WriteIntPtr (pdwAttr, (uint) method.Attributes); - WriteIntPtr (pulCodeRVA, (uint) method.RVA); - - return (uint) method.ImplAttributes; - } - - 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) - { - TypeDefinition type; - if (!TryGetType (tdNestedClass, out type)) - return 0; - - return type.IsNested ? type.DeclaringType.MetadataToken.ToUInt32 () : 0; - } - - public uint GetNativeCallConvFromSig (IntPtr pvSig, uint cbSig) - { - throw new NotImplementedException (); - } - - public int IsGlobal (uint pd) - { - throw new NotImplementedException (); - } - } -} - -#endif diff --git a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/PdbHelper.cs b/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/PdbHelper.cs deleted file mode 100644 index aa6398253..000000000 --- a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/PdbHelper.cs +++ /dev/null @@ -1,206 +0,0 @@ -// -// 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_language = new Dictionary (); - static readonly Dictionary language_guid = new Dictionary (); - - 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)); - AddMapping (DocumentLanguage.FSharp, new Guid (0xab4f38c9, 0xb6e6, 0x43ba, 0xbe, 0x3b, 0x58, 0x08, 0x0b, 0x2c, 0xcc, 0xe3)); - } - - 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 diff --git a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/PdbReader.cs b/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/PdbReader.cs deleted file mode 100644 index 9d7166638..000000000 --- a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/PdbReader.cs +++ /dev/null @@ -1,278 +0,0 @@ -// -// 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 documents = new Dictionary (); - readonly Dictionary functions = new Dictionary (); - - 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 && 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 (); - } - } -} diff --git a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/PdbWriter.cs b/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/PdbWriter.cs deleted file mode 100644 index d07b69824..000000000 --- a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/PdbWriter.cs +++ /dev/null @@ -1,222 +0,0 @@ -// -// 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 documents; - - internal PdbWriter (ModuleDefinition module, SymWriter writer) - { - this.module = module; - this.writer = writer; - this.documents = new Dictionary (); - } - - 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 CollectInstructions (MethodBody body) - { - var collection = new Collection (); - 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 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 diff --git a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/SymDocumentWriter.cs b/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/SymDocumentWriter.cs deleted file mode 100644 index 34918dc63..000000000 --- a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/SymDocumentWriter.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// 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 diff --git a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/SymWriter.cs b/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/SymWriter.cs deleted file mode 100644 index 678942a34..000000000 --- a/Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/SymWriter.cs +++ /dev/null @@ -1,170 +0,0 @@ -// -// 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 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 (); - } - - 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 diff --git a/Mono.Cecil/symbols/pdb/Test/.gitignore b/Mono.Cecil/symbols/pdb/Test/.gitignore deleted file mode 100644 index 17ff3483d..000000000 --- a/Mono.Cecil/symbols/pdb/Test/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -bin -obj -*.xml -*.user diff --git a/Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Pdb.Tests.csproj b/Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Pdb.Tests.csproj deleted file mode 100644 index 7bf3ed40b..000000000 --- a/Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Pdb.Tests.csproj +++ /dev/null @@ -1,124 +0,0 @@ - - - - net_4_0_Debug - AnyCPU - 9.0.30729 - 2.0 - {29300103-CB76-4A1D-B6FD-FFD91C1EC8AA} - Library - Properties - Mono.Cecil.Pdb.Tests - Mono.Cecil.Pdb.Tests - 512 - - - true - full - false - bin\net_2_0_Debug\ - DEBUG;TRACE - prompt - 4 - v2.0 - - - pdbonly - true - bin\net_2_0_Release\ - TRACE - prompt - 4 - v2.0 - - - true - full - false - bin\net_3_5_Debug\ - DEBUG;TRACE;NET_3_5 - prompt - 4 - v3.5 - - - pdbonly - true - bin\net_3_5_Release\ - TRACE;NET_3_5 - prompt - 4 - v3.5 - - - true - full - false - bin\net_4_0_Debug\ - DEBUG;TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - pdbonly - true - bin\net_4_0_Release\ - TRACE;NET_3_5;NET_4_0 - prompt - 4 - v4.0 - - - - - - - {D68133BD-1E63-496E-9EDE-4FBDBF77B486} - Mono.Cecil - - - {A47B1F49-A81A-43E8-BE6B-DD28AF2C4055} - Mono.Cecil.Tests - - - {63E6915C-7EA4-4D76-AB28-0D7191EEA626} - Mono.Cecil.Pdb - - - - - - - - - - - - - - - - - - False - ..\..\..\Test\libs\nunit-2.5.10\nunit.core.dll - - - False - ..\..\..\Test\libs\nunit-2.5.10\nunit.core.interfaces.dll - - - False - ..\..\..\Test\libs\nunit-2.5.10\nunit.framework.dll - - - - - \ No newline at end of file diff --git a/Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Tests/Addin.cs b/Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Tests/Addin.cs deleted file mode 100644 index 080f45eb3..000000000 --- a/Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Tests/Addin.cs +++ /dev/null @@ -1,8 +0,0 @@ -using NUnit.Core.Extensibility; - -namespace Mono.Cecil.Tests { - - [NUnitAddin] - public class CecilPdbAddin : CecilTestAddin { - } -} diff --git a/Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Tests/Linq.cs b/Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Tests/Linq.cs deleted file mode 100644 index 0950ce114..000000000 --- a/Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Tests/Linq.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; - -#if !NET_3_5 && !NET_4_0 - -namespace System { - - delegate TResult Func (T t); -} - -namespace System.Runtime.CompilerServices { - - [AttributeUsage (AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)] - sealed class ExtensionAttribute : Attribute { - } -} - -namespace System.Linq { - - static class Enumerable { - - public static IEnumerable Select (this IEnumerable self, Func selector) - { - foreach (var item in self) - yield return selector (item); - } - - public static IEnumerable Where (this IEnumerable self, Func predicate) - { - foreach (var item in self) - if (predicate (item)) - yield return item; - } - - public static T First (this IEnumerable self) - { - using (var enumerator = self.GetEnumerator ()) { - if (!enumerator.MoveNext ()) - throw new InvalidOperationException (); - - return enumerator.Current; - } - } - } -} - -#endif diff --git a/Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Tests/PdbTests.cs b/Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Tests/PdbTests.cs deleted file mode 100644 index d084dcd44..000000000 --- a/Mono.Cecil/symbols/pdb/Test/Mono.Cecil.Tests/PdbTests.cs +++ /dev/null @@ -1,175 +0,0 @@ - -using System.IO; -using System.Linq; - -using Mono.Cecil.Cil; -using Mono.Cecil.Pdb; - -using NUnit.Framework; - -namespace Mono.Cecil.Tests { - - [TestFixture] - public class PdbTests : BaseTestFixture { - - [TestModule ("test.exe", SymbolReaderProvider = typeof (PdbReaderProvider), SymbolWriterProvider = typeof (PdbWriterProvider))] - public void Main (ModuleDefinition module) - { - var type = module.GetType ("Program"); - var main = type.GetMethod ("Main"); - - AssertCode (@" - .locals init (System.Int32 i, System.Int32 CS$1$0000, System.Boolean CS$4$0001) - .line 6,6:2,3 'c:\sources\cecil\symbols\Mono.Cecil.Pdb\Test\Resources\assemblies\test.cs' - IL_0000: nop - .line 7,7:8,18 'c:\sources\cecil\symbols\Mono.Cecil.Pdb\Test\Resources\assemblies\test.cs' - IL_0001: ldc.i4.0 - IL_0002: stloc.0 - .line 16707566,16707566:0,0 'c:\sources\cecil\symbols\Mono.Cecil.Pdb\Test\Resources\assemblies\test.cs' - IL_0003: br.s IL_0012 - .line 8,8:4,21 'c:\sources\cecil\symbols\Mono.Cecil.Pdb\Test\Resources\assemblies\test.cs' - IL_0005: ldarg.0 - IL_0006: ldloc.0 - IL_0007: ldelem.ref - IL_0008: call System.Void Program::Print(System.String) - IL_000d: nop - .line 7,7:36,39 'c:\sources\cecil\symbols\Mono.Cecil.Pdb\Test\Resources\assemblies\test.cs' - IL_000e: ldloc.0 - IL_000f: ldc.i4.1 - IL_0010: add - IL_0011: stloc.0 - .line 7,7:19,34 'c:\sources\cecil\symbols\Mono.Cecil.Pdb\Test\Resources\assemblies\test.cs' - IL_0012: ldloc.0 - IL_0013: ldarg.0 - IL_0014: ldlen - IL_0015: conv.i4 - IL_0016: clt - IL_0018: stloc.2 - .line 16707566,16707566:0,0 'c:\sources\cecil\symbols\Mono.Cecil.Pdb\Test\Resources\assemblies\test.cs' - IL_0019: ldloc.2 - IL_001a: brtrue.s IL_0005 - .line 10,10:3,12 'c:\sources\cecil\symbols\Mono.Cecil.Pdb\Test\Resources\assemblies\test.cs' - IL_001c: ldc.i4.0 - IL_001d: stloc.1 - IL_001e: br.s IL_0020 - .line 11,11:2,3 'c:\sources\cecil\symbols\Mono.Cecil.Pdb\Test\Resources\assemblies\test.cs' - IL_0020: ldloc.1 - IL_0021: ret -", main); - } - - [TestModule ("test.exe", SymbolReaderProvider = typeof (PdbReaderProvider), SymbolWriterProvider = typeof (PdbWriterProvider))] - public void Document (ModuleDefinition module) - { - var type = module.GetType ("Program"); - var method = type.GetMethod ("Main"); - - var sequence_point = method.Body.Instructions.Where (i => i.SequencePoint != null).First ().SequencePoint; - var document = sequence_point.Document; - - Assert.IsNotNull (document); - - Assert.AreEqual (@"c:\sources\cecil\symbols\Mono.Cecil.Pdb\Test\Resources\assemblies\test.cs", document.Url); - Assert.AreEqual (DocumentType.Text, document.Type); - Assert.AreEqual (DocumentHashAlgorithm.None, document.HashAlgorithm); - Assert.AreEqual (DocumentLanguage.CSharp, document.Language); - Assert.AreEqual (DocumentLanguageVendor.Microsoft, document.LanguageVendor); - } - - [TestModule ("VBConsApp.exe", SymbolReaderProvider = typeof (PdbReaderProvider), SymbolWriterProvider = typeof (PdbWriterProvider))] - public void BasicDocument (ModuleDefinition module) - { - var type = module.GetType ("VBConsApp.Program"); - var method = type.GetMethod ("Main"); - - var sequence_point = method.Body.Instructions.Where (i => i.SequencePoint != null).First ().SequencePoint; - var document = sequence_point.Document; - - Assert.IsNotNull (document); - - Assert.AreEqual (@"c:\tmp\VBConsApp\Program.vb", document.Url); - Assert.AreEqual (DocumentType.Text, document.Type); - Assert.AreEqual (DocumentHashAlgorithm.None, document.HashAlgorithm); - Assert.AreEqual (DocumentLanguage.Basic, document.Language); - Assert.AreEqual (DocumentLanguageVendor.Microsoft, document.LanguageVendor); - } - - [TestModule ("fsapp.exe", SymbolReaderProvider = typeof (PdbReaderProvider), SymbolWriterProvider = typeof (PdbWriterProvider))] - public void FSharpDocument (ModuleDefinition module) - { - var type = module.GetType ("Program"); - var method = type.GetMethod ("fact"); - - var sequence_point = method.Body.Instructions.Where (i => i.SequencePoint != null).First ().SequencePoint; - var document = sequence_point.Document; - - Assert.IsNotNull (document); - - Assert.AreEqual (@"c:\tmp\fsapp\Program.fs", document.Url); - Assert.AreEqual (DocumentType.Text, document.Type); - Assert.AreEqual (DocumentHashAlgorithm.None, document.HashAlgorithm); - Assert.AreEqual (DocumentLanguage.FSharp, document.Language); - Assert.AreEqual (DocumentLanguageVendor.Microsoft, document.LanguageVendor); - } - - [Test] - public void CreateMethodFromScratch () - { - var module = ModuleDefinition.CreateModule ("Pan", ModuleKind.Dll); - var type = new TypeDefinition ("Pin", "Pon", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed, module.Import (typeof (object))); - module.Types.Add (type); - - var method = new MethodDefinition ("Pang", MethodAttributes.Public | MethodAttributes.Static, module.Import (typeof (string))); - type.Methods.Add (method); - - var body = method.Body; - - body.InitLocals = true; - - var il = body.GetILProcessor (); - var temp = new VariableDefinition ("temp", module.Import (typeof (string))); - body.Variables.Add (temp); - - il.Emit (OpCodes.Nop); - il.Emit (OpCodes.Ldstr, "hello"); - il.Emit (OpCodes.Stloc, temp); - il.Emit (OpCodes.Ldloc, temp); - il.Emit (OpCodes.Ret); - - body.Instructions [0].SequencePoint = new SequencePoint (new Document (@"C:\test.cs")) { - StartLine = 0, - StartColumn = 0, - EndLine = 0, - EndColumn = 4, - }; - - var file = Path.Combine (Path.GetTempPath (), "Pan.dll"); - module.Write (file, new WriterParameters { - SymbolWriterProvider = new PdbWriterProvider (), - }); - - module = ModuleDefinition.ReadModule (file, new ReaderParameters { - SymbolReaderProvider = new PdbReaderProvider (), - }); - - method = module.GetType ("Pin.Pon").GetMethod ("Pang"); - - Assert.AreEqual ("temp", method.Body.Variables [0].Name); - } - - static void AssertCode (string expected, MethodDefinition method) - { - Assert.IsTrue (method.HasBody); - Assert.IsNotNull (method.Body); - - System.Console.WriteLine (Formatter.FormatMethodBody (method)); - - Assert.AreEqual (Normalize (expected), Normalize (Formatter.FormatMethodBody (method))); - } - - static string Normalize (string str) - { - return str.Trim ().Replace ("\r\n", "\n"); - } - } -} diff --git a/Mono.Cecil/symbols/pdb/Test/Resources/assemblies/VBConsApp.exe b/Mono.Cecil/symbols/pdb/Test/Resources/assemblies/VBConsApp.exe deleted file mode 100755 index c86b64b15104fecec5c389cc3694ee7c334a3ecc..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 15360 zcmeHOeRLdGb-!z!T4N^qhO)5ef+Lg5rb>A@jwN@z}T+HeS@6w%Prl0XQ}Ax*=VA>q)3mb7W0z)9`? z?wgO@l^qD}=^v$etGV;;efQmW-+lMp_vX!L=iBclm54N47cUY$f;*=^34b-1LUH5b z&o|P;;jb-uMC|z5lF_3X+b9&RiDD{eq*M94RWim*qgc)xnY=N$d&J0D<7Tpy)_PU_Ehn#RSQK~kyj zJyL*_0pQAVZ<6N@$Q|L_6j4t^l4`+OqI#wrCTijP8%+igdf+D=_%S4ixe3I*sj%(*)k^4yUw8Qf!3Vgg9NHa!fE zCm(+W5>#_a0pU3zI_ z<$NiVGriVF%o6*%m-h4z@*nGbh0+F<5dhxGe@a`xMLuPRkefo8W@A1_rchtA!<>VO zG#fP{Q<%3JYQ?*R3^8Di(k)!YszY%kLBY3rWvGra7Ghxv)|Npa%2=$`FtZFzpo|-` z8Y^WA#h^QMjgq3aAs=ard!;1x;dvgE^l#F+0yYY zg*XJlQ0U)VK)n+N@MWV)Vv4D`>j2AN-1rc>Q>5ha;cI zl>HLsW529Yn`Z*iDiFOk*bdB(A>vNMUmUm6Fa}MYQ`;-J&$2S}@;VIpQZ~X>#3_dT z+ga^kU4lZGZyJrVY~~C2W85Do!|UOb(`jfQ8jQQrDA4K4h&#zCL7i;U+nT zB^8nq4Iyh4sMcyO(!!1%B+oMNC>^TWsm@7=x$$T;+HpX6|7Yhu7Z1#d2I7rzJ#m#1 z)jt{!sSJZrEgG`cuoz}t5RL}h*1GMnr>{dE_Nk);kCi_6nYbR+qmA)cG}iqHxdXse zdp`v`Y86E~Zq=;ysEmfgbE4t+taw9WOp7*HJuE#EjZ}4@9vJs3UKg!%C9pCH=vMFO z2K%sXb&hWFXuMW8_yc5bv;qe6Xr#qX)g1s z(s3g}r(HPK!b@uhW$ii{i`6>BVx9*IT?rY8k%+JGO|7{Ncmx8BA_lzh6lhNTw>E-q zZvvYp3HIgc4}V6e@55*4C>*lWQxl zJuC+?9r`dst$fV0C~=I#bYvr-t{2|rdInqY{0C1Ti(Jsw&aA<mmr4eBFyUa| zc^5P+QNg*9L^RPziZb^($^WdgPHi69zF82AfW&Lw3Ep_D?pocAfyRWQEZ~Qr;?i4? z0Ye|>M@q#^e!^ysJ}A?H`_gMiD2qHlS1jFn?eHM(?_wOIyL5Bb8UxM=i<#Iz`xD_X z0x$h?`D%6oZk@-N+h@C=JG27VE?n2)LO*!@mgOuTYmcmh&>-)KBXY0CJVf1fPH!UA zC4wSC$HYz%q?<(v`KLh%(lts6@CD^73hbf20@xwp^%9;04ARHduK>QLzNiMV<;ZD4 z`n2{@Ek@0Oi-30pZVbfeehHrrJQ@hne+FIxd`s}9K!mOft_nuzcrcC#eSh#wFi77D zJ_`7YAh)|P#G0%N#nGoi=$cTFPJ!<)k~dT00|G&~(<9X=RlX@4x?Gobthy#z-_>ym$dglnyjY!0Jtgj*kz z`BM^pM8bz8d|bjGNjR_W0$kUzHbck4?X(^q;$efp!oYZhn`k$%24E@$z|5oA0A5{U z6D|f9K-s$`XArKc0{f6GgOz02XXuNl7bZi>dK<#G>=wE#{(Zhs5Ig8L)`aaC(H7+f*@sj6(FPi)~jw zk1-iVpkvNe>fgfdB^TSSejR(a(+);Q)n{S%b1rtfdLDa`XI<=m^+l}WJqUBW65Ox; z0&(?0AFC4!X%7bhQlaM#v4jc^M%%S_h-LIK7dxbliRE-&VsZTm%@S8o8#YAP_2}Qz zO2GPD?8n+9upJU}#%~3UOU$v^3Mxo!j=nK)msmk}xb^l(>}(C^gAOMh3CxAZJ>_D@ z0v|>_cFqBX;k&BfY?UbtvDdH456#G{Z>W@Od2*cm$E2KTNq-7ZrRM-O`r&U#*EQC2 zrW`?Umvl#(qklONCY~X;0e(z;0Ps)6J(3cY@Lma*N!TIb8VNVLboR^+Vz@@ajS@Z} zOCOT(bAT7cm*}P7c4a>CT$xWiN7|__v>z0n6W^c}p$X(!lYay}r3}h>{(aH6?;Ed%)ptzX<2 zey=u(e4K{GUE#TOjrfDG8n{mKrvMuQ#{ruIlag{9;6-sp!VgGzkA(M1_<)2DN%%Pl zza*i7==!*5C)h|yQd+qH_znpZN+OV?5#=7hV-niRCy`&E%m-Ymv;wYHwgX<9c7 zaoqt~_if5;fj(Ld$$f|bpAZ8sTtE+rVYC%h4$F4acsPDYq-ALabPbV>Yu!#aOUR|S z)9uKgLFsbktSr5kehkXJ^gQ5w^aSGJeNw`-EPYJoACvlg1v`Mp#d%48UbgtWEPY-| zcu|&;U=2xdyQ*MosDkCIk{%W;!H}hfq%4&@OQF}}VyWa@Dp=d4SQGlRcJSP$^-2Cd z$v*)4N3;P+ACUaRGJja|9F{z3DJ?Ba(^6VmwlXDo&WQKXE81C^pLQYZd|u{Bk@_pF zzv1LnrWg|TNqAVoDGAR?I4$9Mhput2&r3*wxbnF8vG`Z=#JGo7 zg`ZHL7Q92~Qf>hJg2H=%h_+B*_o%Iqa5dm98b9LwhjtopTj2KquLo2R<5a}L0DcPE z2myxBjzY804nKqQE+h`9;5l^`$6!DOD^3*oxqy7869-&^5<#ti3N1$opUKRpGJbc^ z*Tpm9JK_cLBSll2)d}@a)E}tY6i3SH^coO^Nk0kR?;|_r&_*Ouu{yVm89@m zzUy`73LZP0*b0eAsl8vXXMRexmHByVdLHK6O8RT20dv zSQ(Hu?zG0sS@SCL&LC-LCS9~_>qsfNFJqTe+07|Clct@M{e=P!9#bV8Ptv~416JM! zCAo7FMFUo@P%fE8WcL)Ucbe%Ea{JA(5wmzAg9A?*JzB(3=Sb>^xqFO@!F3{oqtCZs@ z$0=t?KBH8!XcN*)lY|VvoT*g4e3z3|9rioI-L|r3RT0c%QZik#(EH0-E;(pAHt>z) zoY0bE2~?GJC(P0zpCjjIYt2Q>Rn<1-7@NU!tqmJ8qs-*wZ3YXMRu50^P|a}7;I3}4 zy4KKfc!y0EZ8b~VQufgSyw{@9$%4rQc^|c$M@1UI@R!U(hlcZZDV0wnhm)y{i_l=k zE?9PLF{=nMUIp~j^`R0xFugC8Ez4&7a`)JKz{+OfU+_^oxz)^@MY!(pP`;cqi>a}! z34e1L;cm$tnf!4&FqAcOX1*j%=E!xti)^Ui5KhSE4zNo)L*TijQ=DfybNjC9&=2^y zYk&$aWl8sTi!OC{%G&^(+a3l@4-cvM>WKLqDx%e)dQl5?&p|N**-LA4v zwOz<0M`d3_2hAOt*?><$6S+fGjbK(`rrW+bO_-IZ8WSCd@^q+7UoW>al}}B;Ym4s0 z2JSI$#o0kBo4Lt}JMP<%;rtQHXLf0FU}g$rFY?NHfV{kS_q`^6Br{PiI*nBMyB9{} zBp)}Ar0_PzcR3b5=+MZ!GtH|+er9JXlcy~yp6HoWmi*4~gtzi=J_KPiOGD!saBMDG zH`?s1{#eW`7{MGcJp=Kq8?o#mxc9pX%f#vWgx`y)|pk>sFhXD0H* z3j^MG-DnlZFR8KDdA;TL-`Bt`a26GtW0K>Bj%T~29HzEG)2tt~wiKWF*m@m zrtE+Nq_C)a;9pUdaR>Gyz9=TipMI9UeSP6m@H-{j#dq` zSA+#*yqvyFfmAGi8I=$+(#1@Hw*Z&6G@2<@$5n6a+z{gS1U914R1rS31=~auQKw4h zis8+ZCic%O_TfF^05(B+vhilLfM1gKVm;-JQJIRAmU-T4KhgEH`klLfw&l^cJh*%P zOE>H${j)b6+&6#C`7`>ts}J28{bpo?YLMU)8*KYy^`YSG*gO%dXGC`qKA(w2T_nm# zvx_uqI_fac8AKU0Ylcu-AXL{3ip@r*QCUQxCLtE#4NRy@2+_2N9~e;_Clx2wS{pJr z#%-J(n=fJuBlrx-$u;6>$|c5@)Z?tyA;*?9;*qN{wlKCt2a)egh%JvTY0;f~tbG<~ zEejhL#@c7cIz?=GOO&)&cNHPl&6I`Jl!am4)1gkUG#o;n+faiG8?_)La_3oQqoInb z`ay$LS%~hpw5Y+@T3o$sthEe!acC`o!$4~p^rDnsKmq_mPUw2T5F$FHdxzTrLlKRQ z^YBEsb8^(o6)Mn)dfk&}r-n=G7Vdq^WU3d{1Mlt4t z2u37V9j1pYr&zZd5iKFf(9)tsl$I9OquX(Pv_`Sz0ldtU){V6@z65uZ4ut#%C|Kb1syIkbua$7 z{kH1_y=~?$Z=_Tn&sa%khYFu?AFrMLnOXD+BM6>Zla~c|-(nT3=85aLUTr?|5CT&I zJ;$Jm=+tM}HFW3|lHP%gbKEF@Nnb{`vvKSk=|t zjgLuIO$2w8!j^AHeJQ%6ydm_ICRpKj~VhD$261US$=nmFItzA(I<0n zg4efz_wB6$mLXg%hjHP>_TG`fk$?H+-#@nJsZVZy@3{wG&=364A$HC5hJ&SC;h^s& z2l0%3@MO=rgL0cyp(hLDV_<(X{hzS_pC{uinrI5&pwS-O`J02IxZ@)Xnv#FW_=&%c zBl-yFT<_c^^~boQh3uS5U&W$0k%rGG|p2*&Hsu{zC24gqV&jN}mZ;MR1S z=%2V#Zumld_7U2M(|zId56ZoMTFNQZ zv~%fG0{a-&UBB)=)Ggwvp`u$io+P^bi`!}hKliRAdGqK?7WPX~4mex*(kBsLAfaZ_#aDCB#`)YOiGA2WH>idmHvql{t({Q(`|Gi6v z{7`k9?B~3;8Mr(@pGN-jX^Nej9oxA9BKsTpdB}BF*J@jLOJ#ok-@b2ihHvW*XIQp= z*%3SqEo%}_wW%7)8$bllQRiao;4QJyB(20NBfiUOaxh*OdEMvq@}pnec=gF#);Qt* z6GtnaNm>n@6qfjfsLoKIQZYxI%(RiS6|f-*_d(<4Gjp$+nZX; z#ry_4eH15Vc4y9euh^NkavM^1E_tH6)ySptnIooM@*YNHYY=4^zOZ4O+?Q~0SECU> zC$$=RJd$i`t$C}POce^PD;)`?V%f%?eItNj<4SLYfH>p*Cj2e2K%et%@p*i%|7QCCXMz6$ D!qQIG diff --git a/Mono.Cecil/symbols/pdb/Test/Resources/assemblies/VBConsApp.pdb b/Mono.Cecil/symbols/pdb/Test/Resources/assemblies/VBConsApp.pdb deleted file mode 100755 index 2625666b403116250b8bb376b283adb797685eb9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 36352 zcmeI53v`v$mB+u!<4O>eAmOFxMT7DTHz7bktbrs53W|crRA$H}xj-}|F}b{|POnpH z(Xr#B?W(qQs`jC68O0gw(3Y;!scQyjv}GK-mUXpjXcz6+F07BTTH9JXzyEoB_q#VY zG1JniKo0D?zjMys`|PvNKKq>SeBZrU-qO_B-qpS#lc<|nH*H#C`O3wKxfRLe@S)@D zR|cd3=6`S*mzkIff}p{o{?C)Z0tbHIpH5{9)HomR_k&Z@3r_#{%9!zi5jcW?G$Hu? z?+1YgW|iwtC$j|xp3I%=@7p_C;G-3lvAtJ*@k(v&Uir=Q-&%3#vCHq=v-`-9HJ@GQ znN{bue!i$5pClG27XP&pM&rNo>TV%ENlb7`cVpk7k@H*s9>4qyF z_~}ocFTLl|;J{U%8SwDw58nRX(hdJr`t_+n@aB-EUvK<;TkUt6|7O{jUt9FTZJm!k z;I<6GsPD&@zt!~G8^d1y<)PPqwePM|+NdW`=a1L;&wT8g114Af;KuW=8aVE(OzUYU zkO@v{Rgc&Bw`VS>eWdM~UthB;{;fO4?O$<98}$V0{P7z9XCGd4>-tMio4T~*>W>{8 zJ8|O)WP(##)#Ek(&;Pph7hgL2hd&zm_Tnqiw~8( zZ_*>zPx-~mCy)tFX;qKc`0v}_Jm&11zxK=%-){TYH~#h$+fHeto@&TzDk6VR3KEc%QSN9LJz}v6B{i@D(U*b7`P&v1`vUs<&4?0s^?Ks(^Q$9TUoJnecvdnMA_Gy{*0T#_6k}W;`$1T3wNxPAeN)TGN-*wYH?&G8GG*Z5L)Toh|FPWH6ldkS%#_ zFvQJjqt&#LF>SP^GaJG-wnp1PThm69Z6oE{NaeLL9_QWZiIdL$Q8Kod9(?J!Tc23)v1enhGkxyB5Gc<8 z#5cFhvdOBGxs>eNj(zxvHC)TuvY6`9mdt#L&(lu+%$MS#RhejoqqG`1PrL2B!PRxE32yUFSimZR7BJi5B})>c*@f>alE=l4`saao$>sHF*-k$E(>jdN|; za{u~V#p;%>EveQ;sV>7(&}My0YGYe_SEi*&ZRX2UJe3`-tuAr(p&2Wd@1Tg+@ZtvE z;Cg`yNHP9-`|CM=(v$|ljX{vrc(j6tfH#9nf^orcpoEt^j!~v^(J1LU0aOG1>D017 zvH3qbVuA~p|DPG`e5Inv1c2!L7p<@FpZ|aQ`9H_S>Lh_#>2!e^J--kcVR{5h)&_{8Js3UxTw`7@iCP=}}}@6%Oo zUhRzdn8Yiw#>Vdhn<|)B?dS+~7(!tdkWYG=LLK~^;-Pp{2P3Ai{UL5%NA19TjX&bs zU)8>nyQeliV3Q4Y(e@yCMDJ+|+xIqLEW`FAV#2YQ?`&|u>5xFCPsooyPR7`vt}~s= zq}Q!m+SZjxwKZ{NbQuQUejovzr!CawLN^|aZKz8TaqPKm_VEN~-O;r$6zDlVq|EI7-!ZQ z#iPfaj09Lod)roX#kG@B0@fP%^H<+C`V1vMmi+19ao}O#3E<)2bHQhThXw0sYdYEu z2+D#BxGv*gIe1LizQ)7)PVw=;p-mq~f@P<(z{B}wO)2uU&iU~;OkGcV`!P<&Sg`sw z&d8X6-On*Hj!~v^V{b5FIM@Rm1P%j?qqz^B4naMz7SQ*4?gz9#cmX&H(9QmI3Robz z{x`b*o)_si^C14;5XmKiNURdyT0peEJ`$^DRnE%Yv-)-AHE5MIr+nf%{VM4Lo^;^+81v=eaE zdL36=T{OS;!KZoU=?Zo6>pgqmP?t1aQUiWni`Er1V`wz}ax^`!eTo^4fE|OF84t4N z&}Nk`NR2N3D&8qJq{!=(ay?jk_a?C79d;%jy~tP(K=Eo|GN3qL7RDxP|5!MN(HOk} zewmcLN%kD@CL`~!k+BUKl&jTx7j}PxDrop46_&*k->;9-7 zXa;Tp?gvih#MI+{%bx%3avjy$=+lL`($juE=$_I)kbppQQ~VlJ@p!uEe9%3m-+!JR znGX>$;Xcl_ z{9fr|i_B+&@n01kfB(>Hd8#e7G2JO5?+3N;i`Uc35Bkr8|M>G@onJ@KgDdplm*7#~aM558q=4iUFCmKWMRiG zUI(6$uJgF|li(-rFA+fkg_4p={rh4aO&SJVXDmDo5n*~BM%uQ7u1DdeYu z0ke)x0}~>-vk0>Dz%#)1?5n}7UE_i;vTj{u)~&+(1Z%6}aZ+b!8n?M%^$8O?x%N!W z$6DLhSZJ&0dX7Fu#(eN;$Y5?GL-%dEf6T>NJy%o0M}i~RaR@>Zzyd(`Ez$D9TFJpgk&oWD^~eqWrc z?;fN4{PSlkBb?t2l_D-N$KonCRgwFZz0`AGZ_ZYHeW8wCzUD?FVEYm?{UV#Ur@q$R zhpz@}FRlIQNU-wS`(6hw2d@E_GFQr&J=#|<2(IILCPo+=?y0Rl#h>N<75wVUI-`_U-s|~rbiLR3dEfNs)Q=HomFg@qpZH(A+>e#!>grVM7FJo!(LI!Z79P=inu!0K z`*nZcIxI3rod~msSChFqclOzt-cY_QY4#ywBc{yJ>GHJfinBg?(3if}J_#<5Tzkss9D_ z-THSJqAYD`FSEnx)sX`>w*r*7WdQcc6i0-X$x)P#~l5fExPwpV_s0-t)DN@R))6l-(VmN>YpF; z9B=Ra92SR(q&37R&Sv7XoV=dKJWIPn;1!>zE$pWsbJm6)$K1yk?}OW&KI)TCoJYkQ zygohHeFS_NKzyFIP@lrKrfYLaik>^NmyBQS+p-Uc!ci8j#`qT6nGCP^JZ)iHzVCEA z?0ca&(P+$aG{z6|#@Xw<$eoqE>~z*z?-TbX@s50*uk`OWMU|KCN%)Td;`cm-x{r2q zm9Y(VPeEVd^o^F=J{4^)jG0pAYJq=l$`!yzbYeH@9z1cNfO}rgT3ly^$e) z&r_(obd+4;a;SSRV#D<#N8f!6jNRA-jiv2{$ky4MpKHQ7Uf!2;=dI$|4bLceyvYKl^l{T!dyW6bmk{Us)PLGPh79q0o}T(ojPFzb z6~kFe*i(CY7sFeswJkAgnbx18^_BMgM0@6f`nIew zj?HP<3|}pa#9IJo6u~zfpWYA9(i7!t+S1v{i1 zKE^m?^$b#aT?%G@hCUNryI!9O=yX=7kJm*uvU~DaxUY}eh<5UH!47%45NESmztr|b zFwg6<=ev9z7`?KWfuSj4quEZ!;x@AT<5;-Imd|?|C6E`j5pCz`g$`!SE&$6mRuws?QL^hj6UURS-tTkyiSkF~;7CSij2=dQ! z;~*a$4%9M-N{z3sg3j&(V`fiCmO9o+U65*!p}y-(R0oq5dfD)RJcoXzrLXR=LJ_5qa#Wxt_(2K|Pp0 zn`d&ezvz%kejA8sn8$0er-r)f@o^9egx)y zVvz6a)#Md}&@+pjf|cM#Fyoa?fv*Lx2d@Ti0AB|#306k>@}KDG`|^b8OIh$zQQdV` zZudp8aF5l1OqD5RkS!nB0+#PeM~&lF@?%|I{5;D0{m(6H7>sZ{4n`C@FU=Q@aMq#&d}$< z+Aq~aO`K2soinJRK;+x~UIRuA=J_130@wuX0v-Ym0*3*eza)SqKqIgVI8hSa3(x-#;6qAd zEHa;yxxf1keKb|e`3fkd+AoVw?@x)=*Xv%c|NQ@tKmV5b?biq;Pre1I@V3+FR{?iP%qr)FfFr^M_KkXF!R>zcS^uzvu(ZatQ6G)e~Z^s7V5z_-Te;@h*r8B1$RIoK2O_|E=;RXm#8Rj z6F+B<710G(iEEyOy68LjPKWIjzUFlBG=)0oyaw`su?ux@BD&ck>taUK7R>jp% zU3&e>bm!IG*hVPq}{3M{HJ+k`uJ}~p&?3L|% zH}*Y3FQcBio@9K`$++Fg_z>92m`7~Lz0YsQskk2ZI2rdk8TW-U=I6<*fDhr6qr1b=r72VS7FYjW$M>+S zPdPl%;U5x!MPK6RUUB%F4v#}W)xYB8O?2{8PLBpxKEvVXoZOhxtHk9maq?bwS%1kLMh|)#>r1Yxk#)?`lWC)aAeH>L2v&IsV&Reaz**=jzig z&%Leb_m5qEoU32z@b6r|mOHvToW9Taywk&;i3Pz^j{ad+{-l%pJ4gSFEB~>hyVcdV zxbhiJ-v=Ci((z67?Yi=7UH*rzzRdMs<1v6>1S*=|sa|~NdE8S?l!@Kx<_qpgp_x z^E(07NS);b2Y_b*o$ctI(*&UJvFYqa=QJw-oxf;*cNcI!@L6CFpnKJWzze`(;3%Ly z%pkfm0yqbl3{(TPz%pPBp!*}8%WAK)3wQ|F4eSG+1`Yw=2VMq_0ors81I7a7fZj#c zd$2mg)A?Q_&W3S z`vTbLU`nJcIftKQNhYhbFU-*n@iz-ta&5@Z1_toBFMNA?TkhynIr?3O zKKIRPPjAZ|{d&bOYo}rO%fP_Cxsmr}YIOCymd5cm<#^?L1B2pUX!g98#_=}i#!}xi z9_YW!M_c{r)U`kYKhm5jmi*pO0e%Q{xVM2~v?pmrUj07QQW8Z~2ng!>`YK4WE5M-_zPMOIt}_JgsC5E;6Qr{g~1R zzs_p?9c=XR?-|>*->qr)S?*`vsa;Fscq4wKcU<48T}$J5=jO&&@2n1XYksITm48amkZt8()*&GultLcIets$_}R;Ne!a6fxR)0cefyTq@w2z_{Can>FZ`Cy@vo2Y zb9mP$enaQ@+3!Ssc4%N9KzUu|$3y*G#a7;D^;~0Ukb6qu>20}{T@~5qNzQ;C_NxP& z{A6Um+HC0a5379}w$8SZ#8>^i*4gm@GmoOD!MSm>^^PyH&)rU6ET28W_3hYlM{l0f z*gd80X)Jy8q&3%$t#^F*rPlauC6zJQh;_l8X9w+D^+weKj51w7`D9hPG#Wh4T>t!l zD?*07k}O^Mye%DJ?!R=s3XrISTMkK#N#S!Ye&>+?;j#Uk%IeC7hFNu<&dV&`#<*Z7 zaYw0x2Gqvk*WT|+csFB_`|)Ah1`Cw=J%^gAhQ-Oc*^3Qd@A5|m`-oFYlaVUUFK{UHWQqUERFus@aRIBFOGtm$IPR zjqg~e%f8wk#@BBhx+34guCH!bSXV!Lp*lnAy)AxO!+B;FTJ?KKPxf8DBi!69o?D%) zshnF6xk4o7{bhsU}4?7s_MEb9R-`zds}0JR@WcJF!krL zqWwXMA^~vbrX`hR=2i>tv`AfKp+d zY|>L*b1!un>P7-euFK|H@^1%*nOyg}`zZJA74kjO3*Y0^B><&DzHd|3lP-s;^Y$#{ z`x$i?0!q&1&9(Y4f)CGESf_V{eI3g}n8a7kN1ZDvtke6q3wx-0jJl;g)X6ax^-!mG zM19{2+tWF>ABVy^z0-MK4>EPecTNv=cTp#wQ7V*qn7U22s#~4T{QP$%3i17ty={H<_UGyeee0pEVzhmUvm0;EBJ(Pqpq-fm$W&pp(Mv4(%ZA8-F zs?fQFk}ne;YCKhMY7Asd26JzD8t028aCZM^xpSZIl6whQ5+4HVm7MV z=QtMlG;>}1ifL|>x0=1nUItPNtP5IBd?*E7$flx<>vb42_s^m^WzAfLqx zYN6ApQ)KpcbznJ-p8s9~=sOmd0=2+GK>KDnmiBvc8aa%dOKQq#CA%j4c-*D`#kkqdo1n262L^@eBc709GC=L2wViHkJ<}N1*QShff+yr zFcU}uy3woxI3_apCAxW%Jvn00_kZ-g9ermf+@Epzu1NLo3N8AT=(j+>1^yfs_+Pq# BmInX; diff --git a/Mono.Cecil/symbols/pdb/Test/Resources/assemblies/fsapp.exe b/Mono.Cecil/symbols/pdb/Test/Resources/assemblies/fsapp.exe deleted file mode 100755 index 7cdd2368ec004dabe05dbacfaa4b81c430f179c5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5120 zcmeHKU2GiH6+U-%y;-kgi`0P-XvKJKSAmeRgCmr>cC!8j7u!j*4ivO1nVr3MCd|$( zGj|=Eht#M=Ri!>q6;-O}LsWq(p+4|X30e?TedtRYRjS$tp2#z8)h8a>m-IV#X7uPD(>Gn;T)a>=>p@LggM)>!#Pr1_qE(ThpE~cXr?cIr zAu%BGM2Ep)#{f4T1v1e}XpBsJjFvc6Bif7kz=*5VM|7Y5Z+{b#6#x&wuH;UM=xNy7 z2UlV@egM6%?i1dHVG<#N7UV%c-J*yrC3h6)69pj1bgVt|gMGycqtJm^`&L4S^D%_h z0VQ~Eh0+V4$SI>MXl&~%XdO@@n(rWW_Y&t7z`hyOM{k%&A+p9b0Ta2SU&oh;1H$lR zA3c=n8cPCQ_T;2->@mYQ_WTJjaxXkaG(4H1!Bp>I%|3yA6(FMd^0(#%@z6M)?K9S- zH8nYP`WwvYBMPLLorLm@Pm(BpE{@PRd^!$%l16}kMyG+_ zp*i3W>D$16qUSZXsb>5QIw$E5z*F=W;BNw3G=O!sFykcf!}JSUpiz34vU}8q-*fj9 zG+vDq1S~Uj@(Oeuam2u#0kjfQ%l+|~&3H4i8x2eDNLnsmwZlf)-STbK4CSJ&Y)eZM z$%Te;>+UPIas$6ZII|Yinw~sI<=sfhI$fw@GrU%vxXCSjMR*uLt2vk3TEJ2s6)e%gCs z@s#vshyk^>AF<~$To3%qkqmil+d_6P@FYDKx=OCPzNEVC`Xya^d^g=1U;XE=mNMVh z_f-D9S1QjQKXdy>`FGF1_`M^4FHGmmjL7Hn_X)kl^eBz8rVv9?(4z;g4?!D4M_bFY z=td3C-d#swJ;El;mc%?`#sy_2_0@-|j@+NeQKYw0mf(=)eGNQ5vT#`CV$L`?F=R{< zStg(^@;K+YKaHJd&_HJu_UTOkrJ=ZY%$csJdZVJ*m1JjN2hyRW-@h@P^s-zc{jK88 z#b&cy+!@zb!gm&?E4(04oJrnp)$>6RV5J$xbdR-6?M|POcCwAwl-8KLZ_%FH8KY|`2h|gmTX)k{F zGNiSlD}+PCb@rOuHGdCb&`1xbixj=lcS#YcejW8NQ!-5@XZT$5Dq`6c?wj1(59#Zv zTk;}mdud0mp_JpRMM|sY@vEg5?u?UJ(#-Vz%gZ;5b`!JS#5H)SyjVW;@lQj8&&Cs8YoU5{KN2luPE9sOI)TiyJZf&0~nswWEH)W*K zhnJoWrcASCY^8?Rm#cQWJi-qPc;(}Ioh`2I;@F=>#Akh=(%53L51}F|g*wJWgEk3Ce1VIsT)0wH zP{f70)4dDv(S;kOEByxwf(nWvqMOF=o4L1*B`S*6Hn}G~bMBmb=FGk4+;bmi+7*wa zlbK{JYleg2=4P|2x7}PHuqOo<@1BA=fET9Ly=LrGhpqNIDLJNGLKTndDYi;>&i1_Y-+x?m>khVGkh z-&}jxe)6k&mUTo8rDuU+^FPu2}-W6%8$nuPe`?RZdr7AlV(FO%I=v^;vPdpZ1m_&wM5 zRWwCpV_$Y4)fdaysZ`&tbn!^E%vBRC+M{A|q{*(4Ro zyoFDvNh(Clj%0D;0qY~^W>x?U{M0jye#_ws0o^$t%2PpSfI?Ajs_=^%;R7xdpTP41 z)wp5V1gdtRsNo-5pqT&ZGX;q4Y4ok*qX9df*f#3_2JqcF10HpOa`R;w{>&La@N*|* z4oEpo{+|VSrmL?EelXF5*>JWEN*{Jfx>nM~lCth^fmuY+-_&13{kXDneO?cFysbcu2^2cv({OJ z(D$+);Vu@1vK}F2ox{eYuo<@`8ngvU)&eF1pRrvG)ZTzW;DsF5=2BXpi}iU7ujJ#O zK0a9)a?btLLY%7+$rCYVvz>vZ+(=H9HG&K^&NlZT=WPBLpt zph3N8{f5x$khP{2!Yl6uKB)1m&aX-bDeK5DJll{@@Zjfj9yUh4i!gV}I3dukic*%^ z_*3wsRGZ4jN!3c+RY;}zyw_3gmPhOVu=KOwuL&x|8nX#EJO?c^)@@ f_#V2P|7OBmkcNq2f!PzI8M+nP0@?!q!2;g^>7@u# diff --git a/Mono.Cecil/symbols/pdb/Test/Resources/assemblies/test.exe b/Mono.Cecil/symbols/pdb/Test/Resources/assemblies/test.exe deleted file mode 100644 index 1f45491b739e7580fe39e0a14636247bab29bcb9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4096 zcmeHJ-EUMy6hC*nElZ(I2~r>`3|lm{*xRMlK*%m^zraFEn{Fw@tkAo6r`xOdW4Uv; z?ixcHBZ|=&eDKBaz=O|36BCIa(SLx%e?UV*LZUwKq6sk({LS3E-E9PcM;?F68#vDoXui^Xd~>4Jw(qm z`yZyWRp=@*0sG~qF?ztO0qmlj6Md@I2sbQ6jA%jkg>S-A*s@TX)&!QKEYRydw><<( zth9h8b9JIMQI=?=$y90<^-Gf2V$@2P7||V!)nKE^*&d5Fr(%@E2#noC-R*liVr`%H zB3~P|Z9U!I7W>G$8{e4d|D}7w9$MG;JjHsk0PWPbBi7prrEes6Y(!JDhqWvZ>M8xD z)c(Q!5=JZ8;0(!o&J%qIc?Wh+F7Pe4BxJ-pm`fg+o|8HH5IT0BdXAo)7=yeFJ1^}K z+bcjyf=fHPB}VI|@u#+ry2ILK;pkJ}hLixObWEwxNhyJcvW@o8Zq)cH9it6&4n1vj zg;v0SQ2Zu(C56#peOurYnqji{V;WQ$&qvmNppVf-WxcyCLt7#Qqlne8W1A>L z+i4g0PI>`+3+<)fFlN2dbs*^@9kc8Mf11+35MRO2HS{wqSznzrM6ObL$}3iEeux4t z0-aYm&4k}JIl}aO+bU45CIarzbm28_1~g?@E@CVL>ptZh zZ(iv^-o zctBO%C#24l`VW?EiVHi>j(Yxhm8-2+$AWXcXv^;uFUoVovPyfx{tGJ*Q}-pqE4mGE z4}`C26Y%innt6bK={|lrc%>;rsD|hL5{xTZqO?5l5#1Oe`ZerUo^)&oavpE=S@3b1 zg*HLcbOQDS_z~!mzKh?!TfbkGBVvam8Ha32tGr{%H%|un$YbGc;mGOIB6+GG_a)>U zdJT95`V9&Y=fMi;^Y~>X)qp8Llm&n3KAEa2CPnqXAu2#8dJ#9Twi-W%*#*9PnWwyF z9){Qy?vY09JYs!BH?X8|$2S_$5MBXIRTHRK7uapAmq89}LVh_Lu4%}s@(}eZJd?0W zDtZ)^mZ_!?m1qgkL=sC{<(`iGvTB*TzJk(v@Ek*`jv0*gs7Mvm8(?48R@10M)+EoN ztbG`G1tJ}+o()v&q2n-=Zh!NA`f$~;*)sP9?%PaqubxUW?wVc^4^1X{a_&g~fg}@w z;T8?sb9p9N<05(ZP)B<@x+!Z630#p$R($uMFqgPvh6%kCh zi{2yR8BD5im|JkOf)}n9+3@)MTm?9J5wG^56+DEAmB~rns!jyu)0i~BiN?ttqn_ZB{y#C zTb!ak$sSZ3C@6wH$V5yJ#YO1<-Zs%_0fmcGE+7F|z z4r*vP+uGD}sr|*l53-MsY@dDdcjsI3h%Qv02bNp^xgVCV|17iTf2GyujrG@~>tm00 z&uqNrKO2|n!|!Eop-#f=+1L4OHUq5(cZm#c_H#WR{@~xA9Sheo+PVqp8ZKy-<6uVtJ|D6XG=NIR> zx4%X)sfQD$@k~CYn~9X3N@o)0RCdhBn2DH?GeS{Tg@(t+5=V8jkT{|{ZIh;{XU8&W zd{zJ_lrk%b%2Je)9(o$0_(39HNfdXYLEsQA1khUd)T&&u0*|)uBU%x1j!!O}FMW1J zyWMjh+apD&qT+nZNbLnu_Jyu9$Bx;2CyF}CF02g?aCU`cpI=#H2XI%JX{f4YQL$pl zbPn&WQsd`$Ujd!Acxk& zeG^c_pY@H^|8Xh-_$;EHu(6hXRIK5AI)^0q-_oI#N|p|(rHZ47_yN!cP!HC|I$Z3VrVrTEi8qS3hMwh{1eUK>wYMd|f*hB%x*p)#b{8Fqzn%KI;d7Brc_h`VvW -// -// 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"; - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/ControlFlow.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/ControlFlow.cs deleted file mode 100644 index 2d3895b1e..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/ControlFlow.cs +++ /dev/null @@ -1,803 +0,0 @@ -// 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 -{ - /// - /// Represents a node in the control flow graph of a C# method. - /// - public class ControlFlowNode - { - public readonly Statement PreviousStatement; - public readonly Statement NextStatement; - - public readonly ControlFlowNodeType Type; - - public readonly List Outgoing = new List(); - public readonly List Incoming = new List(); - - 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 - { - /// - /// Unknown node type - /// - None, - /// - /// Node in front of a statement - /// - StartNode, - /// - /// Node between two statements - /// - BetweenStatements, - /// - /// Node at the end of a statement list - /// - EndNode, - /// - /// Node representing the position before evaluating the condition of a loop. - /// - LoopCondition - } - - public class ControlFlowEdge - { - public readonly ControlFlowNode From; - public readonly ControlFlowNode To; - public readonly ControlFlowEdgeType Type; - - List 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(); - jumpOutOfTryFinally.Add(tryFinally); - } - - /// - /// Gets whether this control flow edge is leaving any try-finally statements. - /// - public bool IsLeavingTryFinally { - get { return jumpOutOfTryFinally != null; } - } - - /// - /// Gets the try-finally statements that this control flow edge is leaving. - /// - public IEnumerable TryFinallyStatements { - get { return jumpOutOfTryFinally ?? Enumerable.Empty(); } - } - } - - public enum ControlFlowEdgeType - { - /// - /// Regular control flow. - /// - Normal, - /// - /// Conditional control flow (edge taken if condition is true) - /// - ConditionTrue, - /// - /// Conditional control flow (edge taken if condition is false) - /// - ConditionFalse, - /// - /// A jump statement (goto, goto case, break or continue) - /// - Jump - } - - /// - /// Constructs the control flow graph for C# statements. - /// - 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 resolver; - List nodes; - Dictionary labels; - List gotoStatements; - CancellationToken cancellationToken; - - public IList 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 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 BuildControlFlowGraph(Statement statement, Func resolver, CSharpTypeResolveContext typeResolveContext, CancellationToken cancellationToken) - { - NodeCreationVisitor nodeCreationVisitor = new NodeCreationVisitor(); - nodeCreationVisitor.builder = this; - try { - this.nodes = new List(); - this.labels = new Dictionary(); - this.gotoStatements = new List(); - 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 targetParentTryCatch = new HashSet(targetStatement.Ancestors.OfType()); - 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 - /// - /// Gets/Sets whether to handle only primitive expressions as constants (no complex expressions like "a + b"). - /// - public bool EvaluateOnlyPrimitiveConstants { get; set; } - - /// - /// Evaluates an expression. - /// - /// The constant value of the expression; or null if the expression is not a constant. - ResolveResult EvaluateConstant(Expression expr) - { - if (expr.IsNull) - return null; - if (EvaluateOnlyPrimitiveConstants) { - if (!(expr is PrimitiveExpression || expr is NullReferenceExpression)) - return null; - } - return resolver(expr, cancellationToken); - } - - /// - /// Evaluates an expression. - /// - /// The value of the constant boolean expression; or null if the value is not a constant boolean expression. - 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 - { - // '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 breakTargets = new Stack(); - Stack continueTargets = new Stack(); - List gotoCaseOrDefault = new List(); - - 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; - } - - /// - /// Creates an end node for stmt and connects from with the new node. - /// - 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 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 sectionStartNodes = new List(); - - 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) - { - // while (cond) { embeddedStmt; } - 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) - { - // do { embeddedStmt; } while(cond); - 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 ; cond; iterators) { embeddedStmt; } - 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) - { - // foreach (...) { embeddedStmt } - 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); - } - } - - /// - /// Debugging helper that exports a control flow graph. - /// - public static GraphVizGraph ExportGraph(IList nodes) - { - GraphVizGraph g = new GraphVizGraph(); - GraphVizNode[] n = new GraphVizNode[nodes.Count]; - Dictionary dict = new Dictionary(); - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DeclarationSpace/LocalDeclarationSpace.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DeclarationSpace/LocalDeclarationSpace.cs deleted file mode 100644 index a412cba3a..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DeclarationSpace/LocalDeclarationSpace.cs +++ /dev/null @@ -1,157 +0,0 @@ -// -// LovalVariableDeclarationSpace.cs -// -// Author: -// Simon Lindgren -// -// 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 -{ - /// - /// Represents a declaration space. (§3.3) - /// - public class LocalDeclarationSpace - { - /// - /// Maps from variable name to the declarations in this declaration space. - /// - /// - /// This maps from variable name - /// - MultiDictionary declarations = new MultiDictionary (); - - public LocalDeclarationSpace() - { - Children = new List (); - } - - /// - /// The child declaration spaces. - /// - public IList Children { - get; - private set; - } - - /// - /// The parent declaration space. - /// - /// The parent. - public LocalDeclarationSpace Parent { - get; - private set; - } - - /// - /// The names declared in this declaration space, excluding child spaces. - /// - /// The declared names. - public ICollection DeclaredNames { - get { - return declarations.Keys; - } - } - - /// - /// Get all nodes declaring the name specified in . - /// - /// The declaring nodes. - /// The declaration name. - public IEnumerable GetNameDeclarations(string name) - { - return declarations [name].Concat(Children.SelectMany(child => child.GetNameDeclarations(name))); - } - - /// - /// Adds a child declaration space. - /// - /// The to add. - 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; - } - - /// - /// Adds a new declaration to the declaration space. - /// - /// The name of the declared variable. - /// A node associated with the declaration. - 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); - } - - /// - /// Determines if the name exists in the this declaration space. - /// - /// true, if the name specified in is used in this variable declaration space, false otherwise. - /// The name to look for. - /// When true, child declaration spaces are included in the search. - 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)); - } - - /// - /// Determines whether the name specified in is used in surrouding code. - /// - /// true if the name is used, false otherwise. - /// The name to check. - /// - /// Contrary to , 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. - /// - 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); - } - } -} \ No newline at end of file diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DeclarationSpace/LocalDeclarationSpaceVisitor.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DeclarationSpace/LocalDeclarationSpaceVisitor.cs deleted file mode 100644 index 08389a413..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DeclarationSpace/LocalDeclarationSpaceVisitor.cs +++ /dev/null @@ -1,138 +0,0 @@ -// -// LocalDeclarationSpaceVisitor.cs -// -// Author: -// Simon Lindgren -// -// 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 nodeDeclarationSpaces = new Dictionary(); - - 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 - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DefiniteAssignmentAnalysis.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DefiniteAssignmentAnalysis.cs deleted file mode 100644 index 9b33e74a7..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DefiniteAssignmentAnalysis.cs +++ /dev/null @@ -1,759 +0,0 @@ -// 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 -{ - /// - /// Represents the definite assignment status of a variable at a specific location. - /// - public enum DefiniteAssignmentStatus - { - /// - /// The variable might be assigned or unassigned. - /// - PotentiallyAssigned, - /// - /// The variable is definitely assigned. - /// - DefinitelyAssigned, - /// - /// The variable is definitely assigned iff the expression results in the value 'true'. - /// - AssignedAfterTrueExpression, - /// - /// The variable is definitely assigned iff the expression results in the value 'false'. - /// - AssignedAfterFalseExpression, - /// - /// The code is unreachable. - /// - CodeUnreachable - } - - /// - /// Implements the C# definite assignment analysis (C# 4.0 Spec: §5.3 Definite assignment) - /// - 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 allNodes = new List(); - readonly Dictionary beginNodeDict = new Dictionary(); - readonly Dictionary endNodeDict = new Dictionary(); - readonly Dictionary conditionNodeDict = new Dictionary(); - readonly CSharpAstResolver resolver; - Dictionary edgeStatus = new Dictionary(); - - string variableName; - List unassignedVariableUses = new List(); - int analyzedRangeStart, analyzedRangeEnd; - CancellationToken analysisCancellationToken; - - Queue nodesWithModifiedInput = new Queue(); - - 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()); - 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().Except(allNodes.Select(n => n.NextStatement)).Any()); - // Verify that we put all nodes into the dictionaries: - Debug.Assert(rootStatement.DescendantsAndSelf.OfType().All(stmt => beginNodeDict.ContainsKey(stmt))); - Debug.Assert(rootStatement.DescendantsAndSelf.OfType().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()); - return; - } - LambdaExpression lambda = node as LambdaExpression; - if (lambda != null && lambda.Body is Statement) { - allNodes.InsertRange(insertPos, cfgBuilder.BuildControlFlowGraph((Statement)lambda.Body, resolver, cancellationToken).Cast()); - 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); - } - } - - /// - /// Gets the unassigned usages of the previously analyzed variable. - /// - public IList UnassignedVariableUses { - get { - return unassignedVariableUses.AsReadOnly(); - } - } - - /// - /// 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. - /// - /// By default, both 'start' and 'end' are inclusive. - 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; - } - - /// - /// Exports the CFG. This method is intended to help debugging issues related to definite assignment. - /// - 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); - } - } - - /// - /// Evaluates an expression. - /// - /// The constant value of the expression; or null if the expression is not a constant. - ResolveResult EvaluateConstant(Expression expr) - { - return resolver.Resolve(expr, analysisCancellationToken); - } - - /// - /// Evaluates an expression. - /// - /// The value of the constant boolean expression; or null if the value is not a constant boolean expression. - 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 - { - 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 - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/NullValueAnalysis.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/NullValueAnalysis.cs deleted file mode 100644 index a20b4a0f0..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/NullValueAnalysis.cs +++ /dev/null @@ -1,2215 +0,0 @@ -// -// NullValueAnalysis.cs -// -// Author: -// Luís Reis -// -// 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, IEnumerable> - { - readonly Dictionary VariableStatus = new Dictionary(); - - 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; - } - } - } - - /// - /// Modifies the variable state to consider a new incoming path - /// - /// true, if the state has changed, false otherwise. - /// The variable state of the incoming path - 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> 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 { - internal readonly NullAnalysisNode nodeToVisit; - internal readonly VariableStatusInfo statusInfo; - internal readonly ComparableList pendingTryFinallyNodes; - internal readonly NullAnalysisNode nodeAfterFinally; - - internal PendingNode(NullAnalysisNode nodeToVisit, VariableStatusInfo statusInfo) - : this(nodeToVisit, statusInfo, new ComparableList(), null) - { - } - - public PendingNode(NullAnalysisNode nodeToVisit, VariableStatusInfo statusInfo, ComparableList 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 allNodes; - readonly HashSet nodesToVisit = new HashSet(); - Dictionary nodeBeforeStatementDict; - Dictionary nodeAfterStatementDict; - readonly Dictionary expressionResult = new Dictionary(); - - public NullValueAnalysis(BaseRefactoringContext context, MethodDeclaration methodDeclaration, CancellationToken cancellationToken) - : this(context, methodDeclaration.Body, methodDeclaration.Parameters, cancellationToken) - { - } - - readonly IEnumerable parameters; - readonly Statement rootStatement; - - readonly CancellationToken cancellationToken; - - public NullValueAnalysis(BaseRefactoringContext context, Statement rootStatement, IEnumerable 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; - } - - /// - /// 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. - /// - /// true, if local variable value was set, false otherwise. - /// The variable status data to change. - /// The identifier to set. - /// The name of the identifier to set. - /// The value to set the identifier. - 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().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() - .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()) { - //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()) { - //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(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(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(); - 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 - { - /// - /// True if the variable is null for the true path, false if it is false for the true path. - /// - public Dictionary TrueResultVariableNullStates = new Dictionary(); - /// - /// True if the variable is null for the false path, false if it is false for the false path. - /// - public Dictionary FalseResultVariableNullStates = new Dictionary(); - } - - class VisitorResult - { - /// - /// Indicates the return value of the expression. - /// - /// - /// Only applicable for expressions. - /// - public NullValueStatus NullableReturnResult; - - /// - /// Indicates the value of each item in an array or linq query. - /// - public NullValueStatus EnumeratedValueResult; - - /// - /// Information that indicates the restrictions to add - /// when branching. - /// - /// - /// Used in if/else statements, conditional expressions and - /// while statements. - /// - public ConditionalBranchInfo ConditionalBranchInfo; - - /// - /// The state of the variables after the expression is executed. - /// - public VariableStatusInfo Variables; - - /// - /// The expression is known to be invalid and trigger an error - /// (e.g. a NullReferenceException) - /// - public bool ThrowsException; - - /// - /// The known bool result of an expression. - /// - 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 - { - 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 parameterResults = new List(); - - 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(); - 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 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 = ""; - 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 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 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(); - 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(); - 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(); - 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); - } - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/NullValueStatus.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/NullValueStatus.cs deleted file mode 100644 index f6816dfd5..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/NullValueStatus.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -// NullValueAnalysis.cs -// -// Author: -// Luís Reis -// -// 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 -{ - /// - /// Represents the null value status of a variable at a specific location. - /// - public enum NullValueStatus - { - /// - /// The value of the variable is unknown, possibly due to limitations - /// of the null value analysis. - /// - Unknown = 0, - /// - /// 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. - /// - CapturedUnknown, - /// - /// This variable is potentially unassigned. - /// - Unassigned, - /// - /// The value of the variable is provably null. - /// - DefinitelyNull, - /// - /// The value of the variable might or might not be null - /// - PotentiallyNull, - /// - /// The value of the variable is provably not null - /// - DefinitelyNotNull, - /// - /// 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. - /// - UnreachableOrInexistent, - /// - /// The analyser has encountered an error when attempting to find the value - /// of this variable. - /// - Error - } - - public static class NullValueStatusExtensions - { - public static bool IsDefiniteValue (this NullValueStatus self) { - return self == NullValueStatus.DefinitelyNull || self == NullValueStatus.DefinitelyNotNull; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/ReachabilityAnalysis.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/ReachabilityAnalysis.cs deleted file mode 100644 index ce64f5f3b..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/ReachabilityAnalysis.cs +++ /dev/null @@ -1,209 +0,0 @@ -// 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 -{ - /// - /// Statement reachability analysis. - /// - public sealed class ReachabilityAnalysis - { - HashSet reachableStatements = new HashSet(); - HashSet reachableEndPoints = new HashSet(); - HashSet visitedNodes = new HashSet(); - Stack stack = new Stack(); - 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 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 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 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 - { - 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 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().FirstOrDefault(); - if (queryFromClause == null) - return true; - return queryFromClause.AcceptVisitor(this); - } - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/SemanticHighlightingVisitor.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/SemanticHighlightingVisitor.cs deleted file mode 100644 index 0528d4885..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/SemanticHighlightingVisitor.cs +++ /dev/null @@ -1,685 +0,0 @@ -// 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 -{ - /// - /// C# Semantic highlighter. - /// - public abstract class SemanticHighlightingVisitor : 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; - - /// - /// Used for 'in' modifiers on type parameters. - /// - /// - /// '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. - /// - protected TColor parameterModifierColor; - - /// - /// Used for inactive code (excluded by preprocessor or ConditionalAttribute) - /// - 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); - } - } - - /// - /// Visit all children of node until (but excluding) end. - /// If end is a null node, nothing will be visited. - /// - 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); - } - } - - /// - /// Visit all children of node after (excluding) start. - /// If start is a null node, all children will be visited. - /// - 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 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 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().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--; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstNode.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstNode.cs deleted file mode 100644 index 8676beb67..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstNode.cs +++ /dev/null @@ -1,1042 +0,0 @@ -// -// AstNode.cs -// -// Author: -// Mike Krüger -// -// 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 RootRole = new Role ("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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitPatternPlaceholder (this, child); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } - - /// - /// 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. - /// - 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 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; - } - } - } - - /// - /// Gets the ancestors of this node (excluding this node itself) - /// - public IEnumerable Ancestors { - get { - for (AstNode cur = parent; cur != null; cur = cur.parent) { - yield return cur; - } - } - } - - /// - /// Gets the ancestors of this node (including this node itself) - /// - public IEnumerable AncestorsAndSelf { - get { - for (AstNode cur = this; cur != null; cur = cur.parent) { - yield return cur; - } - } - } - - /// - /// Gets all descendants of this node (excluding this node itself) in pre-order. - /// - public IEnumerable Descendants { - get { return GetDescendantsImpl(false); } - } - - /// - /// Gets all descendants of this node (including this node itself) in pre-order. - /// - public IEnumerable 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 DescendantNodes (Func descendIntoChildren = null) - { - return GetDescendantsImpl(false, new DomRegion (), descendIntoChildren); - } - - public IEnumerable DescendantNodes (DomRegion region, Func descendIntoChildren = null) - { - return GetDescendantsImpl(false, region, descendIntoChildren); - } - - public IEnumerable DescendantNodesAndSelf (Func descendIntoChildren = null) - { - return GetDescendantsImpl(true, new DomRegion (), descendIntoChildren); - } - - public IEnumerable DescendantNodesAndSelf (DomRegion region, Func descendIntoChildren = null) - { - return GetDescendantsImpl(true, region, descendIntoChildren); - } - - IEnumerable GetDescendantsImpl(bool includeSelf, DomRegion region = new DomRegion (), Func descendIntoChildren = null) - { - if (includeSelf) { - if (IsInsideRegion (region, this)) - yield return this; - if (descendIntoChildren != null && !descendIntoChildren(this)) - yield break; - } - - Stack nextStack = new Stack(); - 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(); - } - } - - /// - /// Gets the first child with the specified role. - /// Returns the role's null object if the child is not found. - /// - public T GetChildByRole(Role 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() where T : AstNode - { - return Ancestors.OfType().FirstOrDefault(); - } - - public AstNode GetParent(Func pred) - { - return Ancestors.FirstOrDefault(pred); - } - - public AstNodeCollection GetChildrenByRole (Role role) where T : AstNode - { - return new AstNodeCollection (this, role); - } - - protected void SetChildByRole (Role role, T newChild) where T : AstNode - { - AstNode oldChild = GetChildByRole (role); - if (oldChild.IsNull) - AddChild (newChild, role); - else - oldChild.ReplaceWith (newChild); - } - - public void AddChild (T child, Role 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); - } - - /// - /// Adds a child without performing any safety checks. - /// - 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 (AstNode nextSibling, T child, Role 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 (AstNode prevSibling, T child, Role role) where T : AstNode - { - InsertChildBefore ((prevSibling == null || prevSibling.IsNull) ? firstChild : prevSibling.nextSibling, child, role); - } - - /// - /// Removes this node from its parent. - /// - 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; - } - } - - /// - /// Replaces this node with the new node. - /// - 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 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; - } - - /// - /// Clones the whole subtree starting at this AST node. - /// - /// Annotations are copied over to the new nodes; and any annotations implementing ICloneable will be cloned. - 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 (IAstVisitor visitor); - - public abstract S AcceptVisitor (IAstVisitor 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; - } - - /// - /// Gets the next node which fullfills a given predicate - /// - /// The next node. - /// The predicate. - public AstNode GetNextNode (Func 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; - } - - /// - /// Gets the previous node which fullfills a given predicate - /// - /// The next node. - /// The predicate. - public AstNode GetPrevNode (Func 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; - } - - /// - /// Gets the next sibling which fullfills a given predicate - /// - /// The next node. - /// The predicate. - public AstNode GetNextSibling (Func pred) - { - var next = NextSibling; - while (next != null && !pred (next)) - next = next.NextSibling; - return next; - } - - /// - /// Gets the next sibling which fullfills a given predicate - /// - /// The next node. - /// The predicate. - public AstNode GetPrevSibling (Func pred) - { - var prev = PrevSibling; - while (prev != null && !pred (prev)) - prev = prev.PrevSibling; - return prev; - } - - #region GetNodeAt - /// - /// 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) - /// - public AstNode GetNodeAt (int line, int column, Predicate pred = null) - { - return GetNodeAt (new TextLocation (line, column), pred); - } - - /// - /// 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) - /// - public AstNode GetNodeAt (TextLocation location, Predicate 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; - } - - /// - /// 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) - /// - public T GetNodeAt (int line, int column) where T : AstNode - { - return GetNodeAt (new TextLocation (line, column)); - } - - /// - /// 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) - /// - public T GetNodeAt (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 - /// - /// 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) - /// - public AstNode GetAdjacentNodeAt(int line, int column, Predicate pred = null) - { - return GetAdjacentNodeAt (new TextLocation (line, column), pred); - } - - /// - /// 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) - /// - public AstNode GetAdjacentNodeAt (TextLocation location, Predicate 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; - } - - /// - /// 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) - /// - public T GetAdjacentNodeAt(int line, int column) where T : AstNode - { - return GetAdjacentNodeAt (new TextLocation (line, column)); - } - - /// - /// 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) - /// - public T GetAdjacentNodeAt (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 - - - /// - /// Gets the node that fully contains the range from startLocation to endLocation. - /// - 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; - } - - /// - /// Returns the root nodes of all subtrees that are fully contained in the specified region. - /// - public IEnumerable GetNodesBetween (int startLine, int startColumn, int endLine, int endColumn) - { - return GetNodesBetween (new TextLocation (startLine, startColumn), new TextLocation (endLine, endColumn)); - } - - /// - /// Returns the root nodes of all subtrees that are fully contained between and (inclusive). - /// - public IEnumerable 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); - } - - /// - /// Gets the node as formatted C# output. - /// - /// - /// Formatting options. - /// - 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); - } - - /// - /// Returns true, if the given coordinates (line, column) are in the node. - /// - /// - /// True, if the given coordinates are between StartLocation and EndLocation (exclusive); otherwise, false. - /// - public bool Contains (int line, int column) - { - return Contains (new TextLocation (line, column)); - } - - /// - /// Returns true, if the given coordinates are in the node. - /// - /// - /// True, if location is between StartLocation and EndLocation (exclusive); otherwise, false. - /// - public bool Contains (TextLocation location) - { - return this.StartLocation <= location && location < this.EndLocation; - } - - /// - /// Returns true, if the given coordinates (line, column) are in the node. - /// - /// - /// True, if the given coordinates are between StartLocation and EndLocation (inclusive); otherwise, false. - /// - public bool IsInside (int line, int column) - { - return IsInside (new TextLocation (line, column)); - } - - /// - /// Returns true, if the given coordinates are in the node. - /// - /// - /// True, if location is between StartLocation and EndLocation (inclusive); otherwise, false. - /// - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstNodeCollection.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstNodeCollection.cs deleted file mode 100644 index 32d08b2e4..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstNodeCollection.cs +++ /dev/null @@ -1,231 +0,0 @@ -// 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 -{ - /// - /// Represents the children of an AstNode that have a specific role. - /// - public class AstNodeCollection : ICollection - #if NET_4_5 - , IReadOnlyCollection - #endif - where T : AstNode - { - readonly AstNode node; - readonly Role role; - - public AstNodeCollection(AstNode node, Role 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 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 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 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(); - } - - /// - /// Returns the first element for which the predicate returns true, - /// or the null node (AstNode with IsNull=true) if no such object is found. - /// - public T FirstOrNullObject(Func predicate = null) - { - foreach (T item in this) - if (predicate == null || predicate(item)) - return item; - return role.NullObject; - } - - /// - /// Returns the last element for which the predicate returns true, - /// or the null node (AstNode with IsNull=true) if no such object is found. - /// - public T LastOrNullObject(Func predicate = null) - { - T result = role.NullObject; - foreach (T item in this) - if (predicate == null || predicate(item)) - result = item; - return result; - } - - bool ICollection.IsReadOnly { - get { return false; } - } - - public IEnumerator 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 other = obj as AstNodeCollection; - if (other == null) - return false; - return this.node == other.node && this.role == other.role; - } - #endregion - - internal bool DoMatch(AstNodeCollection 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); - } - - /// - /// Applies the to all nodes in this collection. - /// - 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); - } - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstType.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstType.cs deleted file mode 100644 index 2f13f0fdd..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstType.cs +++ /dev/null @@ -1,280 +0,0 @@ -// 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 -{ - /// - /// A type reference in the C# AST. - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitPatternPlaceholder (this, child); - } - - public override S AcceptVisitor(IAstVisitor 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(); - } - - /// - /// Gets whether this type is a SimpleType "var". - /// - public bool IsVar() - { - SimpleType st = this as SimpleType; - return st != null && st.Identifier == "var" && st.TypeArguments.Count == 0; - } - - /// - /// Create an ITypeReference for this AstType. - /// Uses the context (ancestors of this node) to determine the correct . - /// - /// - /// The resulting type reference will read the context information from the - /// : - /// 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. - /// - public ITypeReference ToTypeReference(InterningProvider interningProvider = null) - { - return ToTypeReference(GetNameLookupMode(), interningProvider); - } - - /// - /// Create an ITypeReference for this AstType. - /// - /// - /// The resulting type reference will read the context information from the - /// : - /// 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. - /// - public abstract ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null); - - /// - /// Gets the name lookup mode from the context (looking at the ancestors of this ). - /// - 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; - } - - /// - /// Creates a pointer type from this type by nesting it in a . - /// If this type already is a pointer type, this method just increases the PointerRank of the existing pointer type. - /// - public virtual AstType MakePointerType() - { - return new ComposedType { BaseType = this }.MakePointerType(); - } - - /// - /// Creates an array type from this type by nesting it in a . - /// If this type already is an array type, the additional rank is prepended to the existing array specifier list. - /// Thus, new SimpleType("T").MakeArrayType(1).MakeArrayType(2) will result in "T[,][]". - /// - public virtual AstType MakeArrayType(int rank = 1) - { - return new ComposedType { BaseType = this }.MakeArrayType(rank); - } - - /// - /// Creates a nullable type from this type by nesting it in a . - /// - public AstType MakeNullableType() - { - return new ComposedType { BaseType = this, HasNullableSpecifier = true }; - } - - /// - /// Builds an expression that can be used to access a static member on this type. - /// - public MemberReferenceExpression Member(string memberName) - { - return new TypeReferenceExpression { Type = this }.Member(memberName); - } - - /// - /// Builds an expression that can be used to access a static member on this type. - /// - public MemberType MemberType(string memberName, params AstType[] typeArguments) - { - var memberType = new MemberType(this, memberName); - memberType.TypeArguments.AddRange(typeArguments); - return memberType; - } - - /// - /// Builds an expression that can be used to access a static member on this type. - /// - public MemberType MemberType(string memberName, IEnumerable typeArguments) - { - var memberType = new MemberType(this, memberName); - memberType.TypeArguments.AddRange(typeArguments); - return memberType; - } - - /// - /// Builds an invocation expression using this type as target. - /// - public InvocationExpression Invoke(string methodName, IEnumerable arguments) - { - return new TypeReferenceExpression { Type = this }.Invoke(methodName, arguments); - } - - /// - /// Builds an invocation expression using this type as target. - /// - public InvocationExpression Invoke(string methodName, params Expression[] arguments) - { - return new TypeReferenceExpression { Type = this }.Invoke(methodName, arguments); - } - - /// - /// Builds an invocation expression using this type as target. - /// - public InvocationExpression Invoke(string methodName, IEnumerable typeArguments, IEnumerable arguments) - { - return new TypeReferenceExpression { Type = this }.Invoke(methodName, typeArguments, arguments); - } - - /// - /// Creates a simple AstType from a dotted name. - /// Does not support generics, arrays, etc. - just simple dotted names, - /// e.g. namespace names. - /// - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/CSharpModifierToken.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/CSharpModifierToken.cs deleted file mode 100644 index 1a46006f2..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/CSharpModifierToken.cs +++ /dev/null @@ -1,218 +0,0 @@ -// -// CSharpModifierToken.cs -// -// Author: -// Mike Krüger -// -// 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 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"); - } - } - } -} \ No newline at end of file diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/CSharpTokenNode.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/CSharpTokenNode.cs deleted file mode 100644 index 713f664b3..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/CSharpTokenNode.cs +++ /dev/null @@ -1,131 +0,0 @@ -// -// TokenNode.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Represents a token in C#. Note that the type of the token is defined through the TokenRole. - /// - /// - /// In all non null c# token nodes the Role of a CSharpToken must be a TokenRole. - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitCSharpTokenNode (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/CSharpUtil.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/CSharpUtil.cs deleted file mode 100644 index a2a07ad6e..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/CSharpUtil.cs +++ /dev/null @@ -1,180 +0,0 @@ -// -// CSharpUtil.cs -// -// Author: -// Mike Krüger -// -// 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 - { - /// - /// Inverts a boolean condition. Note: The condition object can be frozen (from AST) it's cloned internally. - /// - /// The condition to invert. - 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())); - } - - /// - /// When negating an expression this is required, otherwise you would end up with - /// a or b -> !a or b - /// - 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; - } - - /// - /// Get negation of the specified relational operator - /// - /// - /// negation of the specified relational operator, or BinaryOperatorType.Any if it's not a relational operator - /// - 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; - } - - /// - /// Returns true, if the specified operator is a relational operator - /// - public static bool IsRelationalOperator(BinaryOperatorType op) - { - return NegateRelationalOperator(op) != BinaryOperatorType.Any; - } - - /// - /// Get negation of the condition operator - /// - /// - /// negation of the specified condition operator, or BinaryOperatorType.Any if it's not a condition operator - /// - 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; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ComposedType.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ComposedType.cs deleted file mode 100644 index 0c0f96c62..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ComposedType.cs +++ /dev/null @@ -1,230 +0,0 @@ -// -// ComposedType.cs -// -// Author: -// Mike Krüger -// -// 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 ArraySpecifierRole = new Role("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 ArraySpecifiers { - get { return GetChildrenByRole (ArraySpecifierRole); } - } - - public AstNodeCollection PointerTokens { - get { return GetChildrenByRole (PointerRole); } - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitComposedType (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitComposedType (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } - - /// - /// [,,,] - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitArraySpecifier (this); - } - - public override S AcceptVisitor (IAstVisitor 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) + "]"; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/DepthFirstAstVisitor.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/DepthFirstAstVisitor.cs deleted file mode 100644 index d8c678e2b..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/DepthFirstAstVisitor.cs +++ /dev/null @@ -1,1849 +0,0 @@ -// -// IAstVisitor.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// AST visitor with a default implementation that visits all node depth-first. - /// - 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); - } - } - - /// - /// AST visitor with a default implementation that visits all node depth-first. - /// - public abstract class DepthFirstAstVisitor : IAstVisitor - { - 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); - } - } - - /// - /// AST visitor with a default implementation that visits all node depth-first. - /// - public abstract class DepthFirstAstVisitor : IAstVisitor - { - 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/DocumentationReference.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/DocumentationReference.cs deleted file mode 100644 index 633f921b2..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/DocumentationReference.cs +++ /dev/null @@ -1,149 +0,0 @@ -// 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 -{ - /// - /// Represents a 'cref' reference in XML documentation. - /// - public class DocumentationReference : AstNode - { - public static readonly Role DeclaringTypeRole = new Role("DeclaringType", AstType.Null); - public static readonly Role ConversionOperatorReturnTypeRole = new Role("ConversionOperatorReturnType", AstType.Null); - - SymbolKind symbolKind; - OperatorType operatorType; - bool hasParameterList; - - /// - /// Gets/Sets the entity type. - /// Possible values are: - /// SymbolKind.Operator for operators, - /// SymbolKind.Indexer for indexers, - /// SymbolKind.TypeDefinition for references to primitive types, - /// and SymbolKind.None for everything else. - /// - public SymbolKind SymbolKind { - get { return symbolKind; } - set { - ThrowIfFrozen(); - symbolKind = value; - } - } - - /// - /// Gets/Sets the operator type. - /// This property is only used when SymbolKind==Operator. - /// - public OperatorType OperatorType { - get { return operatorType; } - set { - ThrowIfFrozen(); - operatorType = value; - } - } - - /// - /// Gets/Sets whether a parameter list was provided. - /// - public bool HasParameterList { - get { return hasParameterList; } - set { - ThrowIfFrozen(); - hasParameterList = value; - } - } - - public override NodeType NodeType { - get { return NodeType.Unknown; } - } - - /// - /// Gets/Sets the declaring type. - /// - public AstType DeclaringType { - get { return GetChildByRole(DeclaringTypeRole); } - set { SetChildByRole(DeclaringTypeRole, value); } - } - - /// - /// Gets/sets the member name. - /// This property is only used when SymbolKind==None. - /// - public string MemberName { - get { return GetChildByRole(Roles.Identifier).Name; } - set { SetChildByRole(Roles.Identifier, Identifier.Create(value)); } - } - - /// - /// Gets/Sets the return type of conversion operators. - /// This property is only used when SymbolKind==Operator and OperatorType is explicit or implicit. - /// - public AstType ConversionOperatorReturnType { - get { return GetChildByRole(ConversionOperatorReturnTypeRole); } - set { SetChildByRole(ConversionOperatorReturnTypeRole, value); } - } - - public AstNodeCollection TypeArguments { - get { return GetChildrenByRole (Roles.TypeArgument); } - } - - public AstNodeCollection 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 (IAstVisitor visitor) - { - return visitor.VisitDocumentationReference (this); - } - - public override S AcceptVisitor(IAstVisitor visitor, T data) - { - return visitor.VisitDocumentationReference (this, data); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ErrorNode.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ErrorNode.cs deleted file mode 100644 index 36d9ef6e0..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ErrorNode.cs +++ /dev/null @@ -1,88 +0,0 @@ -// -// ErrorNode.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// 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). - /// - 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(IAstVisitor visitor) - { - return visitor.VisitErrorNode(this); - } - - public override S AcceptVisitor(IAstVisitor 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]"; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AnonymousMethodExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AnonymousMethodExpression.cs deleted file mode 100644 index e8de95431..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AnonymousMethodExpression.cs +++ /dev/null @@ -1,117 +0,0 @@ -// -// AnonymousMethodExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// [async] delegate(Parameters) {Body} - /// - 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 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 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)parameters) - { - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitAnonymousMethodExpression (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitAnonymousMethodExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AnonymousTypeCreateExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AnonymousTypeCreateExpression.cs deleted file mode 100644 index 944bf61f5..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AnonymousTypeCreateExpression.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -// AnonymousTypeCreateExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// new { [ExpressionList] } - /// - 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 Initializers { - get { return GetChildrenByRole (Roles.Expression); } - } - - public CSharpTokenNode RParToken { - get { return GetChildByRole (Roles.RPar); } - } - - public AnonymousTypeCreateExpression () - { - } - - public AnonymousTypeCreateExpression (IEnumerable initializers) - { - foreach (var ini in initializers) { - AddChild (ini, Roles.Expression); - } - } - - public AnonymousTypeCreateExpression (params Expression[] initializer) : this ((IEnumerable)initializer) - { - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitAnonymousTypeCreateExpression (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitAnonymousTypeCreateExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ArrayCreateExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ArrayCreateExpression.cs deleted file mode 100644 index 3720a3fc8..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ArrayCreateExpression.cs +++ /dev/null @@ -1,80 +0,0 @@ -// 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 -{ - /// - /// new Type[Dimensions] - /// - public class ArrayCreateExpression : Expression - { - public readonly static TokenRole NewKeywordRole = new TokenRole ("new"); - public readonly static Role AdditionalArraySpecifierRole = new Role("AdditionalArraySpecifier"); - public readonly static Role InitializerRole = new Role("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 Arguments { - get { return GetChildrenByRole (Roles.Argument); } - } - - /// - /// Gets additional array ranks (those without size info). - /// Empty for "new int[5,1]"; will contain a single element for "new int[5][]". - /// - public AstNodeCollection 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 (IAstVisitor visitor) - { - return visitor.VisitArrayCreateExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ArrayInitializerExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ArrayInitializerExpression.cs deleted file mode 100644 index fa3246f92..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ArrayInitializerExpression.cs +++ /dev/null @@ -1,192 +0,0 @@ -// -// ArrayInitializerExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// { Elements } - /// - public class ArrayInitializerExpression : Expression - { - /// - /// 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). - /// - public virtual bool IsSingleElement { - get { - return false; - } - } - - public ArrayInitializerExpression() - { - } - - public ArrayInitializerExpression(IEnumerable 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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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 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 (IAstVisitor visitor) - { - return visitor.VisitArrayInitializerExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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(); - } - /// - /// Single elements in array initializers are represented with this special class. - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitPatternPlaceholder(this, child); - } - - public override S AcceptVisitor(IAstVisitor 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 - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AsExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AsExpression.cs deleted file mode 100644 index 5a7b5ac5d..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AsExpression.cs +++ /dev/null @@ -1,150 +0,0 @@ -// -// AsExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Expression as TypeReference - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitAsExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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 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 typeArguments, IEnumerable 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 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 - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AssignmentExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AssignmentExpression.cs deleted file mode 100644 index 95d0cdf28..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/AssignmentExpression.cs +++ /dev/null @@ -1,304 +0,0 @@ -// -// AssignmentExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Left Operator= Right - /// - public class AssignmentExpression : Expression - { - // reuse roles from BinaryOperatorExpression - public readonly static Role LeftRole = BinaryOperatorExpression.LeftRole; - public readonly static Role 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 (IAstVisitor visitor) - { - return visitor.VisitAssignmentExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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"); - } - } - - /// - /// Gets the binary operator for the specified compound assignment operator. - /// Returns null if 'op' is not a compound assignment. - /// - 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 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 typeArguments, IEnumerable 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 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 - { - /// left = right - Assign, - - /// left += right - Add, - /// left -= right - Subtract, - /// left *= right - Multiply, - /// left /= right - Divide, - /// left %= right - Modulus, - - /// left <<= right - ShiftLeft, - /// left >>= right - ShiftRight, - - /// left &= right - BitwiseAnd, - /// left |= right - BitwiseOr, - /// left ^= right - ExclusiveOr, - - /// Any operator (for pattern matching) - Any - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/BaseReferenceExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/BaseReferenceExpression.cs deleted file mode 100644 index 399c36c22..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/BaseReferenceExpression.cs +++ /dev/null @@ -1,71 +0,0 @@ -// -// BaseReferenceExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// base - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitBaseReferenceExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/BinaryOperatorExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/BinaryOperatorExpression.cs deleted file mode 100644 index e4408e184..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/BinaryOperatorExpression.cs +++ /dev/null @@ -1,325 +0,0 @@ -// -// BinaryOperatorExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Left Operator Right - /// - 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 LeftRole = new Role("Left", Expression.Null); - public readonly static Role RightRole = new Role("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 (IAstVisitor visitor) - { - return visitor.VisitBinaryOperatorExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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 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 typeArguments, IEnumerable 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 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 - { - /// - /// Any binary operator (used in pattern matching) - /// - 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='||' - /// left & right - BitwiseAnd, - /// left | right - BitwiseOr, - /// left && right - ConditionalAnd, - /// left || right - ConditionalOr, - /// left ^ right - ExclusiveOr, - - /// left > right - GreaterThan, - /// left >= right - GreaterThanOrEqual, - /// left == right - Equality, - /// left != right - InEquality, - /// left < right - LessThan, - /// left <= right - LessThanOrEqual, - - /// left + right - Add, - /// left - right - Subtract, - /// left * right - Multiply, - /// left / right - Divide, - /// left % right - Modulus, - - /// left << right - ShiftLeft, - /// left >> right - ShiftRight, - - /// left ?? right - NullCoalescing - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/CastExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/CastExpression.cs deleted file mode 100644 index e771d18fe..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/CastExpression.cs +++ /dev/null @@ -1,152 +0,0 @@ -// -// CastExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// (CastTo)Expression - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitCastExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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 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 typeArguments, IEnumerable 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 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 - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/CheckedExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/CheckedExpression.cs deleted file mode 100644 index 66bdcb54d..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/CheckedExpression.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -// CheckedExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// checked(Expression) - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitCheckedExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ConditionalExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ConditionalExpression.cs deleted file mode 100644 index 4367a0cce..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ConditionalExpression.cs +++ /dev/null @@ -1,162 +0,0 @@ -// -// ConditionalExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Condition ? TrueExpression : FalseExpression - /// - public class ConditionalExpression : Expression - { - public readonly static Role ConditionRole = Roles.Condition; - public readonly static TokenRole QuestionMarkRole = new TokenRole("?"); - public readonly static Role TrueRole = new Role("True", Expression.Null); - public readonly static TokenRole ColonRole = Roles.Colon; - public readonly static Role FalseRole = new Role("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 (IAstVisitor visitor) - { - return visitor.VisitConditionalExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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 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 typeArguments, IEnumerable 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 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 - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/DefaultValueExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/DefaultValueExpression.cs deleted file mode 100644 index 0aab343f3..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/DefaultValueExpression.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -// DefaultValueExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// default(Type) - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitDefaultValueExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/DirectionExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/DirectionExpression.cs deleted file mode 100644 index a17c117bb..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/DirectionExpression.cs +++ /dev/null @@ -1,89 +0,0 @@ -// -// DirectionExpression.cs -// -// Author: -// Mike Krüger -// -// 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 - } - - /// - /// ref Expression - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitDirectionExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ErrorExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ErrorExpression.cs deleted file mode 100644 index 6054792e4..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ErrorExpression.cs +++ /dev/null @@ -1,129 +0,0 @@ -// -// ErrorExpression.cs -// -// Author: -// Mike Krüger -// -// 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(IAstVisitor visitor) - { - throw new NotImplementedException(); - } - - public override S AcceptVisitor(IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitErrorNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/Expression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/Expression.cs deleted file mode 100644 index 22962a606..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/Expression.cs +++ /dev/null @@ -1,230 +0,0 @@ -// 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 -{ - /// - /// Base class for expressions. - /// - /// - /// 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" - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitPatternPlaceholder(this, child); - } - - public override S AcceptVisitor(IAstVisitor 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 replaceFunction) - { - if (replaceFunction == null) - throw new ArgumentNullException("replaceFunction"); - return (Expression)base.ReplaceWith(node => replaceFunction((Expression)node)); - } - - #region Builder methods - /// - /// Builds an member reference expression using this expression as target. - /// - public virtual MemberReferenceExpression Member(string memberName) - { - return new MemberReferenceExpression { Target = this, MemberName = memberName }; - } - - /// - /// Builds an indexer expression using this expression as target. - /// - public virtual IndexerExpression Indexer(IEnumerable arguments) - { - IndexerExpression expr = new IndexerExpression(); - expr.Target = this; - expr.Arguments.AddRange(arguments); - return expr; - } - - /// - /// Builds an indexer expression using this expression as target. - /// - public virtual IndexerExpression Indexer(params Expression[] arguments) - { - IndexerExpression expr = new IndexerExpression(); - expr.Target = this; - expr.Arguments.AddRange(arguments); - return expr; - } - - /// - /// Builds an invocation expression using this expression as target. - /// - public virtual InvocationExpression Invoke(string methodName, IEnumerable arguments) - { - return Invoke(methodName, null, arguments); - } - - /// - /// Builds an invocation expression using this expression as target. - /// - public virtual InvocationExpression Invoke(string methodName, params Expression[] arguments) - { - return Invoke(methodName, null, arguments); - } - - /// - /// Builds an invocation expression using this expression as target. - /// - public virtual InvocationExpression Invoke(string methodName, IEnumerable typeArguments, IEnumerable 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; - } - - /// - /// Builds an invocation expression using this expression as target. - /// - public virtual InvocationExpression Invoke(IEnumerable arguments) - { - InvocationExpression ie = new InvocationExpression(); - ie.Target = this; - ie.Arguments.AddRange(arguments); - return ie; - } - - /// - /// Builds an invocation expression using this expression as target. - /// - 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 - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/IdentifierExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/IdentifierExpression.cs deleted file mode 100644 index 0ec466c3f..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/IdentifierExpression.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -// IdentifierExpression.cs -// -// Author: -// Mike Krüger -// -// 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 TypeArguments { - get { return GetChildrenByRole (Roles.TypeArgument); } - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitIdentifierExpression (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitIdentifierExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/IndexerExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/IndexerExpression.cs deleted file mode 100644 index cbc80c2cf..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/IndexerExpression.cs +++ /dev/null @@ -1,92 +0,0 @@ -// -// IndexerExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Target[Arguments] - /// - 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 Arguments { - get { return GetChildrenByRole(Roles.Argument); } - } - - public CSharpTokenNode RBracketToken { - get { return GetChildByRole (Roles.RBracket); } - } - - public IndexerExpression () - { - } - - public IndexerExpression (Expression target, IEnumerable 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)arguments) - { - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitIndexerExpression (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitIndexerExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/InvocationExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/InvocationExpression.cs deleted file mode 100644 index ad768d541..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/InvocationExpression.cs +++ /dev/null @@ -1,92 +0,0 @@ -// -// InvocationExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Target(Arguments) - /// - 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 Arguments { - get { return GetChildrenByRole(Roles.Argument); } - } - - public CSharpTokenNode RParToken { - get { return GetChildByRole (Roles.RPar); } - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitInvocationExpression (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitInvocationExpression (this); - } - - public override S AcceptVisitor (IAstVisitor visitor, T data) - { - return visitor.VisitInvocationExpression (this, data); - } - - public InvocationExpression () - { - } - - public InvocationExpression (Expression target, IEnumerable 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)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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/IsExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/IsExpression.cs deleted file mode 100644 index 791ab25d7..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/IsExpression.cs +++ /dev/null @@ -1,150 +0,0 @@ -// -// TypeOfIsExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Expression is Type - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitIsExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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 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 typeArguments, IEnumerable 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 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 - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/LambdaExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/LambdaExpression.cs deleted file mode 100644 index e85902d84..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/LambdaExpression.cs +++ /dev/null @@ -1,89 +0,0 @@ -// -// LambdaExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// [async] Parameters => Body - /// - public class LambdaExpression : Expression - { - public readonly static TokenRole AsyncModifierRole = new TokenRole ("async"); - public readonly static TokenRole ArrowRole = new TokenRole ("=>"); - public static readonly Role BodyRole = new Role("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 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 (IAstVisitor visitor) - { - return visitor.VisitLambdaExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/MemberReferenceExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/MemberReferenceExpression.cs deleted file mode 100644 index 334c6a260..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/MemberReferenceExpression.cs +++ /dev/null @@ -1,119 +0,0 @@ -// -// MemberReferenceExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Target.MemberName - /// - 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 TypeArguments { - get { return GetChildrenByRole (Roles.TypeArgument); } - } - - public CSharpTokenNode RChevronToken { - get { return GetChildByRole (Roles.RChevron); } - } - - public MemberReferenceExpression () - { - } - - public MemberReferenceExpression (Expression target, string memberName, IEnumerable 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)arguments) - { - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitMemberReferenceExpression (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitMemberReferenceExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/NamedArgumentExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/NamedArgumentExpression.cs deleted file mode 100644 index 6b485f015..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/NamedArgumentExpression.cs +++ /dev/null @@ -1,87 +0,0 @@ -// 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 -{ - /// - /// Represents a named argument passed to a method or attribute. - /// name: expression - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitNamedArgumentExpression (this); - } - - public override S AcceptVisitor(IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/NamedExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/NamedExpression.cs deleted file mode 100644 index 92bc993b1..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/NamedExpression.cs +++ /dev/null @@ -1,97 +0,0 @@ -// -// NamedExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// 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)]. - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitNamedExpression (this); - } - - public override S AcceptVisitor(IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/NullReferenceExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/NullReferenceExpression.cs deleted file mode 100644 index fbfeb6f91..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/NullReferenceExpression.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -// NullReferenceExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// null - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitNullReferenceExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ObjectCreateExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ObjectCreateExpression.cs deleted file mode 100644 index a9665f8c7..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ObjectCreateExpression.cs +++ /dev/null @@ -1,104 +0,0 @@ -// -// ObjectCreateExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// new Type(Arguments) { Initializer } - /// - public class ObjectCreateExpression : Expression - { - public readonly static TokenRole NewKeywordRole = new TokenRole ("new"); - public readonly static Role 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 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 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)arguments) - { - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitObjectCreateExpression (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitObjectCreateExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ParenthesizedExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ParenthesizedExpression.cs deleted file mode 100644 index 7dddcb3fb..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ParenthesizedExpression.cs +++ /dev/null @@ -1,98 +0,0 @@ -// -// ParenthesizedExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// ( Expression ) - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitParenthesizedExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - - /// - /// 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. - /// - /// Returns true for ParenthesizedExpression, CheckedExpression or UncheckedExpression; false otherwise. - public static bool ActsAsParenthesizedExpression(AstNode expression) - { - return expression is ParenthesizedExpression || expression is CheckedExpression || expression is UncheckedExpression; - } - - /// - /// Unpacks the given expression if it is a ParenthesizedExpression, CheckedExpression or UncheckedExpression. - /// - public static Expression UnpackParenthesizedExpression(Expression expr) - { - while (ActsAsParenthesizedExpression(expr)) - expr = expr.GetChildByRole(Roles.Expression); - return expr; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/PointerReferenceExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/PointerReferenceExpression.cs deleted file mode 100644 index 35c4a7203..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/PointerReferenceExpression.cs +++ /dev/null @@ -1,90 +0,0 @@ -// -// PointerReferenceExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Target->MemberName - /// - 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 TypeArguments { - get { return GetChildrenByRole (Roles.TypeArgument); } - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitPointerReferenceExpression (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitPointerReferenceExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/PrimitiveExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/PrimitiveExpression.cs deleted file mode 100644 index adfe7c3ba..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/PrimitiveExpression.cs +++ /dev/null @@ -1,162 +0,0 @@ -// -// PrimitiveExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Represents a literal value. - /// - 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; - } - } - - /// Never returns null. - public string LiteralValue { - get { return literalValue ?? ""; } - } - - /// Can be null. - 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 (IAstVisitor visitor) - { - return visitor.VisitPrimitiveExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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)); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/QueryExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/QueryExpression.cs deleted file mode 100644 index b52f50a47..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/QueryExpression.cs +++ /dev/null @@ -1,655 +0,0 @@ -// 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 ClauseRole = new Role("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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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 Clauses { - get { return GetChildrenByRole(ClauseRole); } - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitQueryExpression (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitQueryExpression (this); - } - - public override S AcceptVisitor(IAstVisitor 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 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 typeArguments, IEnumerable 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 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; } - } - } - - /// - /// 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) - /// } - /// - public class QueryContinuationClause : QueryClause - { - public static readonly Role PrecedingQueryRole = new Role("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 (IAstVisitor visitor) - { - return visitor.VisitQueryContinuationClause (this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitQueryFromClause (this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitQueryLetClause (this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitQueryWhereClause (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } - - /// - /// Represents a join or group join clause. - /// - public class QueryJoinClause : QueryClause - { - public static readonly TokenRole JoinKeywordRole = new TokenRole ("join"); - public static readonly Role TypeRole = Roles.Type; - public static readonly Role JoinIdentifierRole = Roles.Identifier; - public static readonly TokenRole InKeywordRole = new TokenRole ("in"); - public static readonly Role InExpressionRole = Roles.Expression; - public static readonly TokenRole OnKeywordRole = new TokenRole ("on"); - public static readonly Role OnExpressionRole = new Role("OnExpression", Expression.Null); - public static readonly TokenRole EqualsKeywordRole = new TokenRole ("equals"); - public static readonly Role EqualsExpressionRole = new Role("EqualsExpression", Expression.Null); - public static readonly TokenRole IntoKeywordRole = new TokenRole ("into"); - public static readonly Role IntoIdentifierRole = new Role("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 (IAstVisitor visitor) - { - return visitor.VisitQueryJoinClause (this); - } - - public override S AcceptVisitor (IAstVisitor 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 OrderingRole = new Role("Ordering"); - - public CSharpTokenNode OrderbyToken { - get { return GetChildByRole (OrderbyKeywordRole); } - } - - public AstNodeCollection Orderings { - get { return GetChildrenByRole (OrderingRole); } - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitQueryOrderClause (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitQueryOrderClause (this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitQueryOrdering (this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitQuerySelectClause (this); - } - - public override S AcceptVisitor (IAstVisitor 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 ProjectionRole = new Role("Projection", Expression.Null); - public static readonly TokenRole ByKeywordRole = new TokenRole ("by"); - public static readonly Role KeyRole = new Role("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 (IAstVisitor visitor) - { - return visitor.VisitQueryGroupClause (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} \ No newline at end of file diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/SizeOfExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/SizeOfExpression.cs deleted file mode 100644 index 8a794960c..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/SizeOfExpression.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -// SizeOfExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// sizeof(Type) - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitSizeOfExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/StackAllocExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/StackAllocExpression.cs deleted file mode 100644 index ad9f58c1b..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/StackAllocExpression.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -// StackAllocExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// stackalloc Type[Count] - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitStackAllocExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ThisReferenceExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ThisReferenceExpression.cs deleted file mode 100644 index 481ef6658..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ThisReferenceExpression.cs +++ /dev/null @@ -1,71 +0,0 @@ -// -// ThisReferenceExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// this - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitThisReferenceExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/TypeOfExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/TypeOfExpression.cs deleted file mode 100644 index fd2e93ab8..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/TypeOfExpression.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -// TypeOfExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// typeof(Type) - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitTypeOfExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/TypeReferenceExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/TypeReferenceExpression.cs deleted file mode 100644 index 84b2d60dc..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/TypeReferenceExpression.cs +++ /dev/null @@ -1,64 +0,0 @@ -// 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 -{ - /// - /// Represents an AstType as an expression. - /// This is used when calling a method on a primitive type: "int.Parse()" - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitTypeReferenceExpression (this); - } - - public override S AcceptVisitor(IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/UnaryOperatorExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/UnaryOperatorExpression.cs deleted file mode 100644 index 878d6132f..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/UnaryOperatorExpression.cs +++ /dev/null @@ -1,181 +0,0 @@ -// -// UnaryOperatorExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Operator Expression - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitUnaryOperatorExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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 - { - /// - /// Any unary operator (used in pattern matching) - /// - Any, - - /// Logical not (!a) - Not, - /// Bitwise not (~a) - BitNot, - /// Unary minus (-a) - Minus, - /// Unary plus (+a) - Plus, - /// Pre increment (++a) - Increment, - /// Pre decrement (--a) - Decrement, - /// Post increment (a++) - PostIncrement, - /// Post decrement (a--) - PostDecrement, - /// Dereferencing (*a) - Dereference, - /// Get address (&a) - AddressOf, - /// C# 5.0 await - Await - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/UncheckedExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/UncheckedExpression.cs deleted file mode 100644 index 5b8686a26..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/UncheckedExpression.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -// UncheckedExpression.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// unchecked(Expression) - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitUncheckedExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/UndocumentedExpression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/UndocumentedExpression.cs deleted file mode 100644 index 0efc0d70f..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/UndocumentedExpression.cs +++ /dev/null @@ -1,105 +0,0 @@ -// -// UndocumentedExpression.cs -// -// Author: -// Mike Krüger -// -// 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) - } - - /// - /// Represents undocumented expressions. - /// - 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 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 (IAstVisitor visitor) - { - return visitor.VisitUndocumentedExpression (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/Attribute.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/Attribute.cs deleted file mode 100644 index cc99936e5..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/Attribute.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -// Attribute.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Attribute(Arguments) - /// - 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 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 (IAstVisitor visitor) - { - return visitor.VisitAttribute (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/AttributeSection.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/AttributeSection.cs deleted file mode 100644 index 67b04412b..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/AttributeSection.cs +++ /dev/null @@ -1,174 +0,0 @@ -// -// AttributeSection.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// [AttributeTarget: Attributes] - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitPatternPlaceholder (this, child); - } - - public override S AcceptVisitor(IAstVisitor 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 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 (IAstVisitor visitor) - { - return visitor.VisitAttributeSection (this); - } - - public override S AcceptVisitor (IAstVisitor 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"); -// } -// } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/Comment.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/Comment.cs deleted file mode 100644 index 9d53f6e66..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/Comment.cs +++ /dev/null @@ -1,140 +0,0 @@ -// -// Comment.cs -// -// Author: -// Mike Krüger -// -// 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 - { - /// - /// "//" comment - /// - SingleLine, - /// - /// "/* */" comment - /// - MultiLine, - /// - /// "///" comment - /// - Documentation, - /// - /// Inactive code (code in non-taken "#if") - /// - InactiveCode, - /// - /// "/** */" comment - /// - 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; } - } - - /// - /// Returns true if the is Documentation or MultiLineDocumentation. - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitComment (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/Constraint.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/Constraint.cs deleted file mode 100644 index c49930427..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/Constraint.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -// Constraint.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// where TypeParameter : BaseTypes - /// - /// - /// new(), struct and class constraints are represented using a PrimitiveType "new", "struct" or "class" - /// - 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 BaseTypes { - get { - return GetChildrenByRole(Roles.BaseType); } - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitConstraint (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitConstraint (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/DelegateDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/DelegateDeclaration.cs deleted file mode 100644 index 68489bc7f..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/DelegateDeclaration.cs +++ /dev/null @@ -1,92 +0,0 @@ -// -// DelegateDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// delegate ReturnType Name<TypeParameters>(Parameters) where Constraints; - /// - 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 TypeParameters { - get { return GetChildrenByRole (Roles.TypeParameter); } - } - - public CSharpTokenNode LParToken { - get { return GetChildByRole (Roles.LPar); } - } - - public AstNodeCollection Parameters { - get { return GetChildrenByRole (Roles.Parameter); } - } - - public CSharpTokenNode RParToken { - get { return GetChildByRole (Roles.RPar); } - } - - public AstNodeCollection Constraints { - get { return GetChildrenByRole (Roles.Constraint); } - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitDelegateDeclaration (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitDelegateDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/ExternAliasDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/ExternAliasDeclaration.cs deleted file mode 100644 index 9404d417f..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/ExternAliasDeclaration.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -// ExternAliasDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// extern alias ; - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitExternAliasDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/NamespaceDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/NamespaceDeclaration.cs deleted file mode 100644 index dbcf0192d..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/NamespaceDeclaration.cs +++ /dev/null @@ -1,158 +0,0 @@ -// -// NamespaceDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// namespace Name { Members } - /// - public class NamespaceDeclaration : AstNode - { - public static readonly Role MemberRole = SyntaxTree.MemberRole; - public static readonly Role NamespaceNameRole = new Role("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]); - } - - /// - /// Gets the full namespace name (including any parent namespaces) - /// - public string FullName { - get { - NamespaceDeclaration parentNamespace = Parent as NamespaceDeclaration; - if (parentNamespace != null) - return BuildQualifiedName(parentNamespace.FullName, Name); - return Name; - } - } - - public IEnumerable Identifiers { - get { - var result = new Stack(); - 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 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(IAstVisitor visitor) - { - return visitor.VisitNamespaceDeclaration(this); - } - - public override S AcceptVisitor(IAstVisitor 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); - } - } -} ; diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/NewLineNode.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/NewLineNode.cs deleted file mode 100644 index 12b004420..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/NewLineNode.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System; -namespace ICSharpCode.NRefactory.CSharp -{ - - /// - /// A New line node represents a line break in the text. - /// - 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(IAstVisitor visitor) - { - return visitor.VisitNewLine (this); - } - - public override S AcceptVisitor(IAstVisitor visitor, T data) - { - return visitor.VisitNewLine (this, data); - } - - protected internal override bool DoMatch(AstNode other, ICSharpCode.NRefactory.PatternMatching.Match match) - { - return other is NewLineNode; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/PreProcessorDirective.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/PreProcessorDirective.cs deleted file mode 100644 index 631f35e98..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/PreProcessorDirective.cs +++ /dev/null @@ -1,205 +0,0 @@ -// -// PreProcessorDirective.cs -// -// Author: -// Mike Krüger -// -// 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 WarningRole = new Role ("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 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; - } - - /// - /// For an '#if' directive, specifies whether the condition evaluated to true. - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitPreProcessorDirective (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/TextNode.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/TextNode.cs deleted file mode 100644 index 4c7f9b942..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/TextNode.cs +++ /dev/null @@ -1,94 +0,0 @@ -// -// TextNode.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// A text node contains text without syntactic or semantic information. - /// (non parseable part of a text) - /// - 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(IAstVisitor visitor) - { - return visitor.VisitText (this); - } - - public override S AcceptVisitor(IAstVisitor 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; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/TypeDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/TypeDeclaration.cs deleted file mode 100644 index f2dedfa16..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/TypeDeclaration.cs +++ /dev/null @@ -1,145 +0,0 @@ -// -// TypeDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 - } - - /// - /// class Name<TypeParameters> : BaseTypes where Constraints; - /// - 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 TypeParameters { - get { return GetChildrenByRole (Roles.TypeParameter); } - } - - public CSharpTokenNode RChevronToken { - get { return GetChildByRole (Roles.RChevron); } - } - - - - public CSharpTokenNode ColonToken { - get { - return GetChildByRole(Roles.Colon); - } - } - - public AstNodeCollection BaseTypes { - get { return GetChildrenByRole(Roles.BaseType); } - } - - public AstNodeCollection Constraints { - get { return GetChildrenByRole(Roles.Constraint); } - } - - public CSharpTokenNode LBraceToken { - get { return GetChildByRole (Roles.LBrace); } - } - - public AstNodeCollection 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 (IAstVisitor visitor) - { - return visitor.VisitTypeDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/TypeParameterDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/TypeParameterDeclaration.cs deleted file mode 100644 index c992b629a..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/TypeParameterDeclaration.cs +++ /dev/null @@ -1,113 +0,0 @@ -// 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 -{ - /// - /// [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. - /// - public class TypeParameterDeclaration : AstNode - { - public static readonly Role 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 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 (IAstVisitor visitor) - { - return visitor.VisitTypeParameterDeclaration (this); - } - - public override S AcceptVisitor(IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/UsingAliasDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/UsingAliasDeclaration.cs deleted file mode 100644 index 9924132d3..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/UsingAliasDeclaration.cs +++ /dev/null @@ -1,107 +0,0 @@ -// -// UsingAliasDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// using Alias = Import; - /// - public class UsingAliasDeclaration : AstNode - { - public static readonly TokenRole UsingKeywordRole = new TokenRole ("using"); - public static readonly Role AliasRole = new Role("Alias", Identifier.Null); - public static readonly Role 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 (IAstVisitor visitor) - { - return visitor.VisitUsingAliasDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/UsingDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/UsingDeclaration.cs deleted file mode 100644 index 9e0c35a89..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/UsingDeclaration.cs +++ /dev/null @@ -1,122 +0,0 @@ -// -// UsingDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// using Import; - /// - public class UsingDeclaration : AstNode - { - public static readonly TokenRole UsingKeywordRole = new TokenRole ("using"); - public static readonly Role ImportRole = new Role("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(); - 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 (IAstVisitor visitor) - { - return visitor.VisitUsingDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/WhitespaceNode.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/WhitespaceNode.cs deleted file mode 100644 index c7e37f704..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/WhitespaceNode.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -// WhitespaceNode.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// A Whitespace node contains only whitespaces. - /// - 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(IAstVisitor visitor) - { - return visitor.VisitWhitespace (this); - } - - public override S AcceptVisitor(IAstVisitor 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; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/IAstVisitor.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/IAstVisitor.cs deleted file mode 100644 index 4aadddbdc..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/IAstVisitor.cs +++ /dev/null @@ -1,418 +0,0 @@ -// 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 -{ - /// - /// AST visitor. - /// - 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); - } - - /// - /// AST visitor. - /// - public interface IAstVisitor - { - 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); - } - - /// - /// AST visitor. - /// - public interface IAstVisitor - { - 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); - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Identifier.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Identifier.cs deleted file mode 100644 index cf403afbd..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Identifier.cs +++ /dev/null @@ -1,173 +0,0 @@ -// -// Identifier.cs -// -// Author: -// Mike Krüger -// -// 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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitIdentifier (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} \ No newline at end of file diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/IdentifierExpressionBackreference.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/IdentifierExpressionBackreference.cs deleted file mode 100644 index 7bfacd990..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/IdentifierExpressionBackreference.cs +++ /dev/null @@ -1,54 +0,0 @@ -// 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 -{ - /// - /// Matches identifier expressions that have the same identifier as the referenced variable/type definition/method definition. - /// - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/MemberType.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/MemberType.cs deleted file mode 100644 index 2045d00ed..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/MemberType.cs +++ /dev/null @@ -1,150 +0,0 @@ -// -// FullTypeName.cs -// -// Author: -// Mike Krüger -// -// 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 TargetRole = new Role("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 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 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)typeArguments) - { - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitMemberType (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitMemberType (this); - } - - public override S AcceptVisitor (IAstVisitor 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(); - 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)); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Modifiers.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Modifiers.cs deleted file mode 100644 index eb320495c..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Modifiers.cs +++ /dev/null @@ -1,65 +0,0 @@ -// -// Modifiers.cs -// -// Author: -// Mike Krüger -// -// 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, - - /// - /// Special value used to match any modifiers during pattern matching. - /// - Any = unchecked((int)0x80000000) - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/NodeType.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/NodeType.cs deleted file mode 100644 index cf96a60c8..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/NodeType.cs +++ /dev/null @@ -1,56 +0,0 @@ -// -// NodeType.cs -// -// Author: -// Mike Krüger -// -// 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, - /// - /// AstType - /// - TypeReference, - /// - /// Type or delegate declaration - /// - TypeDeclaration, - Member, - Statement, - Expression, - Token, - QueryClause, - /// - /// Comment or whitespace or pre-processor directive - /// - Whitespace, - /// - /// Placeholder for a pattern - /// - Pattern - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ObservableAstVisitor.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ObservableAstVisitor.cs deleted file mode 100644 index 898d51864..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ObservableAstVisitor.cs +++ /dev/null @@ -1,857 +0,0 @@ -// -// ObservableAstVisitor.cs -// -// Author: -// Mike Krüger -// -// 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(Action enter, Action 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 EnterSyntaxTree, LeaveSyntaxTree; - - void IAstVisitor.VisitSyntaxTree(SyntaxTree unit) - { - Visit(EnterSyntaxTree, LeaveSyntaxTree, unit); - } - - public event Action EnterComment, LeaveComment; - - void IAstVisitor.VisitComment(Comment comment) - { - Visit(EnterComment, LeaveComment, comment); - } - - public event Action EnterNewLine, LeaveNewLine; - - void IAstVisitor.VisitNewLine(NewLineNode newLineNode) - { - Visit(EnterNewLine, LeaveNewLine, newLineNode); - } - - public event Action EnterWhitespace, LeaveWhitespace; - - void IAstVisitor.VisitWhitespace(WhitespaceNode whitespace) - { - Visit(EnterWhitespace, LeaveWhitespace, whitespace); - } - - public event Action EnterText, LeaveText; - - void IAstVisitor.VisitText(TextNode textNode) - { - Visit(EnterText, LeaveText, textNode); - } - - public event Action EnterPreProcessorDirective, LeavePreProcessorDirective; - void IAstVisitor.VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective) - { - Visit(EnterPreProcessorDirective, LeavePreProcessorDirective, preProcessorDirective); - } - - public event Action EnterDocumentationReference, LeaveDocumentationReference; - - void IAstVisitor.VisitDocumentationReference(DocumentationReference documentationReference) - { - Visit(EnterDocumentationReference, LeaveDocumentationReference, documentationReference); - } - - public event Action EnterIdentifier, LeaveIdentifier; - - void IAstVisitor.VisitIdentifier(Identifier identifier) - { - Visit(EnterIdentifier, LeaveIdentifier, identifier); - } - - public event Action EnterCSharpTokenNode, LeaveCSharpTokenNode; - - void IAstVisitor.VisitCSharpTokenNode(CSharpTokenNode token) - { - Visit(EnterCSharpTokenNode, LeaveCSharpTokenNode, token); - } - - public event Action EnterPrimitiveType, LeavePrimitiveType; - - void IAstVisitor.VisitPrimitiveType(PrimitiveType primitiveType) - { - Visit(EnterPrimitiveType, LeavePrimitiveType, primitiveType); - } - - public event Action EnterComposedType, LeaveComposedType; - - void IAstVisitor.VisitComposedType(ComposedType composedType) - { - Visit(EnterComposedType, LeaveComposedType, composedType); - } - - public event Action EnterSimpleType, LeaveSimpleType; - - void IAstVisitor.VisitSimpleType(SimpleType simpleType) - { - Visit(EnterSimpleType, LeaveSimpleType, simpleType); - } - - public event Action EnterMemberType, LeaveMemberType; - - void IAstVisitor.VisitMemberType(MemberType memberType) - { - Visit(EnterMemberType, LeaveMemberType, memberType); - } - - public event Action EnterAttribute, LeaveAttribute; - - void IAstVisitor.VisitAttribute(Attribute attribute) - { - Visit(EnterAttribute, LeaveAttribute, attribute); - } - - public event Action EnterAttributeSection, LeaveAttributeSection; - - void IAstVisitor.VisitAttributeSection(AttributeSection attributeSection) - { - Visit(EnterAttributeSection, LeaveAttributeSection, attributeSection); - } - - public event Action EnterDelegateDeclaration, LeaveDelegateDeclaration; - - void IAstVisitor.VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration) - { - Visit(EnterDelegateDeclaration, LeaveDelegateDeclaration, delegateDeclaration); - } - - public event Action EnterNamespaceDeclaration, LeaveNamespaceDeclaration; - - void IAstVisitor.VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration) - { - Visit(EnterNamespaceDeclaration, LeaveNamespaceDeclaration, namespaceDeclaration); - } - - public event Action EnterTypeDeclaration, LeaveTypeDeclaration; - - void IAstVisitor.VisitTypeDeclaration(TypeDeclaration typeDeclaration) - { - Visit(EnterTypeDeclaration, LeaveTypeDeclaration, typeDeclaration); - } - - public event Action EnterTypeParameterDeclaration, LeaveTypeParameterDeclaration; - - void IAstVisitor.VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration) - { - Visit(EnterTypeParameterDeclaration, LeaveTypeParameterDeclaration, typeParameterDeclaration); - } - - public event Action EnterEnumMemberDeclaration, LeaveEnumMemberDeclaration; - - void IAstVisitor.VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration) - { - Visit(EnterEnumMemberDeclaration, LeaveEnumMemberDeclaration, enumMemberDeclaration); - } - - public event Action EnterUsingDeclaration, LeaveUsingDeclaration; - - void IAstVisitor.VisitUsingDeclaration(UsingDeclaration usingDeclaration) - { - Visit(EnterUsingDeclaration, LeaveUsingDeclaration, usingDeclaration); - } - - public event Action EnterUsingAliasDeclaration, LeaveUsingAliasDeclaration; - - void IAstVisitor.VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration) - { - Visit(EnterUsingAliasDeclaration, LeaveUsingAliasDeclaration, usingDeclaration); - } - - public event Action EnterExternAliasDeclaration, LeaveExternAliasDeclaration; - - void IAstVisitor.VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration) - { - Visit(EnterExternAliasDeclaration, LeaveExternAliasDeclaration, externAliasDeclaration); - } - - public event Action EnterConstructorDeclaration, LeaveConstructorDeclaration; - - void IAstVisitor.VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration) - { - Visit(EnterConstructorDeclaration, LeaveConstructorDeclaration, constructorDeclaration); - } - - public event Action EnterConstructorInitializer, LeaveConstructorInitializer; - - void IAstVisitor.VisitConstructorInitializer(ConstructorInitializer constructorInitializer) - { - Visit(EnterConstructorInitializer, LeaveConstructorInitializer, constructorInitializer); - } - - public event Action EnterDestructorDeclaration, LeaveDestructorDeclaration; - - void IAstVisitor.VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration) - { - Visit(EnterDestructorDeclaration, LeaveDestructorDeclaration, destructorDeclaration); - } - - public event Action EnterEventDeclaration, LeaveEventDeclaration; - - void IAstVisitor.VisitEventDeclaration(EventDeclaration eventDeclaration) - { - Visit(EnterEventDeclaration, LeaveEventDeclaration, eventDeclaration); - } - - public event Action EnterCustomEventDeclaration, LeaveCustomEventDeclaration; - - void IAstVisitor.VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration) - { - Visit(EnterCustomEventDeclaration, LeaveCustomEventDeclaration, eventDeclaration); - } - - public event Action EnterFieldDeclaration, LeaveFieldDeclaration; - - void IAstVisitor.VisitFieldDeclaration(FieldDeclaration fieldDeclaration) - { - Visit(EnterFieldDeclaration, LeaveFieldDeclaration, fieldDeclaration); - } - - public event Action EnterFixedFieldDeclaration, LeaveFixedFieldDeclaration; - - void IAstVisitor.VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration) - { - Visit(EnterFixedFieldDeclaration, LeaveFixedFieldDeclaration, fixedFieldDeclaration); - } - - public event Action EnterFixedVariableInitializer, LeaveFixedVariableInitializer; - - void IAstVisitor.VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer) - { - Visit(EnterFixedVariableInitializer, LeaveFixedVariableInitializer, fixedVariableInitializer); - } - - public event Action EnterIndexerDeclaration, LeaveIndexerDeclaration; - - void IAstVisitor.VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration) - { - Visit(EnterIndexerDeclaration, LeaveIndexerDeclaration, indexerDeclaration); - } - - public event Action EnterMethodDeclaration, LeaveMethodDeclaration; - - void IAstVisitor.VisitMethodDeclaration(MethodDeclaration methodDeclaration) - { - Visit(EnterMethodDeclaration, LeaveMethodDeclaration, methodDeclaration); - } - - public event Action EnterOperatorDeclaration, LeaveOperatorDeclaration; - - void IAstVisitor.VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration) - { - Visit(EnterOperatorDeclaration, LeaveOperatorDeclaration, operatorDeclaration); - } - - public event Action EnterPropertyDeclaration, LeavePropertyDeclaration; - - void IAstVisitor.VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration) - { - Visit(EnterPropertyDeclaration, LeavePropertyDeclaration, propertyDeclaration); - } - - public event Action EnterAccessor, LeaveAccessor; - - void IAstVisitor.VisitAccessor(Accessor accessor) - { - Visit(EnterAccessor, LeaveAccessor, accessor); - } - - public event Action EnterVariableInitializer, LeaveVariableInitializer; - - void IAstVisitor.VisitVariableInitializer(VariableInitializer variableInitializer) - { - Visit(EnterVariableInitializer, LeaveVariableInitializer, variableInitializer); - } - - public event Action EnterParameterDeclaration, LeaveParameterDeclaration; - - void IAstVisitor.VisitParameterDeclaration(ParameterDeclaration parameterDeclaration) - { - Visit(EnterParameterDeclaration, LeaveParameterDeclaration, parameterDeclaration); - } - - public event Action EnterConstraint, LeaveConstraint; - - void IAstVisitor.VisitConstraint(Constraint constraint) - { - Visit(EnterConstraint, LeaveConstraint, constraint); - } - - public event Action EnterBlockStatement, LeaveBlockStatement; - - void IAstVisitor.VisitBlockStatement(BlockStatement blockStatement) - { - Visit(EnterBlockStatement, LeaveBlockStatement, blockStatement); - } - - public event Action EnterExpressionStatement, LeaveExpressionStatement; - - void IAstVisitor.VisitExpressionStatement(ExpressionStatement expressionStatement) - { - Visit(EnterExpressionStatement, LeaveExpressionStatement, expressionStatement); - } - - public event Action EnterBreakStatement, LeaveBreakStatement; - - void IAstVisitor.VisitBreakStatement(BreakStatement breakStatement) - { - Visit(EnterBreakStatement, LeaveBreakStatement, breakStatement); - } - - public event Action EnterCheckedStatement, LeaveCheckedStatement; - - void IAstVisitor.VisitCheckedStatement(CheckedStatement checkedStatement) - { - Visit(EnterCheckedStatement, LeaveCheckedStatement, checkedStatement); - } - - public event Action EnterContinueStatement, LeaveContinueStatement; - - void IAstVisitor.VisitContinueStatement(ContinueStatement continueStatement) - { - Visit(EnterContinueStatement, LeaveContinueStatement, continueStatement); - } - - public event Action EnterDoWhileStatement, LeaveDoWhileStatement; - - void IAstVisitor.VisitDoWhileStatement(DoWhileStatement doWhileStatement) - { - Visit(EnterDoWhileStatement, LeaveDoWhileStatement, doWhileStatement); - } - - public event Action EnterEmptyStatement, LeaveEmptyStatement; - - void IAstVisitor.VisitEmptyStatement(EmptyStatement emptyStatement) - { - Visit(EnterEmptyStatement, LeaveEmptyStatement, emptyStatement); - } - - public event Action EnterFixedStatement, LeaveFixedStatement; - - void IAstVisitor.VisitFixedStatement(FixedStatement fixedStatement) - { - Visit(EnterFixedStatement, LeaveFixedStatement, fixedStatement); - } - - public event Action EnterForeachStatement, LeaveForeachStatement; - - void IAstVisitor.VisitForeachStatement(ForeachStatement foreachStatement) - { - Visit(EnterForeachStatement, LeaveForeachStatement, foreachStatement); - } - - public event Action EnterForStatement, LeaveForStatement; - - void IAstVisitor.VisitForStatement(ForStatement forStatement) - { - Visit(EnterForStatement, LeaveForStatement, forStatement); - } - - public event Action EnterGotoCaseStatement, LeaveGotoCaseStatement; - - void IAstVisitor.VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement) - { - Visit(EnterGotoCaseStatement, LeaveGotoCaseStatement, gotoCaseStatement); - } - - public event Action EnterGotoDefaultStatement, LeaveGotoDefaultStatement; - - void IAstVisitor.VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement) - { - Visit(EnterGotoDefaultStatement, LeaveGotoDefaultStatement, gotoDefaultStatement); - } - - public event Action EnterGotoStatement, LeaveGotoStatement; - - void IAstVisitor.VisitGotoStatement(GotoStatement gotoStatement) - { - Visit(EnterGotoStatement, LeaveGotoStatement, gotoStatement); - } - - public event Action EnterIfElseStatement, LeaveIfElseStatement; - - void IAstVisitor.VisitIfElseStatement(IfElseStatement ifElseStatement) - { - Visit(EnterIfElseStatement, LeaveIfElseStatement, ifElseStatement); - } - - public event Action EnterLabelStatement, LeaveLabelStatement; - - void IAstVisitor.VisitLabelStatement(LabelStatement labelStatement) - { - Visit(EnterLabelStatement, LeaveLabelStatement, labelStatement); - } - - public event Action EnterLockStatement, LeaveLockStatement; - - void IAstVisitor.VisitLockStatement(LockStatement lockStatement) - { - Visit(EnterLockStatement, LeaveLockStatement, lockStatement); - } - - public event Action EnterReturnStatement, LeaveReturnStatement; - - void IAstVisitor.VisitReturnStatement(ReturnStatement returnStatement) - { - Visit(EnterReturnStatement, LeaveReturnStatement, returnStatement); - } - - public event Action EnterSwitchStatement, LeaveSwitchStatement; - - void IAstVisitor.VisitSwitchStatement(SwitchStatement switchStatement) - { - Visit(EnterSwitchStatement, LeaveSwitchStatement, switchStatement); - } - - public event Action EnterSwitchSection, LeaveSwitchSection; - - void IAstVisitor.VisitSwitchSection(SwitchSection switchSection) - { - Visit(EnterSwitchSection, LeaveSwitchSection, switchSection); - } - - public event Action EnterCaseLabel, LeaveCaseLabel; - - void IAstVisitor.VisitCaseLabel(CaseLabel caseLabel) - { - Visit(EnterCaseLabel, LeaveCaseLabel, caseLabel); - } - - public event Action EnterThrowStatement, LeaveThrowStatement; - - void IAstVisitor.VisitThrowStatement(ThrowStatement throwStatement) - { - Visit(EnterThrowStatement, LeaveThrowStatement, throwStatement); - } - - public event Action EnterTryCatchStatement, LeaveTryCatchStatement; - - void IAstVisitor.VisitTryCatchStatement(TryCatchStatement tryCatchStatement) - { - Visit(EnterTryCatchStatement, LeaveTryCatchStatement, tryCatchStatement); - } - - public event Action EnterCatchClause, LeaveCatchClause; - - void IAstVisitor.VisitCatchClause(CatchClause catchClause) - { - Visit(EnterCatchClause, LeaveCatchClause, catchClause); - } - - public event Action EnterUncheckedStatement, LeaveUncheckedStatement; - - void IAstVisitor.VisitUncheckedStatement(UncheckedStatement uncheckedStatement) - { - Visit(EnterUncheckedStatement, LeaveUncheckedStatement, uncheckedStatement); - } - - public event Action EnterUnsafeStatement, LeaveUnsafeStatement; - - void IAstVisitor.VisitUnsafeStatement(UnsafeStatement unsafeStatement) - { - Visit(EnterUnsafeStatement, LeaveUnsafeStatement, unsafeStatement); - } - - public event Action EnterUsingStatement, LeaveUsingStatement; - - void IAstVisitor.VisitUsingStatement(UsingStatement usingStatement) - { - Visit(EnterUsingStatement, LeaveUsingStatement, usingStatement); - } - - public event Action EnterVariableDeclarationStatement, LeaveVariableDeclarationStatement; - - void IAstVisitor.VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement) - { - Visit(EnterVariableDeclarationStatement, LeaveVariableDeclarationStatement, variableDeclarationStatement); - } - - public event Action EnterWhileStatement, LeaveWhileStatement; - - void IAstVisitor.VisitWhileStatement(WhileStatement whileStatement) - { - Visit(EnterWhileStatement, LeaveWhileStatement, whileStatement); - } - - public event Action EnterYieldBreakStatement, LeaveYieldBreakStatement; - - void IAstVisitor.VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement) - { - Visit(EnterYieldBreakStatement, LeaveYieldBreakStatement, yieldBreakStatement); - } - - public event Action EnterYieldReturnStatement, LeaveYieldReturnStatement; - - void IAstVisitor.VisitYieldReturnStatement(YieldReturnStatement yieldStatement) - { - Visit(EnterYieldReturnStatement, LeaveYieldReturnStatement, yieldStatement); - } - - public event Action EnterAnonymousMethodExpression, LeaveAnonymousMethodExpression; - - void IAstVisitor.VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression) - { - Visit(EnterAnonymousMethodExpression, LeaveAnonymousMethodExpression, anonymousMethodExpression); - } - - public event Action EnterLambdaExpression, LeaveLambdaExpression; - - void IAstVisitor.VisitLambdaExpression(LambdaExpression lambdaExpression) - { - Visit(EnterLambdaExpression, LeaveLambdaExpression, lambdaExpression); - } - - public event Action EnterAssignmentExpression, LeaveAssignmentExpression; - - void IAstVisitor.VisitAssignmentExpression(AssignmentExpression assignmentExpression) - { - Visit(EnterAssignmentExpression, LeaveAssignmentExpression, assignmentExpression); - } - - public event Action EnterBaseReferenceExpression, LeaveBaseReferenceExpression; - - void IAstVisitor.VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression) - { - Visit(EnterBaseReferenceExpression, LeaveBaseReferenceExpression, baseReferenceExpression); - } - - public event Action EnterBinaryOperatorExpression, LeaveBinaryOperatorExpression; - - void IAstVisitor.VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression) - { - Visit(EnterBinaryOperatorExpression, LeaveBinaryOperatorExpression, binaryOperatorExpression); - } - - public event Action EnterCastExpression, LeaveCastExpression; - - void IAstVisitor.VisitCastExpression(CastExpression castExpression) - { - Visit(EnterCastExpression, LeaveCastExpression, castExpression); - } - - public event Action EnterCheckedExpression, LeaveCheckedExpression; - - void IAstVisitor.VisitCheckedExpression(CheckedExpression checkedExpression) - { - Visit(EnterCheckedExpression, LeaveCheckedExpression, checkedExpression); - } - - public event Action EnterConditionalExpression, LeaveConditionalExpression; - - void IAstVisitor.VisitConditionalExpression(ConditionalExpression conditionalExpression) - { - Visit(EnterConditionalExpression, LeaveConditionalExpression, conditionalExpression); - } - - public event Action EnterIdentifierExpression, LeaveIdentifierExpression; - - void IAstVisitor.VisitIdentifierExpression(IdentifierExpression identifierExpression) - { - Visit(EnterIdentifierExpression, LeaveIdentifierExpression, identifierExpression); - } - - public event Action EnterIndexerExpression, LeaveIndexerExpression; - - void IAstVisitor.VisitIndexerExpression(IndexerExpression indexerExpression) - { - Visit(EnterIndexerExpression, LeaveIndexerExpression, indexerExpression); - } - - public event Action EnterInvocationExpression, LeaveInvocationExpression; - - void IAstVisitor.VisitInvocationExpression(InvocationExpression invocationExpression) - { - Visit(EnterInvocationExpression, LeaveInvocationExpression, invocationExpression); - } - - public event Action EnterDirectionExpression, LeaveDirectionExpression; - - void IAstVisitor.VisitDirectionExpression(DirectionExpression directionExpression) - { - Visit(EnterDirectionExpression, LeaveDirectionExpression, directionExpression); - } - - public event Action EnterMemberReferenceExpression, LeaveMemberReferenceExpression; - - void IAstVisitor.VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression) - { - Visit(EnterMemberReferenceExpression, LeaveMemberReferenceExpression, memberReferenceExpression); - } - - public event Action EnterNullReferenceExpression, LeaveNullReferenceExpression; - - void IAstVisitor.VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression) - { - Visit(EnterNullReferenceExpression, LeaveNullReferenceExpression, nullReferenceExpression); - } - - public event Action EnterObjectCreateExpression, LeaveObjectCreateExpression; - - void IAstVisitor.VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression) - { - Visit(EnterObjectCreateExpression, LeaveObjectCreateExpression, objectCreateExpression); - } - - public event Action EnterAnonymousTypeCreateExpression, LeaveAnonymousTypeCreateExpression; - - void IAstVisitor.VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression) - { - Visit(EnterAnonymousTypeCreateExpression, LeaveAnonymousTypeCreateExpression, anonymousTypeCreateExpression); - } - - public event Action EnterArrayCreateExpression, LeaveArrayCreateExpression; - - void IAstVisitor.VisitArrayCreateExpression(ArrayCreateExpression arraySCreateExpression) - { - Visit(EnterArrayCreateExpression, LeaveArrayCreateExpression, arraySCreateExpression); - } - - public event Action EnterParenthesizedExpression, LeaveParenthesizedExpression; - - void IAstVisitor.VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression) - { - Visit(EnterParenthesizedExpression, LeaveParenthesizedExpression, parenthesizedExpression); - } - - public event Action EnterPointerReferenceExpression, LeavePointerReferenceExpression; - - void IAstVisitor.VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression) - { - Visit(EnterPointerReferenceExpression, LeavePointerReferenceExpression, pointerReferenceExpression); - } - - public event Action EnterPrimitiveExpression, LeavePrimitiveExpression; - - void IAstVisitor.VisitPrimitiveExpression(PrimitiveExpression primitiveExpression) - { - Visit(EnterPrimitiveExpression, LeavePrimitiveExpression, primitiveExpression); - } - - public event Action EnterSizeOfExpression, LeaveSizeOfExpression; - - void IAstVisitor.VisitSizeOfExpression(SizeOfExpression sizeOfExpression) - { - Visit(EnterSizeOfExpression, LeaveSizeOfExpression, sizeOfExpression); - } - - public event Action EnterStackAllocExpression, LeaveStackAllocExpression; - - void IAstVisitor.VisitStackAllocExpression(StackAllocExpression stackAllocExpression) - { - Visit(EnterStackAllocExpression, LeaveStackAllocExpression, stackAllocExpression); - } - - public event Action EnterThisReferenceExpression, LeaveThisReferenceExpression; - - void IAstVisitor.VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression) - { - Visit(EnterThisReferenceExpression, LeaveThisReferenceExpression, thisReferenceExpression); - } - - public event Action EnterTypeOfExpression, LeaveTypeOfExpression; - - void IAstVisitor.VisitTypeOfExpression(TypeOfExpression typeOfExpression) - { - Visit(EnterTypeOfExpression, LeaveTypeOfExpression, typeOfExpression); - } - - public event Action EnterTypeReferenceExpression, LeaveTypeReferenceExpression; - - void IAstVisitor.VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression) - { - Visit(EnterTypeReferenceExpression, LeaveTypeReferenceExpression, typeReferenceExpression); - } - - public event Action EnterUnaryOperatorExpression, LeaveUnaryOperatorExpression; - - void IAstVisitor.VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression) - { - Visit(EnterUnaryOperatorExpression, LeaveUnaryOperatorExpression, unaryOperatorExpression); - } - - public event Action EnterUncheckedExpression, LeaveUncheckedExpression; - - void IAstVisitor.VisitUncheckedExpression(UncheckedExpression uncheckedExpression) - { - Visit(EnterUncheckedExpression, LeaveUncheckedExpression, uncheckedExpression); - } - - public event Action EnterQueryExpression, LeaveQueryExpression; - - void IAstVisitor.VisitQueryExpression(QueryExpression queryExpression) - { - Visit(EnterQueryExpression, LeaveQueryExpression, queryExpression); - } - - public event Action EnterQueryContinuationClause, LeaveQueryContinuationClause; - - void IAstVisitor.VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause) - { - Visit(EnterQueryContinuationClause, LeaveQueryContinuationClause, queryContinuationClause); - } - - public event Action EnterQueryFromClause, LeaveQueryFromClause; - - void IAstVisitor.VisitQueryFromClause(QueryFromClause queryFromClause) - { - Visit(EnterQueryFromClause, LeaveQueryFromClause, queryFromClause); - } - - public event Action EnterQueryLetClause, LeaveQueryLetClause; - - void IAstVisitor.VisitQueryLetClause(QueryLetClause queryLetClause) - { - Visit(EnterQueryLetClause, LeaveQueryLetClause, queryLetClause); - } - - public event Action EnterQueryWhereClause, LeaveQueryWhereClause; - - void IAstVisitor.VisitQueryWhereClause(QueryWhereClause queryWhereClause) - { - Visit(EnterQueryWhereClause, LeaveQueryWhereClause, queryWhereClause); - } - - public event Action EnterQueryJoinClause, LeaveQueryJoinClause; - - void IAstVisitor.VisitQueryJoinClause(QueryJoinClause queryJoinClause) - { - Visit(EnterQueryJoinClause, LeaveQueryJoinClause, queryJoinClause); - } - - public event Action EnterQueryOrderClause, LeaveQueryOrderClause; - - void IAstVisitor.VisitQueryOrderClause(QueryOrderClause queryOrderClause) - { - Visit(EnterQueryOrderClause, LeaveQueryOrderClause, queryOrderClause); - } - - public event Action EnterQueryOrdering, LeaveQueryOrdering; - - void IAstVisitor.VisitQueryOrdering(QueryOrdering queryOrdering) - { - Visit(EnterQueryOrdering, LeaveQueryOrdering, queryOrdering); - } - - public event Action EnterQuerySelectClause, LeaveQuerySelectClause; - - void IAstVisitor.VisitQuerySelectClause(QuerySelectClause querySelectClause) - { - Visit(EnterQuerySelectClause, LeaveQuerySelectClause, querySelectClause); - } - - public event Action EnterQueryGroupClause, LeaveQueryGroupClause; - - void IAstVisitor.VisitQueryGroupClause(QueryGroupClause queryGroupClause) - { - Visit(EnterQueryGroupClause, LeaveQueryGroupClause, queryGroupClause); - } - - public event Action EnterAsExpression, LeaveAsExpression; - - void IAstVisitor.VisitAsExpression(AsExpression asExpression) - { - Visit(EnterAsExpression, LeaveAsExpression, asExpression); - } - - public event Action EnterIsExpression, LeaveIsExpression; - - void IAstVisitor.VisitIsExpression(IsExpression isExpression) - { - Visit(EnterIsExpression, LeaveIsExpression, isExpression); - } - - public event Action EnterDefaultValueExpression, LeaveDefaultValueExpression; - - void IAstVisitor.VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression) - { - Visit(EnterDefaultValueExpression, LeaveDefaultValueExpression, defaultValueExpression); - } - - public event Action EnterUndocumentedExpression, LeaveUndocumentedExpression; - - void IAstVisitor.VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression) - { - Visit(EnterUndocumentedExpression, LeaveUndocumentedExpression, undocumentedExpression); - } - - public event Action EnterArrayInitializerExpression, LeaveArrayInitializerExpression; - - void IAstVisitor.VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression) - { - Visit(EnterArrayInitializerExpression, LeaveArrayInitializerExpression, arrayInitializerExpression); - } - - public event Action EnterArraySpecifier, LeaveArraySpecifier; - - void IAstVisitor.VisitArraySpecifier(ArraySpecifier arraySpecifier) - { - Visit(EnterArraySpecifier, LeaveArraySpecifier, arraySpecifier); - } - - public event Action EnterNamedArgumentExpression, LeaveNamedArgumentExpression; - - void IAstVisitor.VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression) - { - Visit(EnterNamedArgumentExpression, LeaveNamedArgumentExpression, namedArgumentExpression); - } - - public event Action EnterNamedExpression, LeaveNamedExpression; - - void IAstVisitor.VisitNamedExpression(NamedExpression namedExpression) - { - Visit(EnterNamedExpression, LeaveNamedExpression, namedExpression); - } - - void IAstVisitor.VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern) - { - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/PrimitiveType.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/PrimitiveType.cs deleted file mode 100644 index 5b52a37ac..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/PrimitiveType.cs +++ /dev/null @@ -1,163 +0,0 @@ -// -// FullTypeName.cs -// -// Author: -// Mike Krüger -// -// 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 (IAstVisitor visitor) - { - return visitor.VisitPrimitiveType (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Roles.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Roles.cs deleted file mode 100644 index a7408c91d..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Roles.cs +++ /dev/null @@ -1,96 +0,0 @@ -// -// Roles.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2012 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; - -namespace ICSharpCode.NRefactory.CSharp -{ - public static class Roles - { - public static readonly Role Root = AstNode.RootRole; - - // some pre defined constants for common roles - public static readonly Role Identifier = new Role ("Identifier", CSharp.Identifier.Null); - public static readonly Role Body = new Role ("Body", CSharp.BlockStatement.Null); - public static readonly Role Parameter = new Role ("Parameter"); - public static readonly Role Argument = new Role ("Argument", CSharp.Expression.Null); - public static readonly Role Type = new Role ("Type", CSharp.AstType.Null); - public static readonly Role Expression = new Role ("Expression", CSharp.Expression.Null); - public static readonly Role TargetExpression = new Role ("Target", CSharp.Expression.Null); - public readonly static Role Condition = new Role ("Condition", CSharp.Expression.Null); - public static readonly Role TypeParameter = new Role ("TypeParameter"); - public static readonly Role TypeArgument = new Role ("TypeArgument", CSharp.AstType.Null); - public readonly static Role Constraint = new Role ("Constraint"); - public static readonly Role Variable = new Role ("Variable", VariableInitializer.Null); - public static readonly Role EmbeddedStatement = new Role ("EmbeddedStatement", CSharp.Statement.Null); - public readonly static Role TypeMemberRole = new Role ("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 = new Role ("Comment"); - public static readonly Role NewLine = new Role ("NewLine"); - public static readonly Role Whitespace = new Role ("Whitespace"); - public static readonly Role Text = new Role ("Text"); - public static readonly Role PreProcessorDirective = new Role ("PreProcessorDirective"); - public static readonly Role Error = new Role ("Error"); - - public readonly static Role BaseType = new Role ("BaseType", AstType.Null); - - public static readonly Role Attribute = new Role ("Attribute"); - public static readonly Role AttributeTargetRole = new Role ("AttributeTarget", CSharpTokenNode.Null); - - public readonly static TokenRole WhereKeyword = new TokenRole ("where"); - public readonly static Role ConstraintTypeParameter = new Role ("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"); - - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SimpleType.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SimpleType.cs deleted file mode 100644 index 529a62fbe..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SimpleType.cs +++ /dev/null @@ -1,169 +0,0 @@ -// -// FullTypeName.cs -// -// Author: -// Mike Krüger -// -// 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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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 typeArguments) - { - this.Identifier = identifier; - foreach (var arg in typeArguments) { - AddChild (arg, Roles.TypeArgument); - } - } - - public SimpleType (string identifier, params AstType[] typeArguments) : this (identifier, (IEnumerable)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 TypeArguments { - get { return GetChildrenByRole (Roles.TypeArgument); } - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitSimpleType (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitSimpleType (this); - } - - public override S AcceptVisitor (IAstVisitor 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(); - 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); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/BlockStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/BlockStatement.cs deleted file mode 100644 index 24b9cd106..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/BlockStatement.cs +++ /dev/null @@ -1,164 +0,0 @@ -// -// BlockStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// { Statements } - /// - public class BlockStatement : Statement, IEnumerable - { - public static readonly Role StatementRole = new Role("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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitPatternPlaceholder(this, child); - } - - public override S AcceptVisitor(IAstVisitor 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 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 (IAstVisitor visitor) - { - return visitor.VisitBlockStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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 IEnumerable.GetEnumerator() - { - return this.Statements.GetEnumerator(); - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return this.Statements.GetEnumerator(); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/BreakStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/BreakStatement.cs deleted file mode 100644 index 4bb4e39ef..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/BreakStatement.cs +++ /dev/null @@ -1,65 +0,0 @@ -// -// BreakStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// break; - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitBreakStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/CheckedStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/CheckedStatement.cs deleted file mode 100644 index 803067aff..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/CheckedStatement.cs +++ /dev/null @@ -1,75 +0,0 @@ -// -// CheckedStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// checked BodyBlock - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitCheckedStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ContinueStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ContinueStatement.cs deleted file mode 100644 index aac1690b2..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ContinueStatement.cs +++ /dev/null @@ -1,65 +0,0 @@ -// -// ContinueStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// continue; - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitContinueStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/DoWhileStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/DoWhileStatement.cs deleted file mode 100644 index 280ca7cea..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/DoWhileStatement.cs +++ /dev/null @@ -1,99 +0,0 @@ -// -// DoWhileStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// "do EmbeddedStatement while(Condition);" - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitDoWhileStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/EmptyStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/EmptyStatement.cs deleted file mode 100644 index deaa3a9c4..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/EmptyStatement.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// EmptyStatement.cs -// -// Author: -// Mike Krüger -// -// 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 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 (IAstVisitor visitor) - { - return visitor.VisitEmptyStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ExpressionStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ExpressionStatement.cs deleted file mode 100644 index 1fdc4ddc4..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ExpressionStatement.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -// ExpressionStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Expression; - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitExpressionStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/FixedStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/FixedStatement.cs deleted file mode 100644 index d44366504..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/FixedStatement.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -// FixedStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// fixed (Type Variables) EmbeddedStatement - /// - 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 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 (IAstVisitor visitor) - { - return visitor.VisitFixedStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ForStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ForStatement.cs deleted file mode 100644 index d369536d0..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ForStatement.cs +++ /dev/null @@ -1,97 +0,0 @@ -// -// ForStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// for (Initializers; Condition; Iterators) EmbeddedStatement - /// - public class ForStatement : Statement - { - public static readonly TokenRole ForKeywordRole = new TokenRole ("for"); - public readonly static Role InitializerRole = new Role("Initializer", Statement.Null); - public readonly static Role IteratorRole = new Role("Iterator", Statement.Null); - - public CSharpTokenNode ForToken { - get { return GetChildByRole (ForKeywordRole); } - } - - public CSharpTokenNode LParToken { - get { return GetChildByRole (Roles.LPar); } - } - - /// - /// 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) - /// - public AstNodeCollection Initializers { - get { return GetChildrenByRole (InitializerRole); } - } - - public Expression Condition { - get { return GetChildByRole (Roles.Condition); } - set { SetChildByRole (Roles.Condition, value); } - } - - public AstNodeCollection 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 (IAstVisitor visitor) - { - return visitor.VisitForStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ForeachStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ForeachStatement.cs deleted file mode 100644 index b3a9c5f78..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ForeachStatement.cs +++ /dev/null @@ -1,108 +0,0 @@ -// -// ForeachStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// foreach (Type VariableName in InExpression) EmbeddedStatement - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitForeachStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/GotoStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/GotoStatement.cs deleted file mode 100644 index 7aff7a82f..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/GotoStatement.cs +++ /dev/null @@ -1,178 +0,0 @@ -// -// GotoStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// "goto Label;" - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitGotoStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } - - /// - /// or "goto case LabelExpression;" - /// - 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); } - } - - /// - /// Used for "goto case LabelExpression;" - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitGotoCaseStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } - - /// - /// or "goto default;" - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitGotoDefaultStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/IfElseStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/IfElseStatement.cs deleted file mode 100644 index 70ece3fd5..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/IfElseStatement.cs +++ /dev/null @@ -1,103 +0,0 @@ -// -// IfElseStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// if (Condition) TrueStatement else FalseStatement - /// - public class IfElseStatement : Statement - { - public readonly static TokenRole IfKeywordRole = new TokenRole ("if"); - public readonly static Role ConditionRole = Roles.Condition; - public readonly static Role TrueRole = new Role("True", Statement.Null); - public readonly static TokenRole ElseKeywordRole = new TokenRole ("else"); - public readonly static Role FalseRole = new Role("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 (IAstVisitor visitor) - { - return visitor.VisitIfElseStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/LabelStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/LabelStatement.cs deleted file mode 100644 index 43d22cea7..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/LabelStatement.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -// LabelStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Label: - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitLabelStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/LockStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/LockStatement.cs deleted file mode 100644 index e59f99308..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/LockStatement.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -// LockStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// lock (Expression) EmbeddedStatement; - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitLockStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ReturnStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ReturnStatement.cs deleted file mode 100644 index 0970bce43..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ReturnStatement.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -// ReturnStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// return Expression; - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitReturnStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/Statement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/Statement.cs deleted file mode 100644 index 24d3ede92..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/Statement.cs +++ /dev/null @@ -1,132 +0,0 @@ -// 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 -{ - /// - /// Base class for statements. - /// - /// - /// 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" - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitPatternPlaceholder(this, child); - } - - public override S AcceptVisitor(IAstVisitor 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 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/SwitchStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/SwitchStatement.cs deleted file mode 100644 index fa8e80cd5..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/SwitchStatement.cs +++ /dev/null @@ -1,230 +0,0 @@ -// -// SwitchStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// switch (Expression) { SwitchSections } - /// - public class SwitchStatement : Statement - { - public static readonly TokenRole SwitchKeywordRole = new TokenRole ("switch"); - public static readonly Role SwitchSectionRole = new Role("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 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 (IAstVisitor visitor) - { - return visitor.VisitSwitchStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitPatternPlaceholder(this, child); - } - - public override S AcceptVisitor(IAstVisitor 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 CaseLabelRole = new Role("CaseLabel"); - - public override NodeType NodeType { - get { - return NodeType.Unknown; - } - } - - public AstNodeCollection CaseLabels { - get { return GetChildrenByRole (CaseLabelRole); } - } - - public AstNodeCollection Statements { - get { return GetChildrenByRole (Roles.EmbeddedStatement); } - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitSwitchSection (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitSwitchSection (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } - - /// - /// Gets or sets the expression. The expression can be null - if the expression is null, it's the default switch section. - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitCaseLabel (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ThrowStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ThrowStatement.cs deleted file mode 100644 index 98e27d1e7..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/ThrowStatement.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -// ThrowStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// throw Expression; - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitThrowStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/TryCatchStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/TryCatchStatement.cs deleted file mode 100644 index 3611574b7..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/TryCatchStatement.cs +++ /dev/null @@ -1,241 +0,0 @@ -// -// TryCatchStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// try TryBlock CatchClauses finally FinallyBlock - /// - public class TryCatchStatement : Statement - { - public static readonly TokenRole TryKeywordRole = new TokenRole ("try"); - public static readonly Role TryBlockRole = new Role("TryBlock", BlockStatement.Null); - public static readonly Role CatchClauseRole = new Role("CatchClause", CatchClause.Null); - public static readonly TokenRole FinallyKeywordRole = new TokenRole ("finally"); - public static readonly Role FinallyBlockRole = new Role("FinallyBlock", BlockStatement.Null); - - public CSharpTokenNode TryToken { - get { return GetChildByRole (TryKeywordRole); } - } - - public BlockStatement TryBlock { - get { return GetChildByRole (TryBlockRole); } - set { SetChildByRole (TryBlockRole, value); } - } - - public AstNodeCollection 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 (IAstVisitor visitor) - { - return visitor.VisitTryCatchStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } - - /// - /// catch (Type VariableName) { Body } - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitPatternPlaceholder(this, child); - } - - public override S AcceptVisitor(IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitCatchClause (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/UncheckedStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/UncheckedStatement.cs deleted file mode 100644 index 765cd9ab3..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/UncheckedStatement.cs +++ /dev/null @@ -1,75 +0,0 @@ -// -// UncheckedStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// unchecked BodyBlock - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitUncheckedStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/UnsafeStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/UnsafeStatement.cs deleted file mode 100644 index fa6421ae6..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/UnsafeStatement.cs +++ /dev/null @@ -1,66 +0,0 @@ -// -// UnsafeStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// unsafe { Body } - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitUnsafeStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/UsingStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/UsingStatement.cs deleted file mode 100644 index c87304675..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/UsingStatement.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -// UsingStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// using (ResourceAcquisition) EmbeddedStatement - /// - public class UsingStatement : Statement - { - public static readonly TokenRole UsingKeywordRole = new TokenRole ("using"); - public static readonly Role ResourceAcquisitionRole = new Role("ResourceAcquisition", AstNode.Null); - - public CSharpTokenNode UsingToken { - get { return GetChildByRole (UsingKeywordRole); } - } - - public CSharpTokenNode LParToken { - get { return GetChildByRole (Roles.LPar); } - } - - /// - /// Either a VariableDeclarationStatement, or an Expression. - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitUsingStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/VariableDeclarationStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/VariableDeclarationStatement.cs deleted file mode 100644 index 32c141d96..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/VariableDeclarationStatement.cs +++ /dev/null @@ -1,90 +0,0 @@ -// -// VariableDeclarationStatement.cs -// -// Author: -// Mike Krüger -// -// 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 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 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 (IAstVisitor visitor) - { - return visitor.VisitVariableDeclarationStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/WhileStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/WhileStatement.cs deleted file mode 100644 index e38daa144..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/WhileStatement.cs +++ /dev/null @@ -1,89 +0,0 @@ -// -// WhileStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// "while (Condition) EmbeddedStatement" - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitWhileStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/YieldBreakStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/YieldBreakStatement.cs deleted file mode 100644 index ea5cac4a6..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/YieldBreakStatement.cs +++ /dev/null @@ -1,70 +0,0 @@ -// -// YieldBreakStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// yield break; - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitYieldBreakStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/YieldReturnStatement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/YieldReturnStatement.cs deleted file mode 100644 index 6539bf0c0..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/YieldReturnStatement.cs +++ /dev/null @@ -1,75 +0,0 @@ -// -// YieldStatement.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// yield return Expression; - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitYieldReturnStatement (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SyntaxExtensions.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SyntaxExtensions.cs deleted file mode 100644 index bac28bb76..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SyntaxExtensions.cs +++ /dev/null @@ -1,45 +0,0 @@ -// 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 -{ - /// - /// Extension methods for the syntax tree. - /// - 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; - } - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SyntaxTree.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SyntaxTree.cs deleted file mode 100644 index 6ac536159..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SyntaxTree.cs +++ /dev/null @@ -1,193 +0,0 @@ -// -// SyntaxTree.cs -// -// Author: -// Mike Krüger -// -// 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 MemberRole = new Role("Member", AstNode.Null); - - public override NodeType NodeType { - get { - return NodeType.Unknown; - } - } - - string fileName; - - /// - /// Gets/Sets the file name of this syntax tree. - /// - public string FileName { - get { return fileName; } - set { - ThrowIfFrozen(); - fileName = value; - } - } - - public AstNodeCollection Members { - get { return GetChildrenByRole(MemberRole); } - } - - IList conditionalSymbols = null; - - List errors = new List (); - - public List Errors { - get { return errors; } - } - - - /// - /// 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. - /// - public IList ConditionalSymbols { - get { - return conditionalSymbols ?? EmptyList.Instance; - } - internal set { - conditionalSymbols = value; - } - } - - /// - /// 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 ., <, ('. - /// - public AstNode TopExpression { - get; - internal set; - } - - public SyntaxTree () - { - } - - /// - /// Gets all defined types in this syntax tree. - /// - /// - /// A list containing or nodes. - /// - public IEnumerable GetTypes(bool includeInnerTypes = false) - { - Stack nodeStack = new Stack (); - 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 (IAstVisitor visitor) - { - return visitor.VisitSyntaxTree (this); - } - - public override S AcceptVisitor (IAstVisitor visitor, T data) - { - return visitor.VisitSyntaxTree (this, data); - } - - /// - /// Converts this syntax tree into a parsed file that can be stored in the type system. - /// - 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TokenRole.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TokenRole.cs deleted file mode 100644 index 8c9c7392a..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TokenRole.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace ICSharpCode.NRefactory.CSharp -{ - /// - /// A specific role only used for C# tokens - /// - public sealed class TokenRole : Role - { - internal readonly static List Tokens = new List (); - internal readonly static List TokenLengths = new List (); - internal readonly uint TokenIndex; - - static TokenRole () - { - // null token - Tokens.Add (""); - TokenLengths.Add (0); - } - - /// - /// Gets the token as string. Note that the token Name and Token value may differ. - /// - public string Token { - get; - private set; - } - - /// - /// Gets the char length of the token. - /// - 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); - } - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/Accessor.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/Accessor.cs deleted file mode 100644 index 8bd18c477..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/Accessor.cs +++ /dev/null @@ -1,117 +0,0 @@ -// -// PropertyDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// get/set/add/remove - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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; } - } - - /// - /// Gets the 'get'/'set'/'add'/'remove' keyword - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitAccessor (this); - } - - public override S AcceptVisitor(IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/ConstructorDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/ConstructorDeclaration.cs deleted file mode 100644 index 23a973a5c..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/ConstructorDeclaration.cs +++ /dev/null @@ -1,190 +0,0 @@ -// -// ConstructorDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 InitializerRole = new Role("Initializer", ConstructorInitializer.Null); - - public override SymbolKind SymbolKind { - get { return SymbolKind.Constructor; } - } - - public CSharpTokenNode LParToken { - get { return GetChildByRole (Roles.LPar); } - } - - public AstNodeCollection 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 (IAstVisitor visitor) - { - return visitor.VisitConstructorDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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 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 (IAstVisitor visitor) - { - return visitor.VisitConstructorInitializer (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/DestructorDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/DestructorDeclaration.cs deleted file mode 100644 index 0609e5dc6..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/DestructorDeclaration.cs +++ /dev/null @@ -1,76 +0,0 @@ -// -// DestructorDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 (IAstVisitor visitor) - { - return visitor.VisitDestructorDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/EntityDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/EntityDeclaration.cs deleted file mode 100644 index c02ff21b6..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/EntityDeclaration.cs +++ /dev/null @@ -1,117 +0,0 @@ -// 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 AttributeRole = new Role("Attribute"); - public static readonly Role UnattachedAttributeRole = new Role("UnattachedAttribute"); - public static readonly Role ModifierRole = new Role("Modifier"); - public static readonly Role PrivateImplementationTypeRole = new Role("PrivateImplementationType", AstType.Null); - - public override NodeType NodeType { - get { return NodeType.Member; } - } - - public abstract NRefactory.TypeSystem.SymbolKind SymbolKind { get; } - - public AstNodeCollection 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 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/EnumMemberDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/EnumMemberDeclaration.cs deleted file mode 100644 index b7c924ab9..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/EnumMemberDeclaration.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// EnumMemberDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 InitializerRole = new Role("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 (IAstVisitor visitor) - { - return visitor.VisitEnumMemberDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/EventDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/EventDeclaration.cs deleted file mode 100644 index d543f9ea7..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/EventDeclaration.cs +++ /dev/null @@ -1,152 +0,0 @@ -// -// EventDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 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 (IAstVisitor visitor) - { - return visitor.VisitEventDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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 AddAccessorRole = new Role("AddAccessor", Accessor.Null); - public static readonly Role RemoveAccessorRole = new Role("RemoveAccessor", Accessor.Null); - - public override SymbolKind SymbolKind { - get { return SymbolKind.Event; } - } - - /// - /// Gets/Sets the type reference of the interface that is explicitly implemented. - /// Null node if this member is not an explicit interface implementation. - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitCustomEventDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/FieldDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/FieldDeclaration.cs deleted file mode 100644 index de220ecd7..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/FieldDeclaration.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -// FieldDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 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 (IAstVisitor visitor) - { - return visitor.VisitFieldDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/FixedFieldDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/FixedFieldDeclaration.cs deleted file mode 100644 index fea2a2af2..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/FixedFieldDeclaration.cs +++ /dev/null @@ -1,71 +0,0 @@ -// -// FixedFieldDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 VariableRole = new Role ("FixedVariable"); - - public override SymbolKind SymbolKind { - get { return SymbolKind.Field; } - } - - public CSharpTokenNode FixedToken { - get { return GetChildByRole (FixedKeywordRole); } - } - - public AstNodeCollection Variables { - get { return GetChildrenByRole (VariableRole); } - } - - public override void AcceptVisitor (IAstVisitor visitor) - { - visitor.VisitFixedFieldDeclaration (this); - } - - public override T AcceptVisitor (IAstVisitor visitor) - { - return visitor.VisitFixedFieldDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/FixedVariableInitializer.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/FixedVariableInitializer.cs deleted file mode 100644 index 2c320a826..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/FixedVariableInitializer.cs +++ /dev/null @@ -1,105 +0,0 @@ -// -// FixedFieldDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// Name [ CountExpression ] - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitFixedVariableInitializer (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/IndexerDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/IndexerDeclaration.cs deleted file mode 100644 index 56156dd19..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/IndexerDeclaration.cs +++ /dev/null @@ -1,122 +0,0 @@ -// -// IndexerDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 GetterRole = PropertyDeclaration.GetterRole; - public static readonly Role SetterRole = PropertyDeclaration.SetterRole; - - public override SymbolKind SymbolKind { - get { return SymbolKind.Indexer; } - } - - /// - /// Gets/Sets the type reference of the interface that is explicitly implemented. - /// Null node if this member is not an explicit interface implementation. - /// - 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 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 (IAstVisitor visitor) - { - return visitor.VisitIndexerDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/MethodDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/MethodDeclaration.cs deleted file mode 100644 index 90aaa3047..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/MethodDeclaration.cs +++ /dev/null @@ -1,104 +0,0 @@ -// -// MethodDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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; } - } - - /// - /// Gets/Sets the type reference of the interface that is explicitly implemented. - /// Null node if this member is not an explicit interface implementation. - /// - public AstType PrivateImplementationType { - get { return GetChildByRole (PrivateImplementationTypeRole); } - set { SetChildByRole (PrivateImplementationTypeRole, value); } - } - - public AstNodeCollection TypeParameters { - get { return GetChildrenByRole (Roles.TypeParameter); } - } - - public CSharpTokenNode LParToken { - get { return GetChildByRole (Roles.LPar); } - } - - public AstNodeCollection Parameters { - get { return GetChildrenByRole (Roles.Parameter); } - } - - public CSharpTokenNode RParToken { - get { return GetChildByRole (Roles.RPar); } - } - - public AstNodeCollection 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 (IAstVisitor visitor) - { - return visitor.VisitMethodDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/OperatorDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/OperatorDeclaration.cs deleted file mode 100644 index b4ae52a2a..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/OperatorDeclaration.cs +++ /dev/null @@ -1,268 +0,0 @@ -// -// OperatorDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 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); } - } - - /// - /// Gets the operator type from the method name, or null, if the method does not represent one of the known operator types. - /// - 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 (); - } - } - - /// - /// Gets the method name for the operator type. ("op_Addition", "op_Implicit", etc.) - /// - public static string GetName (OperatorType type) - { - return Mono.CSharp.Operator.GetMetadataName ((Mono.CSharp.Operator.OpType)type); - } - - /// - /// Gets the token for the operator type ("+", "implicit", etc.) - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitOperatorDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/ParameterDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/ParameterDeclaration.cs deleted file mode 100644 index cc69ff1fd..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/ParameterDeclaration.cs +++ /dev/null @@ -1,147 +0,0 @@ -// -// ParameterDeclarationExpression.cs -// -// Author: -// Mike Krüger -// -// 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 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 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 (IAstVisitor visitor) - { - return visitor.VisitParameterDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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(); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/PropertyDeclaration.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/PropertyDeclaration.cs deleted file mode 100644 index 1f137e0c9..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/PropertyDeclaration.cs +++ /dev/null @@ -1,92 +0,0 @@ -// -// PropertyDeclaration.cs -// -// Author: -// Mike Krüger -// -// 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 GetterRole = new Role("Getter", Accessor.Null); - public static readonly Role SetterRole = new Role("Setter", Accessor.Null); - - public override SymbolKind SymbolKind { - get { return SymbolKind.Property; } - } - - /// - /// Gets/Sets the type reference of the interface that is explicitly implemented. - /// Null node if this member is not an explicit interface implementation. - /// - 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 (IAstVisitor visitor) - { - return visitor.VisitPropertyDeclaration (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/VariableInitializer.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/VariableInitializer.cs deleted file mode 100644 index dbf4bbe3d..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/VariableInitializer.cs +++ /dev/null @@ -1,174 +0,0 @@ -// -// VariableInitializer.cs -// -// Author: -// Mike Krüger -// -// 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 (IAstVisitor visitor) - { - return visitor.VisitNullNode(this); - } - - public override S AcceptVisitor (IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitPatternPlaceholder (this, child); - } - - public override S AcceptVisitor(IAstVisitor 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 (IAstVisitor visitor) - { - return visitor.VisitVariableInitializer (this); - } - - public override S AcceptVisitor (IAstVisitor 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/CSharpProjectContent.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/CSharpProjectContent.cs deleted file mode 100644 index ae0ba716e..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/CSharpProjectContent.cs +++ /dev/null @@ -1,289 +0,0 @@ -// 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 unresolvedFiles; - List assemblyReferences; - CompilerSettings compilerSettings; - - public CSharpProjectContent() - { - this.unresolvedFiles = new Dictionary(Platform.FileNameComparer); - this.assemblyReferences = new List(); - 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(pc.unresolvedFiles, Platform.FileNameComparer); - this.assemblyReferences = new List(pc.assemblyReferences); - this.compilerSettings = pc.compilerSettings; - } - - public IEnumerable Files { - get { return unresolvedFiles.Values; } - } - - public IEnumerable 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 AssemblyAttributes { - get { - return this.Files.SelectMany(f => f.AssemblyAttributes); - } - } - - public IEnumerable ModuleAttributes { - get { - return this.Files.SelectMany(f => f.ModuleAttributes); - } - } - - public IEnumerable 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); - } - - /// - /// Sets both the short and the full assembly names. - /// - /// New full assembly name. - 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 references) - { - return AddAssemblyReferences(references.ToArray()); - } - - public IProjectContent AddAssemblyReferences(params IAssemblyReference[] references) - { - CSharpProjectContent pc = Clone(); - pc.assemblyReferences.AddRange(references); - return pc; - } - - public IProjectContent RemoveAssemblyReferences(IEnumerable 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; - } - - /// - /// Adds the specified files to the project content. - /// If a file with the same name already exists, updated the existing file. - /// - public IProjectContent AddOrUpdateFiles(IEnumerable newFiles) - { - CSharpProjectContent pc = Clone(); - foreach (var file in newFiles) { - pc.unresolvedFiles[file.FileName] = file; - } - return pc; - } - - /// - /// Adds the specified files to the project content. - /// If a file with the same name already exists, this method updates the existing file. - /// - public IProjectContent AddOrUpdateFiles(params IUnresolvedFile[] newFiles) - { - return AddOrUpdateFiles((IEnumerable)newFiles); - } - - /// - /// Removes the files with the specified names. - /// - public IProjectContent RemoveFiles(IEnumerable fileNames) - { - CSharpProjectContent pc = Clone(); - foreach (var fileName in fileNames) { - pc.unresolvedFiles.Remove(fileName); - } - return pc; - } - - /// - /// Removes the files with the specified names. - /// - public IProjectContent RemoveFiles(params string[] fileNames) - { - return RemoveFiles((IEnumerable)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 oldFiles, IEnumerable 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); - } - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/CombineQueryExpressions.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/CombineQueryExpressions.cs deleted file mode 100644 index 5311d9a24..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/CombineQueryExpressions.cs +++ /dev/null @@ -1,216 +0,0 @@ -// -// CombineQueryExpressions.cs -// -// Modified by Luís Reis (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 -{ - /// - /// Combines query expressions and removes transparent identifiers. - /// - 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("targetType").Single().Detach(); - fromClause.Expression = m.Get("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("nae1").SingleOrDefault(); - string nae1Name = ExtractExpressionName(ref nae1); - if (nae1Name == null) - return false; - - Expression nae2 = match.Get("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().Any(from => from.Identifier == nae2Name)) { - return false; - } - if (introduceLetClause && innerQuery.Clauses.OfType().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; - } - - /// - /// Removes all occurrences of transparent identifiers - /// - 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(); // 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(); // 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; - } - } -} \ No newline at end of file diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs deleted file mode 100644 index 28c9ea02a..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs +++ /dev/null @@ -1,3807 +0,0 @@ -// -// CSharpCompletionEngine.cs -// -// Author: -// Mike Krüger -// -// 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 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; - /// - /// The auto complete empty match on curly bracket. (only taken into account when AutoCompleteEmptyMatch is true ) - /// - public bool AutoCompleteEmptyMatchOnCurlyBracket = true; - public bool AutoSelect; - public string DefaultCompletionString; - public bool CloseOnSquareBrackets; - public readonly List PossibleDelegates = new List(); - - #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 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(); - 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(result.Select(r => r.CompletionText)); - result = result.Concat(nonWsResult.Where(r => !text.Contains(r.CompletionText))); - } - } - } - - return result; - } - return Enumerable.Empty(); - } - - /// - /// Gets the types that needs to be imported via using or full type name. - /// - public IEnumerable GetImportCompletionData(int offset) - { - var generalLookup = new MemberLookup(null, Compilation.MainAssembly); - SetOffset(offset); - - // flatten usings - var namespaces = new List(); - 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 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 HandleMemberReferenceCompletion(ExpressionResult expr) - { - if (expr == null) - return null; - - // do not auto select . (but ..) (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 (.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 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 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 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 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 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 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 HandleStringFormatItems() - { - var formatArgument = GetFormatItemNumber(); - if (formatArgument < 0) - return Enumerable.Empty(); - 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(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(); - } - } - } - } - return HandleStringFormatItemsFallback(); - } - - IEnumerable HandleStringFormatItemsFallback() - { - var unit = ParseStub("a}\");", false); - - var invoke = unit.GetNodeAt(location); - - if (invoke == null) - return Enumerable.Empty(); - - var resolveResult = ResolveExpression(new ExpressionResult(invoke, unit)); - var invokeResult = resolveResult.Result as CSharpInvocationResolveResult; - if (invokeResult == null) - return Enumerable.Empty(); - - Expression fmtArgumets; - IList 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(); - - } - - IEnumerable 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 HandleToStringFormatItems() - { - var unit = ParseStub("\");", false); - - var invoke = unit.GetNodeAt(location); - if (invoke == null) - return Enumerable.Empty(); - - var resolveResult = ResolveExpression(new ExpressionResult(invoke, unit)); - var invokeResult = resolveResult.Result as InvocationResolveResult; - if (invokeResult == null) - return Enumerable.Empty(); - if (invokeResult.Member.Name == "ToString") - return GetFormatCompletionData(invokeResult.Member.DeclaringType) ?? Enumerable.Empty(); - return Enumerable.Empty(); - } - - IEnumerable 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(); - } - - 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(); - } - - if (lexer.IsInString || lexer.IsInVerbatimString) - return HandleToStringFormatItems(); - return Enumerable.Empty(); - case '.': - if (IsInsideCommentStringOrDirective()) { - return Enumerable.Empty(); - } - 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 (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(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(); - 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 HandleCatchClauseType(ExpressionResult identifierStart) - { - Func 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 HandleEnumContext() - { - var syntaxTree = ParseStub("a", false); - if (syntaxTree == null) { - return null; - } - - var curType = syntaxTree.GetNodeAt(location); - if (curType == null || curType.ClassType != ClassType.Enum) { - syntaxTree = ParseStub("a {}", false); - var node = syntaxTree.GetNodeAt(location); - if (node != null) { - var wrapper = new CompletionDataWrapper(this); - AddKeywords(wrapper, validEnumBaseTypes); - return wrapper.Result; - } - } - - var member = syntaxTree.GetNodeAt(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(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 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 ifStack = new Stack(); - - 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 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( - 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( - location.Line, - location.Column - ); - if (pd != null) { - var astResolver = unit != null ? CompletionContextProvider.GetResolver(GetState(), unit) : null; - var parameterType = astResolver.Resolve(pd.Type); - // Type 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 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 curNamespaces, List 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 typePred = null, Predicate memberPred = null, Action 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(); - 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(); - var dict = new Dictionary>(); - 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 createdDict; - if (!dict.TryGetValue(type.Name, out createdDict)) { - createdDict = new Dictionary(); - 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 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 namespaceList = GetUsedNamespaces (); - // var col = new CSharpTextEditorCompletion.CompletionDataCollector (this, dom, completionList, Document.CompilationUnit, null, location); - // bool isInterface = false; - // HashSet baseTypeNames = new HashSet (); - // if (cls != null) { - // baseTypeNames.Add (cls.Name); - // if (cls.ClassType == ClassType.Struct) - // isInterface = true; - // } - // int tokenIndex = offset; - // - // // Search base types " : [Type1, ... ,TypeN,] " - // 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 innerStack = new Stack (); - // 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 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 CreateConstructorCompletionData(IType hintType) - { - var wrapper = new CompletionDataWrapper(this); - var state = GetState(); - Func pred = null; - Action 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 GetOverrideCompletionData(IUnresolvedTypeDefinition type, string modifiers) - { - var wrapper = new CompletionDataWrapper(this); - var alreadyInserted = new List(); - //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 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(); - - 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 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 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 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 ().GetProjectFile (type2.Region.FileName) != null; - result = false; - } else if (type2.ProjectContent != null) { - //TODO!! - // result = type2.ProjectContent.Annotation ().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 CreateTypeAndNamespaceCompletionData(TextLocation location, ResolveResult resolveResult, AstNode resolvedNode, CSharpResolver state) - { - if (resolveResult == null || resolveResult.IsError) { - return null; - } - var exprParent = resolvedNode.GetParent(); - var unit = exprParent != null ? exprParent.GetParent() : 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 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 addedEnums, HashSet 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 CreateParameterCompletion(MethodGroupResolveResult resolveResult, CSharpResolver state, AstNode invocation, SyntaxTree unit, int parameter, bool controlSpace) - { - var result = new CompletionDataWrapper(this); - var addedEnums = new HashSet(); - var addedDelegates = new HashSet(); - - 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(); - } - 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 CreateCompletionData(TextLocation location, ResolveResult resolveResult, AstNode resolvedNode, CSharpResolver state, Func 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() == null) { - //tags the created expression as part of an object create expression. - /* - var filteredList = new List(); - 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 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 CreateCaseCompletionData(TextLocation location) - { - var unit = ParseStub("a: break;"); - if (unit == null) { - return null; - } - var s = unit.GetNodeAt(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(location); - if (type == null) { - baseUnit = ParseStub("a;", false); - type = baseUnit.GetNodeAt(location); - } - - if (type == null) { - baseUnit = ParseStub("A a;", false); - type = baseUnit.GetNodeAt(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(location) == null && baseUnit.GetNodeAt(location) == null) { - baseUnit = ParseStub("a"); - curNode = baseUnit.GetNodeAt(location); - } - - // Hack for handle object initializer continuation expressions - if (curNode is EntityDeclaration || baseUnit.GetNodeAt(location) == null && baseUnit.GetNodeAt(location) == null) { - baseUnit = ParseStub("a};"); - } - var mref = baseUnit.GetNodeAt(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(location); - if (type != null) { - return new ExpressionResult((AstNode)type.Target, baseUnit); - } - - var pref = baseUnit.GetNodeAt(location); - if (pref != null) { - return new ExpressionResult((AstNode)pref.Target, baseUnit); - } - } - - if (mref == null) { - baseUnit = ParseStub("A a;", false); - var type = baseUnit.GetNodeAt(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(location); - MemberType memberType = tref != null ? ((TypeReferenceExpression)tref).Type as MemberType : null; - if (memberType == null) { - memberType = baseUnit.GetNodeAt(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(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(location.Line, location.Column - 1); - } - if (expr == null) - expr = baseUnit.GetNodeAt(location.Line, location.Column - 1); - // try insertStatement - if (expr == null && baseUnit.GetNodeAt(location.Line, location.Column) != null) { - tmpUnit = baseUnit = ParseStub("a();", false); - expr = baseUnit.GetNodeAt( - location.Line, - location.Column + 1 - ); - } - - if (expr == null) { - baseUnit = ParseStub("()"); - expr = baseUnit.GetNodeAt( - location.Line, - location.Column - 1 - ); - if (expr == null) { - expr = baseUnit.GetNodeAt(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( - location.Line, - location.Column - 1 - ); - baseUnit = tmpUnit; - } - - if (expr == null) { - var block = tmpUnit.GetNodeAt(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( - 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( - location.Line, - location.Column - 1 - ); - baseUnit = tmpUnit; - } - - // try parameter declaration type - if (expr == null) { - baseUnit = ParseStub(">", false, "{}"); - expr = baseUnit.GetNodeAt( - location.Line, - location.Column - 1 - ); - } - - // try parameter declaration method - if (expr == null) { - baseUnit = ParseStub("> ()", false, "{}"); - expr = baseUnit.GetNodeAt( - location.Line, - location.Column - 1 - ); - } - - // try expression in anonymous type "new { sample = x$" case - if (expr == null) { - baseUnit = ParseStub("a", false); - expr = baseUnit.GetNodeAt( - location.Line, - location.Column - ); - if (expr != null) { - expr = baseUnit.GetNodeAt(location.Line, location.Column) ?? expr; - } - if (expr == null) { - expr = baseUnit.GetNodeAt(location.Line, location.Column); - } - } - - // try lambda - if (expr == null) { - baseUnit = ParseStub("foo) => {}", false); - expr = baseUnit.GetNodeAt( - 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 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 commentTags = new List(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 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 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=\"|\"> -// -// 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 -{ - /// - /// Acts as a common base between code completion and parameter completion. - /// - 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 indexStack = new Stack (); - 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 list; - return GetCurrentParameterIndex (triggerOffset, endOffset, out list); - } - - public int GetCurrentParameterIndex (int triggerOffset, int endOffset, out List usedNamedParameters) - { - usedNamedParameters =new List (); - var parameter = new Stack (); - var bracketStack = new Stack> (); - 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 (); - 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; - } - - /// - /// Parsing all text and calling act delegate on almost every character. - /// Skipping begining of comments, begining of verbatim strings and escaped characters. - /// - /// Return true to abort parsing. Integer argument represent offset in text. - /// True if aborted. - public bool Parse(Func act = null) - { - return Parse(0, text.Length, act); - } - - - /// - /// 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. - /// - /// Start offset. - /// Lenght to parse. - /// Return true to abort parsing. Integer argument represent offset in text. - /// True if aborted. - public bool Parse(int start, int length, Func 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> GetBracketStack (string memberText) - { - var bracketStack = new Stack> (); - - 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 memberText; - protected Tuple 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(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(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 - } -} \ No newline at end of file diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpParameterCompletionEngine.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpParameterCompletionEngine.cs deleted file mode 100644 index e5919834e..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpParameterCompletionEngine.cs +++ /dev/null @@ -1,408 +0,0 @@ -// -// CSharpParameterCompletionEngine.cs -// -// Author: -// Mike Krüger -// -// 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 (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(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(location.Line, location.Column + 1); - if (expr == null) - return null; - return new ExpressionResult((AstNode)expr, baseUnit); - } - - - - IEnumerable 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(); - 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 GetAccessibleIndexers(IType type) - { - var lookup = new MemberLookup(ctx.CurrentTypeDefinition, Compilation.MainAssembly); - var properties = new List(); - 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 (); - var chevronStack = new Stack (); - var squareStack = new Stack (); - var bracketStack = new Stack (); - - 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 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 GetUsedNamespaces() - { - var scope = ctx.CurrentUsingScope; - var result = new List(); - while (scope != null) { - result.Add(scope.Namespace.FullName); - - foreach (var ns in scope.Usings) { - result.Add(ns.FullName); - } - scope = scope.Parent; - } - return result; - } - - - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CompletionDataWrapper.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CompletionDataWrapper.cs deleted file mode 100644 index 4bf10d937..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CompletionDataWrapper.cs +++ /dev/null @@ -1,328 +0,0 @@ -// -// CompletionDataWrapper.cs -// -// Author: -// Mike Krüger -// -// 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 result = new List (); - - public List 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 usedNamespaces = new HashSet (); - - 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 typeDisplayText = new Dictionary (); - Dictionary addedTypes = new Dictionary (); - - 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> data = new Dictionary> (); - - public ICompletionData AddVariable(IVariable variable) - { - if (data.ContainsKey(variable.Name)) - return null; - data [variable.Name] = new List(); - 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(); - - 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 (); - 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 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 (); - 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 completionCategories = new Dictionary (); - 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 addedEnums = new HashSet (); - 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 anonymousSignatures = new HashSet (); - - public bool HasAnonymousDelegateAdded(string signature) - { - return anonymousSignatures.Contains(signature); - } - - public void AddAnonymousDelegateAdded(string signature) - { - anonymousSignatures.Add(signature); - } - } -} - - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionContextProvider.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionContextProvider.cs deleted file mode 100644 index b6e9822ee..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionContextProvider.cs +++ /dev/null @@ -1,214 +0,0 @@ -// -// IMemberProvider.cs -// -// Author: -// Mike Krüger -// -// 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 ConditionalSymbols { - get; - } - - void GetCurrentMembers (int offset, out IUnresolvedTypeDefinition currentType, out IUnresolvedMember currentMember); - - Tuple 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 symbols = new List (); - - public IList 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 (); - - 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 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); - } - - - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionDataFactory.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionDataFactory.cs deleted file mode 100644 index da61f8907..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionDataFactory.cs +++ /dev/null @@ -1,89 +0,0 @@ -// -// ICompletionDataFactory.cs -// -// Author: -// Mike Krüger -// -// 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); - - /// - /// Creates the member completion data. - /// Form: Type.Member - /// Used for generating enum members Foo.A, Foo.B where the enum 'Foo' is valid. - /// - ICompletionData CreateMemberCompletionData(IType type, IEntity member); - - /// - /// Creates a generic completion data. - /// - /// - /// The title of the completion data - /// - /// - /// The description of the literal. - /// - /// - /// The insert text. If null, title is taken. - /// - 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 CreateCodeTemplateCompletionData (); - - IEnumerable CreatePreProcessorDefinesCompletionData (); - - /// - /// Creates a completion data that adds the required using for the created type. - /// - /// The type to import - /// If set to true the full name of the type needs to be used. - /// If true the completion data is used in 'new' context. - 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); - - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/IParameterCompletionDataFactory.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/IParameterCompletionDataFactory.cs deleted file mode 100644 index 5bbb64e40..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/IParameterCompletionDataFactory.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -// IParameterCopmletionFactory.cs -// -// Author: -// Mike Krüger -// -// 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); - - /// - /// Creates a constructor provider skipping the parent of thisInitializer. - /// - IParameterDataProvider CreateConstructorProvider (int startOffset, IType type, AstNode thisInitializer); - - IParameterDataProvider CreateMethodDataProvider (int startOffset, IEnumerable methods); - - IParameterDataProvider CreateDelegateDataProvider (int startOffset, IType type); - - IParameterDataProvider CreateIndexerParameterDataProvider (int startOffset, IType type, IEnumerable accessibleIndexers, AstNode resolvedNode); - - IParameterDataProvider CreateTypeParameterDataProvider (int startOffset, IEnumerable types); - - IParameterDataProvider CreateTypeParameterDataProvider (int startOffset, IEnumerable methods); - } - -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/CSharpFormatter.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/CSharpFormatter.cs deleted file mode 100644 index a6969fea7..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/CSharpFormatter.cs +++ /dev/null @@ -1,159 +0,0 @@ -// -// CSharpFormatter.cs -// -// Author: -// Mike Krüger -// -// 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 - } - - /// - /// The C# Formatter generates a set of text replace actions to format a region in a C# document. - /// - public class CSharpFormatter - { - readonly CSharpFormattingOptions policy; - readonly TextEditorOptions options; - - /// - /// Gets the formatting policy the formatter uses. - /// - public CSharpFormattingOptions Policy { - get { - return policy; - } - } - - /// - /// Gets the text editor options the formatter uses. - /// Note: If none was specified TextEditorOptions.Default gets used. - /// - public TextEditorOptions TextEditorOptions { - get { - return options; - } - } - - List formattingRegions = new List (); - internal TextLocation lastFormattingLocation = new TextLocation(int.MaxValue, int.MaxValue); - - /// - /// Gets the formatting regions. NOTE: Will get changed to IReadOnlyList. - /// - public IList FormattingRegions { - get { - return formattingRegions; - } - } - - /// - /// Gets or sets the formatting mode. For on the fly formatting a lightweight formatting mode - /// gives better results. - /// - public FormattingMode FormattingMode { - get; - set; - } - - /// - /// Initializes a new instance of the class. - /// - /// The formatting policy to use. - /// The text editor options (optional). Default is: TextEditorOptions.Default - public CSharpFormatter(CSharpFormattingOptions policy, TextEditorOptions options = null) - { - if (policy == null) - throw new ArgumentNullException("policy"); - this.policy = policy; - this.options = options ?? TextEditorOptions.Default; - } - - /// - /// Format the specified document and gives back the formatted text as result. - /// - public string Format(IDocument document) - { - return InternalFormat (new StringBuilderDocument (document.Text)); - } - - /// - /// Format the specified text and gives back the formatted text as result. - /// - 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; - } - - /// - /// Analyzes the formatting of a given document and syntax tree. - /// - /// Document. - /// Syntax tree. - /// The cancellation token. - 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; - } - - /// - /// Adds a region in the document that should be formatted. - /// - public void AddFormattingRegion (DomRegion region) - { - formattingRegions.Add(region); - if (formattingRegions.Count == 1) { - lastFormattingLocation = region.End; - } else { - lastFormattingLocation = lastFormattingLocation < region.End ? region.End : lastFormattingLocation; - } - } - - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/CSharpFormattingOptions.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/CSharpFormattingOptions.cs deleted file mode 100644 index 0a97a1c0b..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/CSharpFormattingOptions.cs +++ /dev/null @@ -1,1039 +0,0 @@ -// -// CSharpFormattingOptions.cs -// -// Author: -// Mike Krüger -// -// 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; - }*/ - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/ConstructFixer.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/ConstructFixer.cs deleted file mode 100644 index f2fd87547..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/ConstructFixer.cs +++ /dev/null @@ -1,514 +0,0 @@ -// -// ConstructFixer.cs -// -// Author: -// Mike Krüger -// -// 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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingChanges.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingChanges.cs deleted file mode 100644 index f60b58bbd..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingChanges.cs +++ /dev/null @@ -1,169 +0,0 @@ -// -// CSharpFormatter.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// 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. - /// - public class FormattingChanges - { - readonly IDocument document; - readonly internal List changes = new List (); - - internal FormattingChanges (IDocument document) - { - if (document == null) - throw new ArgumentNullException("document"); - this.document = document; - } - - public int Count { - get { - return changes.Count; - } - } - - /// - /// Applies the changes to the input document. - /// - 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); - } - - /// - /// Applies the changes to the given Script instance. - /// - 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 documentReplace, Func 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 (); - 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); - } - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingOptionsFactory.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingOptionsFactory.cs deleted file mode 100644 index ff32c1f8c..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingOptionsFactory.cs +++ /dev/null @@ -1,446 +0,0 @@ -// -// FormattingOptionsFactory.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// The formatting options factory creates pre defined formatting option styles. - /// - public static class FormattingOptionsFactory - { - /// - /// Creates empty CSharpFormatting options. - /// - public static CSharpFormattingOptions CreateEmpty() - { - return new CSharpFormattingOptions(); - } - - /// - /// Creates mono indent style CSharpFormatting options. - /// - 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 - }; - } - - /// - /// Creates sharp develop indent style CSharpFormatting options. - /// - public static CSharpFormattingOptions CreateSharpDevelop() - { - var baseOptions = CreateKRStyle(); - return baseOptions; - } - - /// - /// 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. - /// - 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 - }; - } - - /// - /// Creates allman indent style CSharpFormatting options used in Visual Studio. - /// - 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; - } - - /// - /// 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. - /// - 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; - } - - /// - /// 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. - /// - public static CSharpFormattingOptions CreateGNU() - { - var baseOptions = CreateAllman(); - baseOptions.StatementBraceStyle = BraceStyle.NextLineShifted2; - return baseOptions; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor.cs deleted file mode 100644 index 485996c91..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor.cs +++ /dev/null @@ -1,662 +0,0 @@ -// -// FormattingVisitor.cs -// -// Author: -// Mike Krüger -// -// 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 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; - } - - } - - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Expressions.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Expressions.cs deleted file mode 100644 index 582e26fea..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Expressions.cs +++ /dev/null @@ -1,735 +0,0 @@ -// -// AstFormattingVisitor_Expressions.cs -// -// Author: -// Mike Krüger -// -// 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 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().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().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().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().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().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().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().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().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().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().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().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(); - } - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Global.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Global.cs deleted file mode 100644 index b91cbdd9a..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Global.cs +++ /dev/null @@ -1,351 +0,0 @@ -// -// AstFormattingVisitor_Global.cs -// -// Author: -// Mike Krüger -// -// 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); - } - }); - } - } -} \ No newline at end of file diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Query.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Query.cs deleted file mode 100644 index bfdc47640..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Query.cs +++ /dev/null @@ -1,124 +0,0 @@ -// -// AstFormattingVisitor_Query.cs -// -// Author: -// Luís Reis -// -// 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(); - 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; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Statements.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Statements.cs deleted file mode 100644 index 3c5c92095..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Statements.cs +++ /dev/null @@ -1,517 +0,0 @@ -// -// AstFormattingVisitor_Statements.cs -// -// Author: -// Mike Krüger -// -// 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(); - } - } - - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_TypeMembers.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_TypeMembers.cs deleted file mode 100644 index 913a61e2e..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_TypeMembers.cs +++ /dev/null @@ -1,477 +0,0 @@ -// -// AstFormattingVisitor_TypeMembers.cs -// -// Author: -// Mike Krüger -// -// 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); - } - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/GeneratedCodeSettings.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/GeneratedCodeSettings.cs deleted file mode 100644 index dd2df993e..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/GeneratedCodeSettings.cs +++ /dev/null @@ -1,216 +0,0 @@ -// -// GeneratedCodeSettings.cs -// -// Author: -// Mike Krüger -// -// 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 codeMemberOrder; - - public List 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 (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 defaultSettings = new Lazy( - () => new GeneratedCodeSettings() { - CodeMemberOrder = new List() { - 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; - } - } - } -} \ No newline at end of file diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/Indent.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/Indent.cs deleted file mode 100644 index 347e66f6e..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/Indent.cs +++ /dev/null @@ -1,246 +0,0 @@ -// -// Indent.cs -// -// Author: -// Mike Krüger -// -// 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 indentStack = new CloneableStack(); - 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(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); - } - - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/TextEditorOptions.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/TextEditorOptions.cs deleted file mode 100644 index 7c3eef2d2..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/TextEditorOptions.cs +++ /dev/null @@ -1,116 +0,0 @@ -// -// TextEditorOptions.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// The text editor options class holds basic information about the text editor settings that influences code generation and formatting beside - /// the CSharpFormattingOptions. - /// - public class TextEditorOptions - { - public static readonly TextEditorOptions Default = new TextEditorOptions (); - - /// - /// 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. - /// - public bool TabsToSpaces { - get; - set; - } - - /// - /// Gets or sets the size of the tab chacter as spaces. - /// - public int TabSize { - get; - set; - } - - /// - /// Gets or sets the size of a single indent as spaces. - /// - public int IndentSize { - get; - set; - } - - /// - /// Gets or sets the continuation indent. A continuation indent is the indent that will be put after an embedded statement that is no block. - /// - public int ContinuationIndent { - get; - set; - } - - /// - /// 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) - /// - public int LabelIndent { - get; - set; - } - - /// - /// Gets or sets the eol marker. - /// - public string EolMarker { - get; - set; - } - - /// - /// If true blank lines will be indented up to the indent level, otherwise blank lines will have the length 0. - /// - public bool IndentBlankLines { - get; - set; - } - - /// - /// 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. - /// - public int WrapLineLength { - get; - set; - } - - public TextEditorOptions() - { - TabsToSpaces = false; - TabSize = 4; - IndentSize = 4; - ContinuationIndent = 4; - WrapLineLength = 0; - EolMarker = Environment.NewLine; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/ICSharpCode.NRefactory.CSharp.csproj b/NRefactory/ICSharpCode.NRefactory.CSharp/ICSharpCode.NRefactory.CSharp.csproj deleted file mode 100644 index 4c53d5ff5..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/ICSharpCode.NRefactory.CSharp.csproj +++ /dev/null @@ -1,420 +0,0 @@ - - - - {53DCA265-3C3C-42F9-B647-F72BA678122B} - Debug - AnyCPU - Library - ICSharpCode.NRefactory.CSharp - ICSharpCode.NRefactory.CSharp - Properties - False - False - 4 - False - 8.0.30703 - 2.0 - true - ..\ICSharpCode.NRefactory.snk - False - File - ..\bin\$(Configuration)\ICSharpCode.NRefactory.CSharp.xml - 1591,1587,1570 - ..\bin\$(Configuration)\ - False - obj\$(Configuration)\ - - - AnyCPU - False - Auto - 4194304 - 4096 - - - False - False - DEBUG;TRACE;FULL_AST;NET_4_0 - - - True - False - TRACE;FULL_AST;NET_4_0 - obj\ - - - PdbOnly - True - ..\bin\Release\ - - - full - True - True - ..\bin\Debug\ - - - False - False - DEBUG;TRACE;FULL_AST;NET_4_0;NET_4_5 - v4.5 - - - full - True - True - v4.5 - ..\bin\net_4_5_Debug\ - - - True - False - TRACE;FULL_AST;NET_4_0;NET_4_5 - v4.5 - - - none - True - v4.5 - ..\bin\net_4_5_Release\ - - - - - - - - - - Properties\GlobalAssemblyInfo.cs - - - - - - - - - - - - - - - - - - - - - - ArrayInitializerExpression.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {3B2A5653-EC97-4001-BB9B-D90F1AF2C371} - ICSharpCode.NRefactory - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/CSharpIndentEngine.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/CSharpIndentEngine.cs deleted file mode 100644 index 478bc45c6..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/CSharpIndentEngine.cs +++ /dev/null @@ -1,557 +0,0 @@ -// -// CSharpIndentEngine.cs -// -// Author: -// Matej Miklečić -// -// 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 -{ - /// - /// Indentation engine based on a state machine. - /// Supports only pushing new chars to the end. - /// - /// - /// Represents the context for transitions between . - /// Delegates the responsibility for pushing a new char to the current - /// state and changes between states depending on the pushed chars. - /// - public class CSharpIndentEngine : IStateMachineIndentEngine - { - #region Properties - - /// - /// Formatting options. - /// - internal readonly CSharpFormattingOptions formattingOptions; - - /// - /// Text editor options. - /// - internal readonly TextEditorOptions textEditorOptions; - - /// - /// A readonly reference to the document that's parsed - /// by the engine. - /// - internal readonly IDocument document; - - /// - /// Represents the new line character. - /// - internal readonly char newLineChar; - - /// - /// The current indentation state. - /// - internal IndentState currentState; - - /// - /// Stores conditional symbols of #define directives. - /// - internal HashSet conditionalSymbols; - - /// - /// Stores custom conditional symbols. - /// - internal HashSet customConditionalSymbols; - - /// - /// Stores the results of evaluations of the preprocessor if/elif directives - /// in the current block (between #if and #endif). - /// - internal CloneableStack ifDirectiveEvalResults = new CloneableStack (); - - /// - /// Stores the indentation levels of the if directives in the current block. - /// - internal CloneableStack ifDirectiveIndents = new CloneableStack(); - - /// - /// Stores the last sequence of characters that can form a - /// valid keyword or variable name. - /// - internal StringBuilder wordToken; - - /// - /// Stores the previous sequence of chars that formed a - /// valid keyword or variable name. - /// - internal string previousKeyword; - - #endregion - - #region IDocumentIndentEngine - - /// - public IDocument Document - { - get { return document; } - } - - /// - 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; - } - } - - /// - public string NextLineIndent - { - get - { - return currentState.NextLineIndent.IndentString; - } - } - - /// - public string CurrentIndent - { - get - { - return currentIndent.ToString(); - } - } - - /// - /// - /// This is set depending on the current and - /// can change its value until the 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). - /// - 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(); - } - } - - /// - public int Offset - { - get - { - return offset; - } - } - - /// - public TextLocation Location - { - get - { - return new TextLocation(line, column); - } - } - - /// - public bool EnableCustomIndentLevels - { - get; - set; - } - - #endregion - - #region Fields - - /// - /// Represents the number of pushed chars. - /// - internal int offset = 0; - - /// - /// The current line number. - /// - internal int line = 1; - - /// - /// The current column number. - /// - /// - /// One char can take up multiple columns (e.g. \t). - /// - internal int column = 1; - - /// - /// True if is true for all - /// chars at the current line. - /// - internal bool isLineStart = true; - - /// - /// True if was true before the current - /// . - /// - internal bool isLineStartBeforeWordToken = true; - - /// - /// Current char that's being pushed. - /// - internal char currentChar = '\0'; - - /// - /// Last non-whitespace char that has been pushed. - /// - internal char previousChar = '\0'; - - /// - /// Previous new line char - /// - internal char previousNewline = '\0'; - - /// - /// Current indent level on this line. - /// - internal StringBuilder currentIndent = new StringBuilder(); - - /// - /// True if this line began in . - /// - internal bool lineBeganInsideVerbatimString = false; - - /// - /// True if this line began in . - /// - internal bool lineBeganInsideMultiLineComment = false; - - #endregion - - #region Constructors - - /// - /// Creates a new CSharpIndentEngine instance. - /// - /// - /// An instance of which is being parsed. - /// - /// - /// C# formatting options. - /// - /// - /// Text editor options for indentation. - /// - 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(); - this.customConditionalSymbols = new HashSet(); - this.wordToken = new StringBuilder(); - this.previousKeyword = string.Empty; - this.newLineChar = textEditorOptions.EolMarker[0]; - } - - /// - /// Creates a new CSharpIndentEngine instance from the given prototype. - /// - /// - /// An CSharpIndentEngine instance. - /// - 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(prototype.conditionalSymbols); - this.customConditionalSymbols = new HashSet(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(); - } - - /// - IDocumentIndentEngine IDocumentIndentEngine.Clone() - { - return Clone(); - } - - public IStateMachineIndentEngine Clone() - { - return new CSharpIndentEngine(this); - } - - #endregion - - #region Methods - - /// - 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; - } - } - - /// - 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; - } - - /// - public void Update(int offset) - { - if (Offset > offset) - { - Reset(); - } - - while (Offset < offset) - { - Push(Document.GetCharAt(Offset)); - } - } - - /// - /// Defines the conditional symbol. - /// - /// The symbol to define. - public void DefineSymbol(string defineSymbol) - { - if (!customConditionalSymbols.Contains(defineSymbol)) - customConditionalSymbols.Add(defineSymbol); - } - - /// - /// Removes the symbol. - /// - /// The symbol to undefine. - 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 - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/CacheIndentEngine.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/CacheIndentEngine.cs deleted file mode 100644 index b19f38868..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/CacheIndentEngine.cs +++ /dev/null @@ -1,627 +0,0 @@ -// -// CacheIndentEngine.cs -// -// Author: -// Matej Miklečić -// -// 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 -{ - /// - /// Represents a decorator of an IStateMachineIndentEngine instance that provides - /// logic for reseting and updating the engine on text changed events. - /// - /// - /// The decorator is based on periodical caching of the engine's state and - /// delegating all logic behind indentation to the currently active engine. - /// - public class CacheIndentEngine : IStateMachineIndentEngine - { - - #region Properties - - IStateMachineIndentEngine currentEngine; - Stack cachedEngines = new Stack(); - - #endregion - - #region Constructors - - /// - /// Creates a new CacheIndentEngine instance. - /// - /// - /// An instance of to which the - /// logic for indentation will be delegated. - /// - /// - /// The number of chars between caching. - /// - public CacheIndentEngine(IStateMachineIndentEngine decoratedEngine, int cacheRate = 2000) - { - this.currentEngine = decoratedEngine; - } - - /// - /// Creates a new CacheIndentEngine instance from the given prototype. - /// - /// - /// A CacheIndentEngine instance. - /// - public CacheIndentEngine(CacheIndentEngine prototype) - { - this.currentEngine = prototype.currentEngine.Clone(); - } - - #endregion - - #region IDocumentIndentEngine - - /// - public IDocument Document { - get { return currentEngine.Document; } - } - - /// - public string ThisLineIndent { - get { return currentEngine.ThisLineIndent; } - } - - /// - public string NextLineIndent { - get { return currentEngine.NextLineIndent; } - } - - /// - public string CurrentIndent { - get { return currentEngine.CurrentIndent; } - } - - /// - public bool NeedsReindent { - get { return currentEngine.NeedsReindent; } - } - - /// - public int Offset { - get { return currentEngine.Offset; } - } - - /// - public TextLocation Location { - get { return currentEngine.Location; } - } - - /// - public bool EnableCustomIndentLevels - { - get { return currentEngine.EnableCustomIndentLevels; } - set { currentEngine.EnableCustomIndentLevels = value; } - } - - /// - public void Push(char ch) - { - currentEngine.Push(ch); - } - - /// - public void Reset() - { - currentEngine.Reset(); - cachedEngines.Clear(); - } - - /// - /// Resets the engine to offset. Clears all cached engines after the given offset. - /// - 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(); - } - - /// - /// - /// If the is negative, the engine will - /// update to: document.TextLength + (offset % document.TextLength+1) - /// Otherwise it will update to: offset % document.TextLength+1 - /// - 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 - - /// - public IStateMachineIndentEngine Clone() - { - return new CacheIndentEngine(this); - } - - /// - 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 - - } - /* -/ // - /// Represents a decorator of an IStateMachineIndentEngine instance that provides - /// logic for reseting and updating the engine on text changed events. - /// - /// - /// The decorator is based on periodical caching of the engine's state and - /// delegating all logic behind indentation to the currently active engine. - /// - public class CacheIndentEngine : IStateMachineIndentEngine - { - #region Properties - - /// - /// Represents the cache interval in number of chars pushed to the engine. - /// - /// - /// When this many new chars are pushed to the engine, the currently active - /// engine gets cloned and added to the end of . - /// - readonly int cacheRate; - - /// - /// Determines how much memory to reserve on initialization for the - /// cached engines. - /// - const int cacheCapacity = 25; - - /// - /// Currently active engine. - /// - /// - /// Should be equal to the last engine in . - /// - IStateMachineIndentEngine currentEngine; - - /// - /// List of cached engines sorted ascending by - /// . - /// - IStateMachineIndentEngine[] cachedEngines; - - /// - /// The index of the last cached engine in cachedEngines. - /// - /// - /// Should be equal to: currentEngine.Offset / CacheRate - /// - int lastCachedEngine; - - #endregion - - #region Constructors - - /// - /// Creates a new CacheIndentEngine instance. - /// - /// - /// An instance of to which the - /// logic for indentation will be delegated. - /// - /// - /// The number of chars between caching. - /// - 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; - } - - /// - /// Creates a new CacheIndentEngine instance from the given prototype. - /// - /// - /// A CacheIndentEngine instance. - /// - 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 - - /// - /// Performs caching of the . - /// - 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 - - /// - public IDocument Document - { - get { return currentEngine.Document; } - } - - /// - public string ThisLineIndent - { - get { return currentEngine.ThisLineIndent; } - } - - /// - public string NextLineIndent - { - get { return currentEngine.NextLineIndent; } - } - - /// - public string CurrentIndent - { - get { return currentEngine.CurrentIndent; } - } - - /// - public bool NeedsReindent - { - get { return currentEngine.NeedsReindent; } - } - - /// - public int Offset - { - get { return currentEngine.Offset; } - } - - /// - public TextLocation Location - { - get { return currentEngine.Location; } - } - - /// - public void Push(char ch) - { - currentEngine.Push(ch); - - if (currentEngine.Offset % cacheRate == 0) - { - cache(); - } - } - - /// - public void Reset() - { - currentEngine = cachedEngines[lastCachedEngine = 0]; - } - - /// - /// - /// If the is negative, the engine will - /// update to: document.TextLength + (offset % document.TextLength+1) - /// Otherwise it will update to: offset % document.TextLength+1 - /// - 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 - 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 - lastCachedEngine = offset / cacheRate; - return cachedEngines[lastCachedEngine].Clone(); - } - - return currentEngine; - } - - #endregion - - #region IClonable - - /// - public IStateMachineIndentEngine Clone() - { - return new CacheIndentEngine(this); - } - - /// - 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 - } - - */ -} \ No newline at end of file diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IDocumentIndentEngine.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IDocumentIndentEngine.cs deleted file mode 100644 index 821aa0bc8..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IDocumentIndentEngine.cs +++ /dev/null @@ -1,108 +0,0 @@ -// -// IDocumentIndentEngine.cs -// -// Author: -// Matej Miklečić -// -// 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 -{ - /// - /// The base interface for all indent engines. - /// - public interface IDocumentIndentEngine : ICloneable - { - /// - /// A reference to the document that's parsed by the engine. - /// - IDocument Document { get; } - - /// - /// The indentation string of the current line. - /// - string ThisLineIndent { get; } - - /// - /// The indentation string of the next line. - /// - string NextLineIndent { get; } - - /// - /// The indent string on the beginning of the current line. - /// - string CurrentIndent { get; } - - /// - /// True if the current line needs to be reindented. - /// - bool NeedsReindent { get; } - - /// - /// The current offset of the engine. - /// - int Offset { get; } - - /// - /// The current location of the engine. - /// - TextLocation Location { get; } - - /// - /// If this is true, the engine should try to adjust its indent - /// levels to manual user's corrections, even if they are wrong. - /// - bool EnableCustomIndentLevels { get; set; } - - /// - /// Pushes a new char into the engine which calculates the new - /// indentation levels. - /// - /// - /// A new character. - /// - void Push(char ch); - - /// - /// Resets the engine. - /// - void Reset(); - - /// - /// Updates the engine to the given offset. - /// - /// - /// Valid offset in . - /// - void Update(int offset); - - /// - /// Clones the engine and preserves the current state. - /// - /// - /// An indentical clone which can operate without interference - /// with this engine. - /// - new IDocumentIndentEngine Clone(); - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IStateMachineIndentEngine.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IStateMachineIndentEngine.cs deleted file mode 100644 index 44c3949cf..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IStateMachineIndentEngine.cs +++ /dev/null @@ -1,60 +0,0 @@ -// -// IStateMachineIndentEngine.cs -// -// Author: -// Matej Miklečić -// -// 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(); - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IndentState.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IndentState.cs deleted file mode 100644 index 8867268e6..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IndentState.cs +++ /dev/null @@ -1,2017 +0,0 @@ -// -// IndentState.cs -// -// Author: -// Matej Miklečić -// -// 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 - - /// - /// The base class for all indentation states. - /// Each state defines the logic for indentation based on chars that - /// are pushed to it. - /// - public abstract class IndentState : ICloneable - { - #region Properties - - /// - /// The indentation engine using this state. - /// - public CSharpIndentEngine Engine; - - /// - /// The parent state. - /// This state can use the indentation levels of its parent. - /// When this state exits, the engine returns to the parent. - /// - public IndentState Parent; - - /// - /// The indentation of the current line. - /// This is set when the state is created and will be changed to - /// when the - /// is pushed. - /// - public Indent ThisLineIndent; - - /// - /// The indentation of the next line. - /// This is set when the state is created and can change depending - /// on the pushed chars. - /// - public Indent NextLineIndent; - - #endregion - - #region Constructors - - protected IndentState() - { - } - - /// - /// Creates a new indentation state that is a copy of the given - /// prototype. - /// - /// - /// The prototype state. - /// - /// - /// The engine of the new state. - /// - 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(); - } - - /// - /// Initializes the state: - /// - sets the default indentation levels. - /// - /// - /// Each state can override this method if it needs a different - /// logic for setting up the default indentations. - /// - public virtual void InitializeState() - { - ThisLineIndent = new Indent(Engine.textEditorOptions); - NextLineIndent = ThisLineIndent.Clone(); - } - - /// - /// Actions performed when this state exits. - /// - 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(); - } - } - - /// - /// Changes the current state of the using the current - /// state as the parent for the new one. - /// - /// - /// The type of the new state. Must be assignable from . - /// - public void ChangeState() - where T : IndentState, new () - { - var t = new T(); - t.Initialize(Engine, Engine.currentState); - Engine.currentState = t; - } - - /// - /// Exits this state by setting the current state of the - /// to this state's parent. - /// - public void ExitState() - { - OnExit(); - Engine.currentState = Engine.currentState.Parent ?? new GlobalBodyState(Engine); - } - - /// - /// Common logic behind the push method. - /// Each state can override this method and implement its own logic. - /// - /// - /// The current character that's being pushed. - /// - 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(); - } - } - - /// - /// When derived, checks if the given sequence of chars form - /// a valid keyword or variable name, depending on the state. - /// - /// - /// A possible keyword. - /// - public virtual void CheckKeyword(string keyword) - { } - - /// - /// When derived, checks if the given sequence of chars form - /// a valid keyword or variable name, depending on the state. - /// - /// - /// A possible keyword. - /// - /// - /// This method should be called from . - /// It is left to derived classes to call this method because of - /// performance issues. - /// - public virtual void CheckKeywordOnPush(string keyword) - { } - - #endregion - } - - #endregion - - #region Null state - - /// - /// Null state. - /// - /// - /// Doesn't define any transitions to new states. - /// - 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 - - /// - /// The base for all brackets body states. - /// - /// - /// Represents a block of code between a pair of brackets. - /// - public abstract class BracketsBodyBaseState : IndentState - { - - /// - /// When derived in a concrete bracket body state, represents - /// the closed bracket character pair. - /// - 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(); - break; - case '/': - if (Engine.previousChar == '/') - ChangeState(); - break; - case '*': - if (Engine.previousChar == '/') - ChangeState(); - break; - case '"': - if (Engine.previousChar == '@') - { - ChangeState(); - } - else - { - ChangeState(); - } - break; - case '\'': - ChangeState(); - break; - case '{': - ChangeState(); - break; - case '(': - ChangeState(); - break; - case '[': - ChangeState(); - break; - default: - if (ch == ClosedBracket) - ExitState(); - break; - } - } - } - - #endregion - - #region Braces body state - - /// - /// Braces body state. - /// - /// - /// Represents a block of code between { and }. - /// - public class BracesBodyState : BracketsBodyBaseState - { - /// - /// Type of the current block body. - /// - public Body CurrentBody; - - /// - /// Type of the next block body. - /// Same as if none of the - /// keywords have been read. - /// - public Body NextBody; - - /// - /// Type of the current statement. - /// - 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; - - /// - /// Contains indent levels of nested if statements. - /// - internal CloneableStack NestedIfStatementLevels = new CloneableStack(); - - /// - /// Contains the indent level of the last statement or body keyword. - /// - public Indent LastBlockIndent; - - /// - /// True if the engine is on the right side of the equal operator '='. - /// - public bool IsRightHandExpression; - - /// - /// True if the '=' char has been pushed and it's not - /// a part of a relational operator (>=, <=, !=, ==). - /// - public bool IsEqualCharPushed; - - /// - /// The indentation of the previous line. - /// - public int PreviousLineIndent; - - /// - /// True if the dot member (e.g. method invocation) indentation has - /// been handled in the current statement. - /// - 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(); - } - - /// - /// Actions performed when the current statement exits. - /// - public virtual void OnStatementExit() - { - IsRightHandExpression = false; - IsMemberReferenceDotHandled = false; - - NextLineIndent.RemoveAlignment(); - NextLineIndent.PopWhile(IndentType.Continuation); - - CurrentStatement = Statement.None; - NextBody = Body.None; - LastBlockIndent = null; - } - - #region Helpers - - /// - /// Types of braces bodies. - /// - public enum Body - { - None, - Namespace, - Class, - Struct, - Interface, - Enum, - Switch, - Case, - Try, - Catch, - Finally - } - - /// - /// Types of statements. - /// - public enum Statement - { - None, - If, - Else, - Do, - While, - For, - Foreach, - Lock, - Using, - Return - } - - static readonly Dictionary bodies = new Dictionary - { - { "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 statements = new Dictionary - { - { "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 blocks = new HashSet - { - "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" - }; - - /// - /// Checks if the given string is a keyword and sets the - /// and the - /// variables appropriately. - /// - /// - /// A possible keyword. - /// - /// - /// This method is called from - /// - 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); - } - } - - /// - /// Checks if the given string is a keyword and sets the - /// and the - /// variables appropriately. - /// - /// - /// A possible keyword. - /// - 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(); - } - 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); - } - } - - /// - /// Pushes a new level of indentation depending on the given - /// . - /// - 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; - } - - /// - /// Pushes a new level of indentation depending on the given - /// . - /// - 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); - } - } - - /// - /// Extracts the from the given state. - /// - /// - /// The correct type for this state. - /// - static Body extractBody(IndentState state) - { - if (state != null && state is BracesBodyState) - { - return ((BracesBodyState)state).NextBody; - } - - return Body.None; - } - - #endregion - } - - #endregion - - #region Global body state - - /// - /// Global body state. - /// - /// - /// Represents the global space of the program. - /// - 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 - - /// - /// Switch-case statement state. - /// - /// - /// Represents the block of code in one switch case (including default). - /// - 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(); - } - 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 - - /// - /// Parentheses body state. - /// - /// - /// Represents a block of code between ( and ). - /// - public class ParenthesesBodyState : BracketsBodyBaseState - { - /// - /// True if any char has been pushed. - /// - 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 - - /// - /// Square brackets body state. - /// - /// - /// Represents a block of code between [ and ]. - /// - public class SquareBracketsBodyState : BracketsBodyBaseState - { - /// - /// True if any char has been pushed. - /// - 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 - - /// - /// PreProcessor directive state. - /// - /// - /// Activated when the '#' char is pushed and the - /// is true. - /// - public class PreProcessorState : IndentState - { - /// - /// The type of the preprocessor directive. - /// - public PreProcessorDirective DirectiveType; - - /// - /// If is set (not equal to 'None'), this - /// stores the expression of the directive. - /// - 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(); - } - break; - case PreProcessorDirective.Elif: - if (Engine.ifDirectiveEvalResults.Count > 0) - { - if (!Engine.ifDirectiveEvalResults.Peek()) - { - ExitState(); - Engine.ifDirectiveEvalResults.Pop(); - goto case PreProcessorDirective.If; - } - } - // previous if was true -> comment - ChangeState(); - 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(); - } - else - { - // none if/elif directives were true -> exit comment state. - if (Engine.currentState is PreProcessorCommentState) - ExitState(); - } - 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 - if (Engine.currentState is PreProcessorCommentState) - ExitState(); - - 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 preProcessorDirectives = new Dictionary - { - { "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); - } - - /// - /// Types of preprocessor directives. - /// - 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 - - /// - /// PreProcessor comment state. - /// - /// - /// Activates when the #if or #elif directive is false and ignores - /// all pushed chars until the next '#'. - /// - 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) - { - ChangeState(); - } - } - - 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 - - /// - /// Single-line comment state. - /// - public class LineCommentState : IndentState - { - /// - /// It's possible that this should be the DocComment state: - /// check if the first next pushed char is equal to '/'. - /// - 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(); - } - - 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 - - /// - /// XML documentation comment state. - /// - 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 - - /// - /// Multi-line comment state. - /// - public class MultiLineCommentState : IndentState - { - /// - /// True if any char has been pushed to this state. - /// - /// - /// 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 '*'. - /// - 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 - - /// - /// StringLiteral state. - /// - public class StringLiteralState : IndentState - { - /// - /// True if the next char is escaped with '\'. - /// - 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 - - /// - /// Verbatim string state. - /// - public class VerbatimStringState : IndentState - { - /// - /// True if there is an odd number of '"' in a row. - /// - 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 - - /// - /// Character state. - /// - public class CharacterState : IndentState - { - /// - /// True if the next char is escaped with '\'. - /// - 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 -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/NullIStateMachineIndentEngine.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/NullIStateMachineIndentEngine.cs deleted file mode 100644 index b62932e5b..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/NullIStateMachineIndentEngine.cs +++ /dev/null @@ -1,215 +0,0 @@ -// -// NullIStateMachineIndentEngine.cs -// -// Author: -// Mike Krüger -// -// 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 -{ - /// - /// An empty IStateMachineIndentEngine implementation that does nothing. - /// - 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; - } - } - - /// - public bool EnableCustomIndentLevels - { - get { return false; } - set { } - } - - #endregion - - #region ICloneable implementation - object ICloneable.Clone() - { - return Clone(); - } - #endregion - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/TextPasteIndentEngine.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/TextPasteIndentEngine.cs deleted file mode 100644 index 9170b029f..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/TextPasteIndentEngine.cs +++ /dev/null @@ -1,632 +0,0 @@ -// -// TextPasteIndentEngine.cs -// -// Author: -// Matej Miklečić -// -// 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 -{ - /// - /// Represents a decorator of an IStateMachineIndentEngine instance - /// that provides logic for text paste events. - /// - public class TextPasteIndentEngine : IDocumentIndentEngine, ITextPasteHandler - { - - #region Properties - - /// - /// An instance of IStateMachineIndentEngine which handles - /// the indentation logic. - /// - IStateMachineIndentEngine engine; - /// - /// Text editor options. - /// - internal readonly TextEditorOptions textEditorOptions; - internal readonly CSharpFormattingOptions formattingOptions; - #endregion - - #region Constructors - - /// - /// Creates a new TextPasteIndentEngine instance. - /// - /// - /// An instance of to which the - /// logic for indentation will be delegated. - /// - /// - /// Text editor options for indentation. - /// - /// - /// C# formatting options. - /// - public TextPasteIndentEngine(IStateMachineIndentEngine decoratedEngine, TextEditorOptions textEditorOptions, CSharpFormattingOptions formattingOptions) - { - this.engine = decoratedEngine; - this.textEditorOptions = textEditorOptions; - this.formattingOptions = formattingOptions; - - this.engine.EnableCustomIndentLevels = false; - } - - #endregion - - #region ITextPasteHandler - - /// - 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(); - } - - /// - 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 - - /// - public IDocument Document { - get { return engine.Document; } - } - - /// - public string ThisLineIndent { - get { return engine.ThisLineIndent; } - } - - /// - public string NextLineIndent { - get { return engine.NextLineIndent; } - } - - /// - public string CurrentIndent { - get { return engine.CurrentIndent; } - } - - /// - public bool NeedsReindent { - get { return engine.NeedsReindent; } - } - - /// - public int Offset { - get { return engine.Offset; } - } - - /// - public TextLocation Location { - get { return engine.Location; } - } - - /// - public bool EnableCustomIndentLevels { - get { return engine.EnableCustomIndentLevels; } - set { engine.EnableCustomIndentLevels = value; } - } - - /// - public void Push(char ch) - { - engine.Push(ch); - } - - /// - public void Reset() - { - engine.Reset(); - } - - /// - 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 - - } - - /// - /// Types of text-paste strategies. - /// - public enum PasteStrategy : byte - { - PlainText = 0, - StringLiteral = 1, - VerbatimString = 2 - } - - /// - /// Defines some helper methods for dealing with text-paste events. - /// - public static class TextPasteUtils - { - /// - /// Collection of text-paste strategies. - /// - public static TextPasteStrategies Strategies = new TextPasteStrategies(); - - /// - /// The interface for a text-paste strategy. - /// - public interface IPasteStrategy - { - /// - /// Formats the given text according with this strategy rules. - /// - /// - /// The text to format. - /// - /// - /// Formatted text. - /// - string Encode(string text); - - /// - /// Converts text formatted according with this strategy rules - /// to its original form. - /// - /// - /// Formatted text to convert. - /// - /// - /// Original form of the given formatted text. - /// - string Decode(string text); - - /// - /// Type of this strategy. - /// - PasteStrategy Type { get; } - } - - /// - /// Wrapper that discovers all defined text-paste strategies and defines a way - /// to easily access them through their type. - /// - public sealed class TextPasteStrategies - { - /// - /// Collection of discovered text-paste strategies. - /// - IDictionary strategies; - - /// - /// Uses reflection to find all types derived from - /// and adds an instance of each strategy to . - /// - 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); - } - - /// - /// Checks if there is a strategy of the given type and returns it. - /// - /// - /// Type of the strategy instance. - /// - /// - /// A strategy instance of the requested type, - /// or if it wasn't found. - /// - public IPasteStrategy this [PasteStrategy strategy] { - get { - if (strategies.ContainsKey(strategy)) { - return strategies [strategy]; - } - - return DefaultStrategy; - } - } - } - - /// - /// Doesn't do any formatting. Serves as the default strategy. - /// - public class PlainTextPasteStrategy : IPasteStrategy - { - - #region Singleton - - public static IPasteStrategy Instance { - get { - return instance ?? (instance = new PlainTextPasteStrategy()); - } - } - - static PlainTextPasteStrategy instance; - - protected PlainTextPasteStrategy() - { - } - - #endregion - - /// - public string Encode(string text) - { - return text; - } - - /// - public string Decode(string text) - { - return text; - } - - /// - public PasteStrategy Type { - get { return PasteStrategy.PlainText; } - } - } - - /// - /// Escapes chars in the given text so that they don't - /// break a valid string literal. - /// - public class StringLiteralPasteStrategy : IPasteStrategy - { - - #region Singleton - - public static IPasteStrategy Instance { - get { - return instance ?? (instance = new StringLiteralPasteStrategy()); - } - } - - static StringLiteralPasteStrategy instance; - - protected StringLiteralPasteStrategy() - { - } - - #endregion - - /// - public string Encode(string text) - { - return CSharpOutputVisitor.ConvertString(text); - } - - /// - 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; - } - - /// - public PasteStrategy Type { - get { return PasteStrategy.StringLiteral; } - } - } - - /// - /// Escapes chars in the given text so that they don't - /// break a valid verbatim string. - /// - 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> encodeReplace = new Dictionary> { - { '\"', "\"\"" }, - }; - - /// - public string Encode(string text) - { - return string.Concat(text.SelectMany(c => encodeReplace.ContainsKey(c) ? encodeReplace [c] : new[] { c })); - } - - /// - public string Decode(string text) - { - bool isEscaped = false; - return string.Concat(text.Where(c => !(isEscaped = !isEscaped && c == '"'))); - } - - /// - public PasteStrategy Type { - get { return PasteStrategy.VerbatimString; } - } - } - - /// - /// The default text-paste strategy. - /// - public static IPasteStrategy DefaultStrategy = PlainTextPasteStrategy.Instance; - /// - /// String literal text-paste strategy. - /// - public static IPasteStrategy StringLiteralStrategy = StringLiteralPasteStrategy.Instance; - /// - /// Verbatim string text-paste strategy. - /// - public static IPasteStrategy VerbatimStringStrategy = VerbatimStringPasteStrategy.Instance; - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/IntroduceQueryExpressions.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/IntroduceQueryExpressions.cs deleted file mode 100644 index d80ddb82c..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/IntroduceQueryExpressions.cs +++ /dev/null @@ -1,386 +0,0 @@ -// -// IntroduceQueryExpressions.cs -// -// Modified by Luís Reis (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(this T node) where T : AstNode - { - node.Remove(); - return node; - } - - public static T CopyAnnotationsFrom(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); - } - } - - /// - /// Decompiles query expressions. - /// Based on C# 4.0 spec, §7.16.2 Query expression translation - /// - 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()) { - 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().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("inExpr").Single().Detach(); - joinClause.Type = castMatch.Get("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().Where(id => id.Name == p1.Name)) - { - identifier.Name = elementName1; - } - } - if (p2.Name != elementName2 && mre.MemberName != "GroupJoin") { - foreach (var identifier in resultExpr.Descendants.OfType().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++; - } - - /// - /// Ensure that all ThenBy's are correct, and that the list of ThenBy's is terminated by an 'OrderBy' invocation. - /// - 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; - } - - /// Matches simple lambdas of the form "a => b" - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/NameLookupMode.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/NameLookupMode.cs deleted file mode 100644 index 3196dc583..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/NameLookupMode.cs +++ /dev/null @@ -1,47 +0,0 @@ -// 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 - { - /// - /// Normal name lookup in expressions - /// - Expression, - /// - /// Name lookup in expression, where the expression is the target of an invocation. - /// Such a lookup will only return methods and delegate-typed fields. - /// - InvocationTarget, - /// - /// Normal name lookup in type references. - /// - Type, - /// - /// Name lookup in the type reference inside a using declaration. - /// - TypeInUsingDeclaration, - /// - /// Name lookup for base type references. - /// - BaseTypeReference - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpAmbience.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpAmbience.cs deleted file mode 100644 index f6c153b1a..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpAmbience.cs +++ /dev/null @@ -1,312 +0,0 @@ -// 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 -{ - /// - /// C# ambience. Used to convert type system symbols to text (usually for displaying the symbol to the user; e.g. in editor tooltips) - /// - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs deleted file mode 100644 index dad86b3da..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs +++ /dev/null @@ -1,2401 +0,0 @@ -// 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 -{ - /// - /// Outputs the AST. - /// - public class CSharpOutputVisitor : IAstVisitor - { - readonly TokenWriter writer; - readonly CSharpFormattingOptions policy; - readonly Stack containerStack = new Stack (); - - 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 - /// - /// Writes a comma. - /// - /// The next node after the comma. - /// When set prevents printing a space after comma. - 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. - } - - /// - /// Writes an optional comma, e.g. at the end of an enum declaration or in an array initializer - /// - 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); - } - } - - /// - /// Writes an optional semicolon, e.g. at the end of a type or namespace declaration. - /// - 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 list) - { - bool isFirst = true; - foreach (AstNode node in list) { - if (isFirst) { - isFirst = false; - } else { - Comma(node); - } - node.AcceptVisitor(this); - } - } - - void WriteCommaSeparatedListInParenthesis(IEnumerable list, bool spaceWithin) - { - LPar(); - if (list.Any()) { - Space(spaceWithin); - WriteCommaSeparatedList(list); - Space(spaceWithin); - } - RPar(); - } - - #if DOTNET35 - void WriteCommaSeparatedList(IEnumerable list) - { - WriteCommaSeparatedList(list.SafeCast()); - } - - void WriteCommaSeparatedList(IEnumerable list) - { - WriteCommaSeparatedList(list.SafeCast()); - } - - void WriteCommaSeparatedListInParenthesis(IEnumerable list, bool spaceWithin) - { - WriteCommaSeparatedListInParenthesis(list.SafeCast(), spaceWithin); - } - - void WriteCommaSeparatedListInParenthesis(IEnumerable list, bool spaceWithin) - { - WriteCommaSeparatedListInParenthesis(list.SafeCast(), spaceWithin); - } - - #endif - - void WriteCommaSeparatedListInBrackets(IEnumerable list, bool spaceWithin) - { - WriteToken(Roles.LBracket); - if (list.Any()) { - Space(spaceWithin); - WriteCommaSeparatedList(list); - Space(spaceWithin); - } - WriteToken(Roles.RBracket); - } - - void WriteCommaSeparatedListInBrackets(IEnumerable 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; - - /// - /// Writes a keyword, and all specials up to - /// - 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); - } - - /// - /// Marks the end of a statement - /// - 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(); - } - } - - /// - /// Writes a space depending on policy. - /// - 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 unconditionalKeywords = new HashSet { - "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 queryKeywords = new HashSet { - "from", "where", "join", "on", "equals", "into", "let", "orderby", - "ascending", "descending", "select", "group", "by" - }; - - /// - /// Determines whether the specified identifier is a keyword in the given context. - /// - 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 typeArguments) - { - if (typeArguments.Any()) { - WriteToken(Roles.LChevron); - WriteCommaSeparatedList(typeArguments); - WriteToken(Roles.RChevron); - } - } - - public void WriteTypeParameters(IEnumerable typeParameters) - { - if (typeParameters.Any()) { - WriteToken(Roles.LChevron); - WriteCommaSeparatedList(typeParameters); - WriteToken(Roles.RChevron); - } - } - - void WriteModifiers(IEnumerable modifierTokens) - { - foreach (CSharpModifierToken modifier in modifierTokens) { - modifier.AcceptVisitor(this); - } - } - - void WriteQualifiedIdentifier(IEnumerable 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 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 { { 1 } }" and "new List { 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 { a = 1 };" is an object initalizers and invalid, but - // "int a; new List { { 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 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)) { - WriteKeyword(attributeSection.AttributeTarget, Roles.Identifier); - 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); - if (ifElseStatement.FalseStatement is IfElseStatement) { - // don't put newline between 'else' and 'if' - ifElseStatement.FalseStatement.AcceptVisitor(this); - } else { - 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 - - /// - /// Converts special characters to escape sequences within the given string. - /// - public static string ConvertString(string text) - { - return TextWriterTokenWriter.ConvertString(text); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CodeDomConvertVisitor.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CodeDomConvertVisitor.cs deleted file mode 100644 index bd82827d8..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CodeDomConvertVisitor.cs +++ /dev/null @@ -1,1429 +0,0 @@ -// 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 -{ - /// - /// Converts from C# AST to CodeDom. - /// - /// - /// The conversion is intended for use in the SharpDevelop forms designer. - /// - public class CodeDomConvertVisitor : IAstVisitor - { - CSharpAstResolver resolver; - - /// - /// Gets/Sets whether the visitor should convert short type names into - /// fully qualified type names. - /// The default is false. - /// - public bool UseFullyQualifiedTypeNames { get; set; } - - /// - /// Gets whether the visitor is allowed to produce snippet nodes for - /// code that cannot be converted. - /// The default is true. If this property is set to false, - /// unconvertible code will throw a NotSupportedException. - /// - public bool AllowSnippetNodes { get; set; } - - public CodeDomConvertVisitor() - { - this.AllowSnippetNodes = true; - } - - /// - /// Converts a syntax tree to CodeDom. - /// - /// The input syntax tree. - /// The current compilation. - /// CSharpUnresolvedFile, used for resolving. - /// Converted CodeCompileUnit - /// - /// This conversion process requires a resolver because it needs to distinguish field/property/event references etc. - /// - 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); - } - - /// - /// Converts a C# AST node to CodeDom. - /// - /// The input node. - /// The AST resolver. - /// The node converted into CodeDom - /// - /// This conversion process requires a resolver because it needs to distinguish field/property/event references etc. - /// - 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 expressions) - { - List result = new List(); - 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 types) - { - List result = new List(); - 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 result = new List(); - 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(); - } - - /// - /// Converts an expression by storing it as C# snippet. - /// This is used for expressions that cannot be represented in CodeDom. - /// - CodeSnippetExpression MakeSnippetExpression(Expression expr) - { - return new CodeSnippetExpression(MakeSnippet(expr)); - } - - CodeSnippetStatement MakeSnippetStatement(Statement stmt) - { - return new CodeSnippetStatement(MakeSnippet(stmt)); - } - - CodeObject IAstVisitor.VisitNullNode(AstNode nullNode) - { - return null; - } - - CodeObject IAstVisitor.VisitErrorNode(AstNode errorNode) - { - return null; - } - - CodeObject IAstVisitor.VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression) - { - return MakeSnippetExpression(anonymousMethodExpression); - } - - CodeObject IAstVisitor.VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression) - { - return MakeSnippetExpression(undocumentedExpression); - } - - CodeObject IAstVisitor.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.VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression) - { - // Array initializers should be handled by the parent node - return MakeSnippetExpression(arrayInitializerExpression); - } - - CodeObject IAstVisitor.VisitAsExpression(AsExpression asExpression) - { - return MakeSnippetExpression(asExpression); - } - - CodeObject IAstVisitor.VisitAssignmentExpression(AssignmentExpression assignmentExpression) - { - // assignments are only supported as statements, not as expressions - return MakeSnippetExpression(assignmentExpression); - } - - CodeObject IAstVisitor.VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression) - { - return new CodeBaseReferenceExpression(); - } - - CodeObject IAstVisitor.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.VisitCastExpression(CastExpression castExpression) - { - return new CodeCastExpression(Convert(castExpression.Type), Convert(castExpression.Expression)); - } - - CodeObject IAstVisitor.VisitCheckedExpression(CheckedExpression checkedExpression) - { - return MakeSnippetExpression(checkedExpression); - } - - CodeObject IAstVisitor.VisitConditionalExpression(ConditionalExpression conditionalExpression) - { - return MakeSnippetExpression(conditionalExpression); - } - - CodeObject IAstVisitor.VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression) - { - return new CodeDefaultValueExpression(Convert(defaultValueExpression.Type)); - } - - CodeObject IAstVisitor.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.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.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.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.VisitIsExpression(IsExpression isExpression) - { - return MakeSnippetExpression(isExpression); - } - - CodeObject IAstVisitor.VisitLambdaExpression(LambdaExpression lambdaExpression) - { - return MakeSnippetExpression(lambdaExpression); - } - - CodeObject IAstVisitor.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 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.VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression) - { - return MakeSnippetExpression(namedArgumentExpression); - } - - CodeObject IAstVisitor.VisitNamedExpression(NamedExpression namedExpression) - { - return MakeSnippetExpression(namedExpression); - } - - CodeObject IAstVisitor.VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression) - { - return new CodePrimitiveExpression(null); - } - - CodeObject IAstVisitor.VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression) - { - if (!objectCreateExpression.Initializer.IsNull) - return MakeSnippetExpression(objectCreateExpression); - return new CodeObjectCreateExpression(Convert(objectCreateExpression.Type), Convert(objectCreateExpression.Arguments)); - } - - CodeObject IAstVisitor.VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression) - { - return MakeSnippetExpression(anonymousTypeCreateExpression); - } - - CodeObject IAstVisitor.VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression) - { - // CodeDom generators will insert parentheses where necessary - return Convert(parenthesizedExpression.Expression); - } - - CodeObject IAstVisitor.VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression) - { - return MakeSnippetExpression(pointerReferenceExpression); - } - - CodeObject IAstVisitor.VisitPrimitiveExpression(PrimitiveExpression primitiveExpression) - { - return new CodePrimitiveExpression(primitiveExpression.Value); - } - - CodeObject IAstVisitor.VisitSizeOfExpression(SizeOfExpression sizeOfExpression) - { - return MakeSnippetExpression(sizeOfExpression); - } - - CodeObject IAstVisitor.VisitStackAllocExpression(StackAllocExpression stackAllocExpression) - { - return MakeSnippetExpression(stackAllocExpression); - } - - CodeObject IAstVisitor.VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression) - { - return new CodeThisReferenceExpression(); - } - - CodeObject IAstVisitor.VisitTypeOfExpression(TypeOfExpression typeOfExpression) - { - return new CodeTypeOfExpression(Convert(typeOfExpression.Type)); - } - - CodeObject IAstVisitor.VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression) - { - return new CodeTypeReferenceExpression(Convert(typeReferenceExpression.Type)); - } - - CodeObject IAstVisitor.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.VisitUncheckedExpression(UncheckedExpression uncheckedExpression) - { - return MakeSnippetExpression(uncheckedExpression); - } - - CodeObject IAstVisitor.VisitQueryExpression(QueryExpression queryExpression) - { - return MakeSnippetExpression(queryExpression); - } - - CodeObject IAstVisitor.VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitQueryFromClause(QueryFromClause queryFromClause) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitQueryLetClause(QueryLetClause queryLetClause) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitQueryWhereClause(QueryWhereClause queryWhereClause) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitQueryJoinClause(QueryJoinClause queryJoinClause) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitQueryOrderClause(QueryOrderClause queryOrderClause) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitQueryOrdering(QueryOrdering queryOrdering) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitQuerySelectClause(QuerySelectClause querySelectClause) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitQueryGroupClause(QueryGroupClause queryGroupClause) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitAttribute(Attribute attribute) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.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 attributeSections) - { - List result = new List(); - 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.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.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 typeStack = new Stack(); - - CodeObject IAstVisitor.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.VisitUsingAliasDeclaration(UsingAliasDeclaration usingAliasDeclaration) - { - return new CodeSnippetTypeMember(MakeSnippet(usingAliasDeclaration)); - } - - CodeObject IAstVisitor.VisitUsingDeclaration(UsingDeclaration usingDeclaration) - { - return new CodeNamespaceImport(usingDeclaration.Namespace); - } - - CodeObject IAstVisitor.VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration) - { - return new CodeSnippetTypeMember(MakeSnippet(externAliasDeclaration)); - } - - CodeObject IAstVisitor.VisitBlockStatement(BlockStatement blockStatement) - { - return new CodeConditionStatement(new CodePrimitiveExpression(true), ConvertBlock(blockStatement)); - } - - CodeObject IAstVisitor.VisitBreakStatement(BreakStatement breakStatement) - { - return MakeSnippetStatement(breakStatement); - } - - CodeObject IAstVisitor.VisitCheckedStatement(CheckedStatement checkedStatement) - { - return MakeSnippetStatement(checkedStatement); - } - - CodeObject IAstVisitor.VisitContinueStatement(ContinueStatement continueStatement) - { - return MakeSnippetStatement(continueStatement); - } - - CodeObject IAstVisitor.VisitDoWhileStatement(DoWhileStatement doWhileStatement) - { - // do { } while (expr); - // - // emulate with: - // for (bool _do = true; _do; _do = expr) {} - string varName = "_do" + doWhileStatement.Ancestors.OfType().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.VisitEmptyStatement(EmptyStatement emptyStatement) - { - return EmptyStatement(); - } - - CodeStatement EmptyStatement() - { - return new CodeExpressionStatement(new CodeObjectCreateExpression(new CodeTypeReference(typeof(object)))); - } - - CodeObject IAstVisitor.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.VisitFixedStatement(FixedStatement fixedStatement) - { - return MakeSnippetStatement(fixedStatement); - } - - CodeObject IAstVisitor.VisitForeachStatement(ForeachStatement foreachStatement) - { - return MakeSnippetStatement(foreachStatement); - } - - CodeObject IAstVisitor.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.VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement) - { - return MakeSnippetStatement(gotoCaseStatement); - } - - CodeObject IAstVisitor.VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement) - { - return MakeSnippetStatement(gotoDefaultStatement); - } - - CodeObject IAstVisitor.VisitGotoStatement(GotoStatement gotoStatement) - { - return new CodeGotoStatement(gotoStatement.Label); - } - - CodeObject IAstVisitor.VisitIfElseStatement(IfElseStatement ifElseStatement) - { - return new CodeConditionStatement( - Convert(ifElseStatement.Condition), - ConvertEmbeddedStatement(ifElseStatement.TrueStatement), - ConvertEmbeddedStatement(ifElseStatement.FalseStatement)); - } - - CodeObject IAstVisitor.VisitLabelStatement(LabelStatement labelStatement) - { - return new CodeLabeledStatement(labelStatement.Label); - } - - CodeObject IAstVisitor.VisitLockStatement(LockStatement lockStatement) - { - return MakeSnippetStatement(lockStatement); - } - - CodeObject IAstVisitor.VisitReturnStatement(ReturnStatement returnStatement) - { - return new CodeMethodReturnStatement(Convert(returnStatement.Expression)); - } - - CodeObject IAstVisitor.VisitSwitchStatement(SwitchStatement switchStatement) - { - return MakeSnippetStatement(switchStatement); - } - - CodeObject IAstVisitor.VisitSwitchSection(SwitchSection switchSection) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitCaseLabel(CaseLabel caseLabel) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitThrowStatement(ThrowStatement throwStatement) - { - return new CodeThrowExceptionStatement(Convert(throwStatement.Expression)); - } - - CodeObject IAstVisitor.VisitTryCatchStatement(TryCatchStatement tryCatchStatement) - { - List catchClauses = new List(); - 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.VisitCatchClause(CatchClause catchClause) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitUncheckedStatement(UncheckedStatement uncheckedStatement) - { - return MakeSnippetStatement(uncheckedStatement); - } - - CodeObject IAstVisitor.VisitUnsafeStatement(UnsafeStatement unsafeStatement) - { - return MakeSnippetStatement(unsafeStatement); - } - - CodeObject IAstVisitor.VisitUsingStatement(UsingStatement usingStatement) - { - return MakeSnippetStatement(usingStatement); - } - - CodeObject IAstVisitor.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.VisitWhileStatement(WhileStatement whileStatement) - { - return new CodeIterationStatement(EmptyStatement(), Convert(whileStatement.Condition), EmptyStatement(), ConvertEmbeddedStatement(whileStatement.EmbeddedStatement)); - } - - CodeObject IAstVisitor.VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement) - { - return MakeSnippetStatement(yieldBreakStatement); - } - - CodeObject IAstVisitor.VisitYieldReturnStatement(YieldReturnStatement yieldStatement) - { - return MakeSnippetStatement(yieldStatement); - } - - CodeObject IAstVisitor.VisitAccessor(Accessor accessor) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.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.VisitConstructorInitializer(ConstructorInitializer constructorInitializer) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration) - { - return new CodeSnippetTypeMember(MakeSnippet(destructorDeclaration)); - } - - CodeObject IAstVisitor.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.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.VisitCustomEventDeclaration(CustomEventDeclaration customEventDeclaration) - { - return new CodeSnippetTypeMember(MakeSnippet(customEventDeclaration)); - } - - CodeObject IAstVisitor.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.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.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.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.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 parameters) - { - List result = new List(); - foreach (ParameterDeclaration pd in parameters) { - CodeParameterDeclarationExpression pde = pd.AcceptVisitor(this) as CodeParameterDeclarationExpression; - if (pde != null) - result.Add(pde); - } - return result.ToArray(); - } - - CodeObject IAstVisitor.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.VisitVariableInitializer(VariableInitializer variableInitializer) - { - throw new NotSupportedException(); // should be handled by the parent node - } - - CodeObject IAstVisitor.VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration) - { - return new CodeSnippetTypeMember(MakeSnippet(fixedFieldDeclaration)); - } - - CodeObject IAstVisitor.VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer) - { - throw new NotSupportedException(); // should be handled by the parent node - } - - CodeObject IAstVisitor.VisitSyntaxTree(SyntaxTree syntaxTree) - { - CodeCompileUnit cu = new CodeCompileUnit(); - var globalImports = new List (); - 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 () - .Any (ns => ns.Namespace == gi.Namespace); - if (!found) - cn.Imports.Add (gi); - } - } - return cu; - } - - CodeObject IAstVisitor.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.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.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.VisitArraySpecifier(ArraySpecifier arraySpecifier) - { - throw new NotSupportedException(); // handled by parent node - } - - CodeObject IAstVisitor.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.VisitComment (Comment comment) - { - return new CodeComment (comment.Content, comment.CommentType == CommentType.Documentation); - } - - CodeObject IAstVisitor.VisitNewLine(NewLineNode newLineNode) - { - return null; - } - - CodeObject IAstVisitor.VisitWhitespace(WhitespaceNode whitespaceNode) - { - return null; - } - - CodeObject IAstVisitor.VisitText(TextNode textNode) - { - throw new NotSupportedException(); - } - - CodeObject IAstVisitor.VisitPreProcessorDirective (PreProcessorDirective preProcessorDirective) - { - return new CodeComment ("#" + preProcessorDirective.Type.ToString ().ToLowerInvariant ()); - } - - CodeObject IAstVisitor.VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration) - { - throw new NotSupportedException(); // type parameters and constraints are handled together - } - - CodeObject IAstVisitor.VisitConstraint(Constraint constraint) - { - throw new NotSupportedException(); - } - - CodeTypeParameter[] ConvertTypeParameters(IEnumerable typeParameters, IEnumerable constraints) - { - List result = new List(); - 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.VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode) - { - return null; - } - - CodeObject IAstVisitor.VisitIdentifier(Identifier identifier) - { - return null; - } - - CodeObject IAstVisitor.VisitPatternPlaceholder(AstNode placeholder, Pattern pattern) - { - return null; - } - - CodeObject IAstVisitor.VisitDocumentationReference(DocumentationReference documentationReference) - { - return null; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/ITokenWriter.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/ITokenWriter.cs deleted file mode 100644 index 31b73f987..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/ITokenWriter.cs +++ /dev/null @@ -1,161 +0,0 @@ -// 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); - - /// - /// Writes an identifier. - /// - public abstract void WriteIdentifier(Identifier identifier); - - /// - /// Writes a keyword to the output. - /// - public abstract void WriteKeyword(Role role, string keyword); - - /// - /// Writes a token to the output. - /// - public abstract void WriteToken(Role role, string token); - - /// - /// Writes a primitive/literal value - /// - 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); - } - } -} - - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertMissingTokensDecorator.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertMissingTokensDecorator.cs deleted file mode 100644 index 3f9200145..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertMissingTokensDecorator.cs +++ /dev/null @@ -1,123 +0,0 @@ -// 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> nodes = new Stack>(); - List currentList; - readonly ILocatable locationProvider; - - public InsertMissingTokensDecorator(TokenWriter writer, ILocatable locationProvider) - : base(writer) - { - this.locationProvider = locationProvider; - currentList = new List(); - } - - public override void StartNode(AstNode node) - { - currentList.Add(node); - nodes.Push(currentList); - currentList = new List(); - 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertParenthesesVisitor.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertParenthesesVisitor.cs deleted file mode 100644 index 6d622de23..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertParenthesesVisitor.cs +++ /dev/null @@ -1,345 +0,0 @@ -// 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 -{ - /// - /// 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)". - /// - public class InsertParenthesesVisitor : DepthFirstAstVisitor - { - /// - /// 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. - /// - 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; - - /// - /// Gets the row number in the C# 4.0 spec operator precedence table. - /// - 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; - } - - /// - /// Parenthesizes the expression if it does not have the minimum required precedence. - /// - 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertRequiredSpacesDecorator.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertRequiredSpacesDecorator.cs deleted file mode 100644 index e9aca4bf5..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertRequiredSpacesDecorator.cs +++ /dev/null @@ -1,184 +0,0 @@ -// 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 - { - /// - /// Used to insert the minimal amount of spaces so that the lexer recognizes the tokens that were written. - /// - 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; - } - } - } -} \ No newline at end of file diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertSpecialsDecorator.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertSpecialsDecorator.cs deleted file mode 100644 index 0fafdeef0..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/InsertSpecialsDecorator.cs +++ /dev/null @@ -1,157 +0,0 @@ -// 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 positionStack = new Stack(); - 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 - /// - /// Writes all specials from start to end (exclusive). Does not touch the positionStack. - /// - 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); - } - } - } - - /// - /// Writes all specials between the current position (in the positionStack) and the next - /// node with the specified role. Advances the current position. - /// - 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; - } - } - } - - /// - /// Writes all specials between the current position (in the positionStack) and the specified node. - /// Advances the current position. - /// - 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 - } -} - - - - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/TextWriterOutputFormatter.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/TextWriterOutputFormatter.cs deleted file mode 100644 index 277b1c3e9..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/TextWriterOutputFormatter.cs +++ /dev/null @@ -1,419 +0,0 @@ -// 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 -{ - /// - /// Writes C# code into a TextWriter. - /// - 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; - } - } - - /// - /// Gets the escape sequence for the specified character within a char literal. - /// Does not include the single quotes surrounding the char literal. - /// - public static string ConvertCharLiteral(char ch) - { - if (ch == '\'') { - return "\\'"; - } - return ConvertChar(ch); - } - - /// - /// Gets the escape sequence for the specified character. - /// - /// This method does not convert ' or ". - 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(); - } - } - } - - /// - /// Converts special characters to escape sequences within the given string. - /// - 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) - { - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/CSharpParser.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/CSharpParser.cs deleted file mode 100644 index 158b86ce3..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/CSharpParser.cs +++ /dev/null @@ -1,4096 +0,0 @@ -// -// CSharpParser.cs -// -// Author: -// Mike Krüger -// -// 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 namespaceStack = new Stack(); - - 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 GetAttributes(IEnumerable 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 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); - // 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("", 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 "" identifiers in namespace names (on certain bugs in the input file) - if (memberName.Name == "") - 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 typeStack = new Stack(); - - 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 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 modifierTable = new Dictionary(); - 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 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 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 == "") { - 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 Errors = new List(); - - 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 Errors { - get { - return errorReportPrinter.Errors.Where(e => e.ErrorType == ErrorType.Error); - } - } - - public IEnumerable Warnings { - get { - return errorReportPrinter.Errors.Where(e => e.ErrorType == ErrorType.Warning); - } - } - - public IEnumerable ErrorsAndWarnings { - get { return errorReportPrinter.Errors; } - } - - /// - /// Parses a C# code file. - /// - /// The source code to parse. - /// 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. - /// Returns the syntax tree. - public SyntaxTree Parse(string program, string fileName = "") - { - return Parse(new StringTextSource(program), fileName); - } - - /// - /// Parses a C# code file. - /// - /// The text reader containing the source code to parse. - /// 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. - /// Returns the syntax tree. - public SyntaxTree Parse(TextReader reader, string fileName = "") - { - return Parse(new StringTextSource(reader.ReadToEnd()), fileName); - } - - /// - /// Converts a Mono.CSharp syntax tree into an NRefactory syntax tree. - /// - 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(); - 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; - } - } - - /// - /// Callback that gets called with the Mono.CSharp syntax tree whenever some code is parsed. - /// - public Action CompilationUnitCallback { - get; - set; - } - - /// - /// 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 - /// call and might be missing other nodes (e.g. method bodies). - /// The default is false. - /// - public bool GenerateTypeSystemMode { - get; - set; - } - - TextLocation initialLocation = new TextLocation(1, 1); - - /// - /// 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). - /// - public TextLocation InitialLocation { - get { return initialLocation; } - set { initialLocation = value; } - } - - internal static object parseLock = new object(); - - /// - /// Parses a C# code file. - /// - /// The stream containing the source code to parse. - /// 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. - /// Returns the syntax tree. - public SyntaxTree Parse(Stream stream, string fileName = "") - { - return Parse(new StreamReader(stream), fileName); - } - - /// - /// Parses a C# code file. - /// - /// The source code to parse. - /// 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. - /// Returns the syntax tree. - 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(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 ParseTypeMembers(string code) - { - return ParseTypeMembers(code, initialLocation.Line, initialLocation.Column); - } - - IEnumerable 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(); - 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(); - } - - public IEnumerable ParseStatements(string code) - { - return ParseStatements(code, initialLocation.Line, initialLocation.Column); - } - - IEnumerable 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(); - } - - 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; - } - /* - /// - /// Parses a file snippet; guessing what the code snippet represents (whole file, type members, block, type reference, expression). - /// - 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(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; - } - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/CompilerSettings.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/CompilerSettings.cs deleted file mode 100644 index 1146ff85e..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/CompilerSettings.cs +++ /dev/null @@ -1,151 +0,0 @@ -// 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 -{ - /// - /// C# compiler settings. - /// - [Serializable] - public class CompilerSettings : AbstractFreezable - { - protected override void FreezeInternal() - { - conditionalSymbols = FreezableHelper.FreezeList(conditionalSymbols); - specificWarningsAsErrors = FreezableHelper.FreezeList(specificWarningsAsErrors); - disabledWarnings = FreezableHelper.FreezeList(disabledWarnings); - base.FreezeInternal(); - } - - /// - /// Creates a new CompilerSettings instance. - /// - public CompilerSettings() - { - } - - bool allowUnsafeBlocks = true; - - /// - /// Gets/Sets whether unsafe code is allowed. - /// The default is true. If set to false, parsing unsafe code will result in parser errors. - /// - public bool AllowUnsafeBlocks { - get { return allowUnsafeBlocks; } - set { - FreezableHelper.ThrowIfFrozen(this); - allowUnsafeBlocks = value; - } - } - - bool checkForOverflow; - - /// - /// Gets/Sets whether overflow checking is enabled. - /// The default is false. This setting effects semantic analysis. - /// - public bool CheckForOverflow { - get { return checkForOverflow; } - set { checkForOverflow = value; } - } - - Version languageVersion = new Version((int)Mono.CSharp.LanguageVersion.Default, 0); - - /// - /// Gets/Sets the language version used by the parser. - /// Using language constructs newer than the supplied version will result in parser errors. - /// - public Version LanguageVersion { - get { return languageVersion; } - set { - FreezableHelper.ThrowIfFrozen(this); - if (value == null) - throw new ArgumentNullException(); - languageVersion = value; - } - } - - IList conditionalSymbols = new List(); - - /// - /// Gets/Sets the list of conditional symbols that are defined project-wide. - /// - public IList ConditionalSymbols { - get { return conditionalSymbols; } - } - - bool treatWarningsAsErrors; - - public bool TreatWarningsAsErrors { - get { return treatWarningsAsErrors; } - set { - FreezableHelper.ThrowIfFrozen(this); - treatWarningsAsErrors = value; - } - } - - IList specificWarningsAsErrors = new List(); - - /// - /// Allows treating specific warnings as errors without setting to true. - /// - public IList SpecificWarningsAsErrors { - get { return specificWarningsAsErrors; } - } - - int warningLevel = 4; - - public int WarningLevel { - get { return warningLevel; } - set { - FreezableHelper.ThrowIfFrozen(this); - warningLevel = value; - } - } - - IList disabledWarnings = new List(); - - /// - /// Disables the specified warnings. - /// - public IList 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/SeekableStreamReader.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/SeekableStreamReader.cs deleted file mode 100644 index 5a853c54e..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/SeekableStreamReader.cs +++ /dev/null @@ -1,103 +0,0 @@ -// -// SeekableStreamReader.cs -// -// Author: -// Mike Krüger -// -// 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 () - { - } - - /// - /// 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. - /// - 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++); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/CryptoConvert.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/CryptoConvert.cs deleted file mode 100644 index a56e94d01..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/CryptoConvert.cs +++ /dev/null @@ -1,754 +0,0 @@ -// -// CryptoConvert.cs - Crypto Convertion Routines -// -// Author: -// Sebastien Pouliot -// -// (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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolFile.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolFile.cs deleted file mode 100644 index 8431c70a4..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolFile.cs +++ /dev/null @@ -1,637 +0,0 @@ -// -// 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 methods = new List (); - List sources = new List (); - List comp_units = new List (); - Dictionary 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 (); - - 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 source_file_hash; - Dictionary compile_unit_hash; - - List method_list; - Dictionary method_token_hash; - Dictionary 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 (); - compile_unit_hash = new Dictionary (); - } - - 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 (); - method_list = new List (); - - 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 (); - - 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 (); - 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; - } - } - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolTable.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolTable.cs deleted file mode 100644 index 277f25a7f..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolTable.cs +++ /dev/null @@ -1,1437 +0,0 @@ -// -// 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 - { - 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 captured_vars = new List (); - List captured_scopes = new List (); - - 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 include_files; - List 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 (); - } - - public void AddFile (SourceFileEntry file) - { - if (!creating) - throw new InvalidOperationException (); - - if (include_files == null) - include_files = new List (); - - 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 (); - for (int i = 0; i < count_includes; i++) - include_files.Add (file.GetSourceFile (reader.ReadLeb128 ())); - } - - int count_ns = reader.ReadLeb128 (); - namespaces = new List (); - 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 (); - - 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 (); - 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolWriter.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolWriter.cs deleted file mode 100644 index b2c2afdba..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolWriter.cs +++ /dev/null @@ -1,238 +0,0 @@ -// -// 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 methods; - List sources; - List comp_units; - protected readonly MonoSymbolFile file; - string filename; - - private SourceMethodBuilder current_method; - Stack current_method_stack = new Stack (); - - public MonoSymbolWriter (string filename) - { - this.methods = new List (); - this.sources = new List (); - this.comp_units = new List (); - 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); - } - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/SourceMethodBuilder.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/SourceMethodBuilder.cs deleted file mode 100644 index bd801f657..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/SourceMethodBuilder.cs +++ /dev/null @@ -1,190 +0,0 @@ -// -// 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 _locals; - List _blocks; - List _scope_vars; - Stack _block_stack; - readonly List 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 (); - } - - 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 (); - } - - if (_blocks == null) - _blocks = new List (); - - 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 (); - 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 (); - _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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/anonymous.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/anonymous.cs deleted file mode 100644 index e7f003784..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/anonymous.cs +++ /dev/null @@ -1,2292 +0,0 @@ -// -// 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 used_parent_storeys; - List children_references; - - // A list of hoisted parameters - protected List hoisted_params; - List hoisted_local_params; - protected List 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 (); - - 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 (); - 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 (); - - 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 (); - - 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 (); - - 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 (); - - 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 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 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 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 (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 compatibles; - - public ParametersBlock Block; - - public AnonymousMethodExpression (Location loc) - { - this.loc = loc; - this.compatibles = new Dictionary (); - } - - #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 - // - 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 - // - 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 { - // public static DelegateType cache; - // } - // - // We then specialize local variable to capture all generic parameters - // and delegate type, e.g. "Wrap 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 parameters; - - private AnonymousTypeClass (ModuleContainer parent, MemberName name, IList parameters, Location loc) - : base (parent, name, parent.Evaluator != null ? Modifiers.PUBLIC : Modifiers.INTERNAL) - { - this.parameters = parameters; - } - - public static AnonymousTypeClass Create (TypeContainer parent, IList 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 Parameters { - get { - return parameters; - } - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/argument.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/argument.cs deleted file mode 100644 index a5edeb53c..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/argument.cs +++ /dev/null @@ -1,674 +0,0 @@ -// -// 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 ordered; - - public ArgumentsOrdered (Arguments args) - : base (args.Count) - { - AddRange (args); - ordered = new List (); - } - - public void AddOrdered (MovableArgument arg) - { - ordered.Add (arg); - } - - public override void FlowAnalysis (FlowAnalysisContext fc, List 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 args; - - public Arguments (int capacity) - { - args = new List (capacity); - } - - private Arguments (List 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 dups; - - if ((dup_args && Count != 0) || prepareAwait) - dups = new List (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 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.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; } - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assembly.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assembly.cs deleted file mode 100644 index f93c03839..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assembly.cs +++ /dev/null @@ -1,1257 +0,0 @@ -// -// 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; -#else -using SecurityType = System.Collections.Generic.Dictionary; -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 added_modules; - SecurityType declarative_security; - Dictionary 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 (); - 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 (); - } 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 - { - 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 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 where T : class - { - protected readonly CompilerContext compiler; - - protected readonly List paths; - - protected AssemblyReferencesLoader (CompilerContext compiler) - { - this.compiler = compiler; - - paths = new List (); - 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> loaded) - { - compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading); - - loaded = new List> (); - - // - // 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.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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assign.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assign.cs deleted file mode 100644 index 2bdc3331a..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assign.cs +++ /dev/null @@ -1,956 +0,0 @@ -// -// 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 { - - /// - /// This interface is implemented by expressions that can be assigned to. - /// - /// - /// 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. - /// - 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. - */ - } - - /// - /// An Expression to hold a temporary value. - /// - /// - /// 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. - /// - /// - 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); - } - } - } - - /// - /// The Assign node takes care of assigning the value of source into - /// the expression represented by target. - /// - 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/async.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/async.cs deleted file mode 100644 index 68bbd3e18..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/async.cs +++ /dev/null @@ -1,1005 +0,0 @@ -// -// 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 - { - 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 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> stack_fields; - Dictionary> 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> (); - } - - #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 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 (); - 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 existing_fields = null; - if (stack_fields == null) { - stack_fields = new Dictionary> (); - } 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 (); - stack_fields.Add (type, existing_fields); - } - - existing_fields.Add (field); - - return field; - } - - protected override bool DoDefineMembers () - { - PredefinedType builder_type; - PredefinedMember bf; - PredefinedMember bs; - PredefinedMember sr; - PredefinedMember se; - PredefinedMember 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 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 (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 (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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/attribute.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/attribute.cs deleted file mode 100644 index 9e0437492..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/attribute.cs +++ /dev/null @@ -1,2140 +0,0 @@ -// -// 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; -using BadImageFormat = IKVM.Reflection.BadImageFormatException; -using IKVM.Reflection; -using IKVM.Reflection.Emit; -#else -using SecurityType = System.Collections.Generic.Dictionary; -using BadImageFormat = System.BadImageFormatException; -using System.Reflection; -using System.Reflection.Emit; -#endif - -namespace Mono.CSharp { - - /// - /// Base class for objects that can have Attributes applied to them. - /// - 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; - } - } - - /// - /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder - /// - public abstract void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa); - - /// - /// Returns one AttributeTarget for this element. - /// - public abstract AttributeTargets AttributeTargets { get; } - - public abstract bool IsClsComplianceRequired (); - - /// - /// Gets list of valid attribute targets for explicit target declaration. - /// The first array item is default target. Don't break this rule. - /// - 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> 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]; - } - } - - /// - /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true. - /// - 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 (named_arg_count); - - named_values = new List> (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) member, a)); - } - - return true; - } - - /// - /// Get a string containing a list of valid targets for the attribute 'attr' - /// - 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; - } - - /// - /// Returns custom name of indexer - /// - 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; - } - - /// - /// Returns condition of ConditionalAttribute - /// - 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; - } - - /// - /// Creates the instance of ObsoleteAttribute from this attribute instance - /// - 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); - } - - /// - /// 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. - /// - 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; - } - - /// - /// Tests permitted SecurityAction for assembly or other types - /// - 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 (); - } - - /// - /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table. - /// - /// - 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 (); - } - - /// - /// Emit attribute for Attributable symbol - /// - public void Emit (Dictionary> 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 (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 Attrs; -#if FULL_AST - public readonly List> Sections = new List> (); -#endif - - public Attributes (Attribute a) - { - Attrs = new List (); - Attrs.Add (a); - -#if FULL_AST - Sections.Add (Attrs); -#endif - } - - public Attributes (List attrs) - { - Attrs = attrs ?? new List (); -#if FULL_AST - Sections.Add (attrs); -#endif - } - - public void AddAttribute (Attribute attr) - { - Attrs.Add (attr); - } - - public void AddAttributes (List 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 (Attrs.Count); - foreach (Attribute a in Attrs) - al.Add (a.Clone ()); - - return new Attributes (al); - } - - /// - /// Checks whether attribute target is valid for the current element - /// - 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; - } - - /// - /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true - /// - public Attribute[] SearchMulti (PredefinedAttribute t) - { - List ar = null; - - foreach (Attribute a in Attrs) { - if (a.ResolveTypeForComparison () == t) { - if (ar == null) - ar = new List (Attrs.Count); - ar.Add (a); - } - } - - return ar == null ? null : ar.ToArray (); - } - - public void Emit () - { - CheckTargets (); - - Dictionary> ld = Attrs.Count > 1 ? new Dictionary> () : 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[] 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; - } - } - - - /// - /// Helper class for attribute verification routine. - /// - static class AttributeTester - { - /// - /// Common method for Obsolete error/warning reporting. - /// - 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 - // 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 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 (); - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cfold.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cfold.cs deleted file mode 100644 index da85bf386..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cfold.cs +++ /dev/null @@ -1,1192 +0,0 @@ -// -// 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"); - } - - /// - /// Constant expression folder for binary operations. - /// - /// Returns null if the expression can not be folded. - /// - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/class.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/class.cs deleted file mode 100644 index ae4c02766..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/class.cs +++ /dev/null @@ -1,3895 +0,0 @@ -// -// 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; -using IKVM.Reflection; -using IKVM.Reflection.Emit; -#else -using SecurityType = System.Collections.Generic.Dictionary; -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 containers; - - TypeDefinition main_container; - - protected Dictionary 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 (); - } - - public override TypeSpec CurrentType { - get { - return null; - } - } - - public Dictionary DefinedNames { - get { - return defined_names; - } - } - - public TypeDefinition PartialContainer { - get { - return main_container; - } - protected set { - main_container = value; - } - } - - public IList 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 members; - - // Holds a list of fields that have initializers - protected List initialized_fields; - - // Holds a list of static fields that have initializers - protected List initialized_static_fields; - - Dictionary hoisted_base_call_proxies; - - Dictionary Cache = new Dictionary (); - - // - // 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 type_bases; - - // Partial parts for classes only - List 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" }; - - /// - /// The pending methods that need to be implemented - // (interfaces or abstract methods) - /// - PendingImplementation pending; - - protected TypeDefinition (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind) - : base (parent, name, attrs, kind) - { - PartialContainer = this; - members = new List (); - } - - #region Properties - - public List 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 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 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 (); - - 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; - } - - /// - /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute - /// - 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 (); - - 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 (4); - } - - initialized_static_fields.Add (expression); - } else { - if (initialized_fields == null) - initialized_fields = new List (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 baseTypes) - { - type_bases = baseTypes; - } - - /// - /// 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'. - /// - 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 found_matched = new List (); - - 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 (); - 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 (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 (); - - 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 : IB - // interface IB : IC - // interface IC - // - 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; - } - - /// - /// Populates our TypeBuilder with fields and methods - /// - 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; - } - - /// - /// 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. - /// - 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); - } - } - - /// - /// Method container contains Equals method - /// - public bool HasEquals { - get { - return (cached_method & CachedMethods.Equals) != 0; - } - } - - /// - /// Method container contains GetHashCode method - /// - 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); - } - - /// - /// Defines the default constructors - /// - 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 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 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; - - // - // Modifiers allowed in a struct declaration - // - 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); - } - } - - /// - /// Interfaces - /// - public sealed class Interface : TypeDefinition { - - /// - /// Modifiers allowed in a class declaration - /// - 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 ()); - } - - /// - /// Gets base method and its return type - /// - 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_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; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/codegen.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/codegen.cs deleted file mode 100644 index 55a061cf0..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/codegen.cs +++ /dev/null @@ -1,1365 +0,0 @@ -// -// 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 -{ - /// - /// An Emit Context is created for each body of code (from methods, - /// properties bodies, indexer bodies or constructor bodies) - /// - public class EmitContext : BuilderContext - { - // TODO: Has to be private - public readonly ILGenerator ig; - - /// - /// The value that is allowed to be returned or NULL if there is no - /// return type. - /// - readonly TypeSpec return_type; - - /// - /// 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) - /// - Dictionary temporary_storage; - - /// - /// The location where we store the return value. - /// - public LocalBuilder return_value; - - - /// - /// Current loop begin and end labels. - /// - public Label LoopBegin, LoopEnd; - - /// - /// Default target in a switch statement. Only valid if - /// InSwitch is true - /// - public Label DefaultTarget; - - /// - /// If this is non-null, points to the current switch statement - /// - public Switch Switch; - - /// - /// Whether we are inside an anonymous method. - /// - public AnonymousExpression CurrentAnonymousMethod; - - readonly IMemberContext member_context; - - readonly SourceMethodBuilder methodSymbols; - - DynamicSiteClass dynamic_site_container; - - Label? return_label; - - List 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 StatementEpilogue { - get { - return epilogue_expressions; - } - } - - public LocalVariable AsyncThrowVariable { get; set; } - - public List TryFinallyUnwind { get; set; } - - #endregion - - public void AddStatementEpilog (IExpressionCleanup cleanupExpression) - { - if (epilogue_expressions == null) { - epilogue_expressions = new List (); - } 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 - } - - /// - /// This is called immediately before emitting an IL opcode to tell the symbol - /// writer to which source line this opcode belongs. - /// - 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; - } - - /// - /// Returns a temporary storage for a variable of type t as - /// a local variable in the current body. - /// - public LocalBuilder GetTemporaryLocal (TypeSpec t) - { - if (temporary_storage != null) { - object o; - if (temporary_storage.TryGetValue (t, out o)) { - if (o is Stack) { - var s = (Stack) 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 (ReferenceEquality.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; - if (s == null) { - s = new Stack (); - s.Push ((LocalBuilder)o); - temporary_storage [t] = s; - } - s.Push (b); - } - - /// - /// 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. - /// - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/complete.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/complete.cs deleted file mode 100644 index 3504302d5..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/complete.cs +++ /dev/null @@ -1,226 +0,0 @@ -// -// 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 results, string prefix, IEnumerable 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 (); - - 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 (); - 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 (); - 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]); - } - } - -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/const.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/const.cs deleted file mode 100644 index eef90b346..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/const.cs +++ /dev/null @@ -1,237 +0,0 @@ -// -// 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; - } - - /// - /// Defines the constant in the @parent - /// - 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); - } - - /// - /// Emits the field value by evaluating the expression - /// - 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/constant.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/constant.cs deleted file mode 100644 index a50baacc7..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/constant.cs +++ /dev/null @@ -1,2496 +0,0 @@ -// -// 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 { - - /// - /// Base class for constants and literals. - /// - 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 () + ")"; - } - - /// - /// This is used to obtain the actual value of the literal - /// cast into an object. - /// - 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); - } - - /// - /// Maybe ConvertTo name is better. It tries to convert `this' constant to target_type. - /// It throws OverflowException - /// - // 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); - } - - /// - /// Need to pass type as the constant can require a boxing - /// and in such case no optimization is possible - /// - 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); - } - - /// - /// Attempts to perform an implicit constant conversion of the IntConstant - /// into a different data type using casts (See Implicit Constant - /// Expression Conversions) - /// - 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); - } - } - - /// - /// 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. - /// - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/context.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/context.cs deleted file mode 100644 index 230aa1257..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/context.cs +++ /dev/null @@ -1,751 +0,0 @@ -// -// 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 - { - /// - /// 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. - /// - CheckedScope = 1 << 0, - - /// - /// 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. - /// - 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 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_map = new Dictionary (); - - 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 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 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 (); - 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 - { - /// - /// 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. - /// - 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[] Identifiers = new Dictionary[Tokenizer.MaxIdentifierLength + 1]; - public readonly List ParametersStack = new List (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 ()); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/convert.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/convert.cs deleted file mode 100644 index 065c9a7e3..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/convert.cs +++ /dev/null @@ -1,2266 +0,0 @@ -// -// 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 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 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 - 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); - } - - /// - /// 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. - /// - 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; - } - - /// - /// Finds "most encompassed type" according to the spec (13.4.2) - /// amongst the methods in the MethodGroupExpr - /// - public static TypeSpec FindMostEncompassedType (IList 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 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 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 (); - - 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); - } - - /// - /// Finds the most specific target Tx according to section 13.4.4 - /// - static public TypeSpec FindMostSpecificTarget (IList list, - TypeSpec target, bool apply_explicit_conv_rules) - { - List 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 (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 (); - - 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); - } - - /// - /// User-defined Implicit conversions - /// - static public Expression ImplicitUserConversion (ResolveContext ec, Expression source, TypeSpec target, Location loc) - { - return UserDefinedConversion (ec, source, target, UserConversionRestriction.ImplicitOnly, loc); - } - - /// - /// User-defined Explicit conversions - /// - static Expression ExplicitUserConversion (ResolveContext ec, Expression source, TypeSpec target, Location loc) - { - return UserDefinedConversion (ec, source, target, 0, loc); - } - - static void FindApplicableUserDefinedConversionOperators (ResolveContext rc, IList operators, Expression source, TypeSpec target, UserConversionRestriction restr, ref List 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 (); - - candidates.Add (op); - } - } - - // - // User-defined conversions - // - public static Expression UserDefinedConversion (ResolveContext rc, Expression source, TypeSpec target, UserConversionRestriction restr, Location loc) - { - List 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; - } - - /// - /// 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'. - /// - 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; - } - - - /// - /// 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. - /// - 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; - } - - /// - /// Attempts to implicitly convert `source' into `target_type', using - /// ImplicitConversion. If there is no implicit conversion, then - /// an error is signaled - /// - 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; - } - - /// - /// 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 - /// - /// - 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; - } - - /// - /// Returns whether an explicit reference conversion can be performed - /// from source_type to target_type - /// - 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"); - } - - /// - /// Implements Explicit Reference conversions - /// - 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 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 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; - } - - /// - /// Performs an explicit conversion of the expression `expr' whose - /// type is expr.Type to `target_type'. - /// - 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; - } - - /// - /// Same as ExplicitConversion, only it doesn't include user defined conversions - /// - 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; - } - - /// - /// Performs an explicit conversion of the expression `expr' whose - /// type is expr.Type to `target_type'. - /// - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.cs deleted file mode 100644 index 868c1394f..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.cs +++ /dev/null @@ -1,16238 +0,0 @@ -// 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 -{ - /// - /// The C# Parser - /// - 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; - - /// - /// Current block is used to add statements as we find - /// them. - /// - Block current_block; - - BlockVariable current_variable; - - Delegate current_delegate; - - AnonymousMethodExpression current_anonymous_method; - - /// - /// This is used by the unary_expression code to resolve - /// a name against a parameter. - /// - - // 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 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_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 parameters_bucket; - - // - // Full AST support members - // - LocationsBag lbag; - List> mod_locations; - Location parameterModifierLocation, savedLocation, savedEventAssignLocation; - Location savedAttrParenOpenLocation, savedAttrParenCloseLocation, savedOperatorLocation; - Stack> locationListStack = new Stack> (); // used for type parameters - Stack opt_intoStack = new Stack (); - - bool HadAttributeParens; - List attributeArgumentCommas = new List (); - List parameterListCommas = new List (); - Stack location_stack; -#line default - - /** error output stream. - It should be changeable. - */ - public System.IO.TextWriter ErrorOutput = System.Console.Out; - - /** simplified error message. - @see yyerror - */ - 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 (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) 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)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 (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 ("", 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) 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) 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 (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 () { - 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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 ()); - } - -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 ()); - } - -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 (2); - types.Add ((FullNamedExpression) yyVals[0+yyTop]); - yyVal = types; - } - -void case_404() -#line 3279 "cs-parser.jay" -{ - var types = (List) 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) 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) 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 (); - a.Add ((Expression) yyVals[0+yyTop]); - yyVal = a; - } - -void case_478() -#line 3540 "cs-parser.jay" -{ - var a = (List)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)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)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 (4); - list.Add ((Expression) yyVals[0+yyTop]); - yyVal = list; - } - -void case_510() -#line 3735 "cs-parser.jay" -{ - var list = (List) 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) yyVals[-3+yyTop], - new ComposedTypeSpecifier (((List) 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) 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 (4); - a.Add ((AnonymousTypeParameter) yyVals[0+yyTop]); - yyVal = a; - } - -void case_536() -#line 3911 "cs-parser.jay" -{ - var a = (List) 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) 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 (4); - list.Add ((Expression) yyVals[0+yyTop]); - yyVal = list; - } - -void case_556() -#line 4032 "cs-parser.jay" -{ - var list = (List) 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 (4); - pars.Add ((Parameter) yyVals[0+yyTop]); - parameterListCommas.Clear (); - yyVal = pars; - } - -void case_680() -#line 4781 "cs-parser.jay" -{ - var pars = (List) 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) 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) 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) 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) yyVals[-1+yyTop]); - } - -void case_757() -#line 5234 "cs-parser.jay" -{ - var constraints = new List (1); - constraints.Add ((Constraints) yyVals[0+yyTop]); - yyVal = constraints; - } - -void case_758() -#line 5240 "cs-parser.jay" -{ - var constraints = (List) 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) 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 (1); - constraints.Add ((FullNamedExpression) yyVals[0+yyTop]); - yyVal = constraints; - } - -void case_762() -#line 5281 "cs-parser.jay" -{ - var constraints = (List) 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) 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 (2); - - l.Add ((Catch) yyVals[0+yyTop]); - yyVal = l; - } - -void case_957() -#line 6385 "cs-parser.jay" -{ - var l = (List) 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 (); - - 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 (); - - 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 (); - - 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_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 (""), 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)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)yyVals[0+yyTop]; - yyVal = null; - } - -void case_1062() -#line 7240 "cs-parser.jay" -{ - module.DocumentationBuilder.ParsedBuiltinType = (TypeExpression)yyVals[-3+yyTop]; - module.DocumentationBuilder.ParsedParameters = (List)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)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)yyVals[0+yyTop] ?? new List (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)yyVals[0+yyTop] ?? new List (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)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 (); - parameters.Add ((DocumentationParameter) yyVals[0+yyTop]); - yyVal = parameters; - } - -void case_1077() -#line 7320 "cs-parser.jay" -{ - var parameters = yyVals[-2+yyTop] as List; - 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" - -// -// A class used to hold info about an operator declarator -// -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> (); - - mod_locations.Add (Tuple.Create ((Modifiers) token, loc)); -} - -List> 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_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 (); - 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 (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 == "") - 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 ""; - - 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 ""; - - // 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 diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.jay b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.jay deleted file mode 100644 index 25df449fb..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.jay +++ /dev/null @@ -1,8195 +0,0 @@ -%{ -// -// 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 -{ - /// - /// The C# Parser - /// - 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; - - /// - /// Current block is used to add statements as we find - /// them. - /// - Block current_block; - - BlockVariable current_variable; - - Delegate current_delegate; - - AnonymousMethodExpression current_anonymous_method; - - /// - /// This is used by the unary_expression code to resolve - /// a name against a parameter. - /// - - // 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 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_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 parameters_bucket; - - // - // Full AST support members - // - LocationsBag lbag; - List> mod_locations; - Location parameterModifierLocation, savedLocation, savedEventAssignLocation; - Location savedAttrParenOpenLocation, savedAttrParenCloseLocation, savedOperatorLocation; - Stack> locationListStack = new Stack> (); // used for type parameters - Stack opt_intoStack = new Stack (); - - bool HadAttributeParens; - List attributeArgumentCommas = new List (); - List parameterListCommas = new List (); - Stack 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 ("", 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) $1; - $$ = new Attributes (sect); - } - | attribute_sections attribute_section - { - Attributes attrs = $1 as Attributes; - var sect = (List) $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 (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 () { - 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 (4) { (Attribute) $1 }; - } - | attribute_list COMMA attribute - { - var attrs = (List) $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) $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) $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) $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) $1; - $$ = new ParametersCompiled (pars_list.ToArray ()); - lbag.AddLocation ($$, parameterListCommas); - } - | fixed_parameters COMMA parameter_array - { - var pars_list = (List) $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) $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) $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) $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) $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) $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) $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 ()); - } - | 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 ()); - } - | 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 (2); - types.Add ((FullNamedExpression) $1); - $$ = types; - } - | type_list COMMA base_type_name - { - var types = (List) $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) $2, GetLocation ($1)); - } - lbag.AddLocation ($$, GetLocation ($3)); - } - | OPEN_BRACE member_initializer_list COMMA CLOSE_BRACE - { - $$ = new CollectionOrObjectInitializers ((List) $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 (); - a.Add ((Expression) $1); - $$ = a; - } - | member_initializer_list COMMA member_initializer - { - var a = (List)$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)$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)$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 (4); - list.Add ((Expression) $1); - $$ = list; - } - | expression_list COMMA expression_or_error - { - var list = (List) $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) $4, - new ComposedTypeSpecifier (((List) $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) $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 (4); - a.Add ((AnonymousTypeParameter) $1); - $$ = a; - } - | anonymous_type_parameters COMMA anonymous_type_parameter - { - var a = (List) $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) $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 (4); - list.Add ((Expression) $1); - $$ = list; - } - | variable_initializer_list COMMA variable_initializer - { - var list = (List) $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 (4); - pars.Add ((Parameter) $1); - parameterListCommas.Clear (); - $$ = pars; - } - | lambda_parameter_list COMMA lambda_parameter - { - var pars = (List) $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) $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) $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) $2); - lbag.AppendToMember (current_type, GetLocation ($1)); - } - | COLON type_list error - { - Error_SyntaxError (yyToken); - - current_type.SetBaseTypes ((List) $2); - } - ; - -opt_type_parameter_constraints_clauses - : /* empty */ - | type_parameter_constraints_clauses - { - $$ = $1; - } - ; - -type_parameter_constraints_clauses - : type_parameter_constraints_clause - { - var constraints = new List (1); - constraints.Add ((Constraints) $1); - $$ = constraints; - } - | type_parameter_constraints_clauses type_parameter_constraints_clause - { - var constraints = (List) $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) $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 (1); - constraints.Add ((FullNamedExpression) $1); - $$ = constraints; - } - | type_parameter_constraints COMMA type_parameter_constraint - { - var constraints = (List) $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) $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) $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 (2); - - l.Add ((Catch) $1); - $$ = l; - } - | catch_clauses catch_clause - { - var l = (List) $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 (); - - 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 (); - - 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 (); - - 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_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 (""), 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)$2; - } - | builtin_types opt_doc_method_sig - { - module.DocumentationBuilder.ParsedBuiltinType = (TypeExpression)$1; - module.DocumentationBuilder.ParsedParameters = (List)$2; - $$ = null; - } - | VOID opt_doc_method_sig - { - module.DocumentationBuilder.ParsedBuiltinType = new TypeExpression (compiler.BuiltinTypes.Void, GetLocation ($1)); - module.DocumentationBuilder.ParsedParameters = (List)$2; - $$ = null; - } - | builtin_types DOT IDENTIFIER opt_doc_method_sig - { - module.DocumentationBuilder.ParsedBuiltinType = (TypeExpression)$1; - module.DocumentationBuilder.ParsedParameters = (List)$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)$6; - $$ = new MemberName ((MemberName) $1, MemberCache.IndexerNameAlias, Location.Null); - } - | EXPLICIT OPERATOR type opt_doc_method_sig - { - var p = (List)$4 ?? new List (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)$4 ?? new List (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)$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 (0); - } - | doc_parameters - ; - -doc_parameters - : doc_parameter - { - var parameters = new List (); - parameters.Add ((DocumentationParameter) $1); - $$ = parameters; - } - | doc_parameters COMMA doc_parameter - { - var parameters = $1 as List; - 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); - } - ; - -%% - -// -// A class used to hold info about an operator declarator -// -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> (); - - mod_locations.Add (Tuple.Create ((Modifiers) token, loc)); -} - -List> 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_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 (); - 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 (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 == "") - 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 ""; - - 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 ""; - - // A bit more robust. - default: - return yyNames [token]; - } -} - -/* end end end */ -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-tokenizer.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-tokenizer.cs deleted file mode 100644 index a423eb50f..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-tokenizer.cs +++ /dev/null @@ -1,4033 +0,0 @@ -// -// 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; } - } - } - - /// - /// Tokenizer for C# source code. - /// - public class Tokenizer : yyParser.yyInput - { - class KeywordEntry - { - public readonly T Token; - public KeywordEntry Next; - public readonly char[] Value; - - public KeywordEntry (string value,T token) - { - this.Value = value.ToCharArray (); - this.Token = token; - } - } - - sealed class IdentifiersComparer : IEqualityComparer - { - 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 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[][] keywords; - static readonly KeywordEntry[][] keywords_preprocessor; - static readonly HashSet 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 (); - - 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 ifstack; - - public const int MaxIdentifierLength = 512; - public const int MaxNumberLength = 512; - - readonly char[] id_builder; - readonly Dictionary[] 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_stack = new Stack (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 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 all - // methods reverse the order - var clone = t.ifstack.ToArray (); - Array.Reverse (clone); - ifstack = new Stack (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 (KeywordEntry[][] keywords, string kw, T token) - { - int length = kw.Length; - if (keywords[length] == null) { - keywords[length] = new KeywordEntry['z' - '_' + 1]; - } - - int char_index = kw[0] - '_'; - var kwe = keywords[length][char_index]; - if (kwe == null) { - keywords[length][char_index] = new KeywordEntry (kw, token); - return; - } - - while (kwe.Next != null) { - kwe = kwe.Next; - } - - kwe.Next = new KeywordEntry (kw, token); - } - - // - // Class initializer - // - static Tokenizer () - { - keyword_strings = new HashSet (); - - // 11 is the length of the longest keyword for now - keywords = new KeywordEntry[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[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> genericDimensionLocations = new Stack> (); - - public List GenericDimensionLocations { - get { - if (genericDimensionLocations.Count == 0) - return null; - return genericDimensionLocations.Pop (); - } - } - - bool parse_less_than (ref int genericDimension) - { - genericDimensionLocations.Push (new List ()); - 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 checksum_bytes = new List (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); - } - - /// - /// Handles #pragma directive - /// - 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 (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 (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 - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/decl.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/decl.cs deleted file mode 100644 index 56d423ad2..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/decl.cs +++ /dev/null @@ -1,1297 +0,0 @@ -// -// 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; - } - } - - /// - /// Base representation for members. This is used to keep track - /// of Name, Location and Modifier flags, and handling Attributes. - /// - [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; } - } - - /// - /// Modifier flags that the user specified in the source code - /// - 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; - - /// - /// Location where this declaration happens - /// - public Location Location { - get { return member_name.Location; } - } - - /// - /// XML documentation comment - /// - protected string comment; - - /// - /// Represents header string for documentation comment - /// for each member types. - /// - 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 - } - - /// - /// MemberCore flags at first detected then cached - /// - 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 (); - } - - /// - /// Base Emit method. This is also entry point for CLS-Compliant verification. - /// - 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_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; - } - } - - /// - /// Returns instance of ObsoleteAttribute for this MemberCore - /// - 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; - } - - /// - /// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements - /// - 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; - } - - /// - /// Analyze whether CLS-Compliant verification must be execute for this MemberCore. - /// - 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; - } - - /// - /// Returns true when MemberCore is exposed from assembly. - /// - 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); - } - - /// - /// Goes through class hierarchy and gets value of first found CLSCompliantAttribute. - /// If no is attribute exists then assembly CLSCompliantAttribute is returned. - /// - 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; - } - } - - /// - /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute - /// - protected bool HasClsCompliantAttribute { - get { - return CLSAttributeValue.HasValue; - } - } - - /// - /// Returns true when a member supports multiple overloads (methods, indexers, etc) - /// - public virtual bool EnableOverloadChecks (MemberCore overload) - { - return false; - } - - /// - /// 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. - /// - 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 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 GetMissingDependencies () - { - return GetMissingDependencies (this); - } - - public List GetMissingDependencies (MemberSpec caller) - { - if ((state & (StateFlags.MissingDependency | StateFlags.MissingDependency_Undetected)) == 0) - return null; - - state &= ~StateFlags.MissingDependency_Undetected; - - var imported = definition as ImportedDefinition; - List 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 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; } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/delegate.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/delegate.cs deleted file mode 100644 index 612d11636..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/delegate.cs +++ /dev/null @@ -1,952 +0,0 @@ -// -// 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 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 (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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/doc.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/doc.cs deleted file mode 100644 index 35fe58529..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/doc.cs +++ /dev/null @@ -1,755 +0,0 @@ -// -// doc.cs: Support for XML documentation comment. -// -// Authors: -// Atsushi Enomoto -// 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 StoredDocuments = new Dictionary (); - - 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 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 (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 elements. - // - void HandleSee (MemberCore mc, XmlElement see) - { - HandleXrefCommon (mc, see); - } - - // - // Handles elements. - // - void HandleSeeAlso (MemberCore mc, XmlElement seealso) - { - HandleXrefCommon (mc, seealso); - } - - // - // Handles elements. - // - void HandleException (MemberCore mc, XmlElement seealso) - { - HandleXrefCommon (mc, seealso); - } - - // - // Handles 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 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 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 (); - } - - 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/driver.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/driver.cs deleted file mode 100644 index 6ef6859e8..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/driver.cs +++ /dev/null @@ -1,475 +0,0 @@ -// -// 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 -{ - /// - /// The compiler driver. - /// - 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 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 (); - } - } - -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dynamic.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dynamic.cs deleted file mode 100644 index 5604a3fcd..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dynamic.cs +++ /dev/null @@ -1,986 +0,0 @@ -// -// 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/ecore.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/ecore.cs deleted file mode 100644 index d1e2c3b84..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/ecore.cs +++ /dev/null @@ -1,7426 +0,0 @@ -// -// 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 { - - /// - /// 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). - /// - public enum ExprClass : byte { - Unresolved = 0, - - Value, - Variable, - Namespace, - Type, - TypeParameter, - MethodGroup, - PropertyAccess, - EventAccess, - IndexerAccess, - Nothing, - } - - /// - /// This is used to tell Resolve in which types of expressions we're - /// interested. - /// - [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 - }; - - /// - /// This interface is implemented by variables - /// - public interface IMemoryLocation { - /// - /// 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. - /// - 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); - } - - /// - /// Base class for expressions - /// - 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; - } - - /// - /// Performs semantic analysis on the Expression - /// - /// - /// - /// 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). - /// - 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; - } - - /// - /// Resolves an expression and performs semantic analysis on it. - /// - /// - /// - /// Currently Resolve wraps DoResolve to perform sanity - /// checking and assertion checking on what we expect from Resolve. - /// - 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 - } - } - - /// - /// Resolves an expression and performs semantic analysis on it. - /// - public Expression Resolve (ResolveContext rc) - { - return Resolve (rc, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup); - } - - /// - /// Resolves an expression for LValue assignment - /// - /// - /// - /// Currently ResolveLValue wraps DoResolveLValue to perform sanity - /// checking and assertion checking on what we expect from Resolve - /// - 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 ()); - } - } - - /// - /// Emits the code for the expression - /// - /// - /// - /// The Emit method is invoked to generate the code - /// for the expression. - /// - 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 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); - } - } - - /// - /// Protected constructor. Only derivate types should - /// be able to be created - /// - - protected Expression () - { - } - - /// - /// Returns a fully formed expression after a MemberLookup - /// - /// - 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 (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 RemoveHiddenTypeParameterMethods (IList 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 (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 (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; - } - - /// - /// Returns an expression that can be used to invoke operator true - /// on the expression if it exists. - /// - protected static Expression GetOperatorTrue (ResolveContext ec, Expression e, Location loc) - { - return GetOperatorTrueOrFalse (ec, e, true, loc); - } - - /// - /// Returns an expression that can be used to invoke operator false - /// on the expression if it exists. - /// - 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"); - } - } - - /// - /// Reports that we were expecting `expr' to be of class `expected' - /// - 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); - } - } - - /// - /// 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. - /// - 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; - } - } - - /// - /// 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). - /// - public abstract void EmitStatement (EmitContext ec); - - public override void EmitSideEffect (EmitContext ec) - { - EmitStatement (ec); - } - } - - /// - /// 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". - /// - /// - 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); - } - } - - /// - /// This class is used to wrap literals which belong inside Enums - /// - 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); - } - } - - /// - /// 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. - /// - 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); - } - } - - /// - /// 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. - /// - 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); - } - } - - /// - /// This kind of cast is used to encapsulate a child and cast it - /// to the class requested - /// - 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); - } - - /// - /// SimpleName expressions are formed of a single word and only happen at the beginning - /// of a dotted-name. - /// - 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); - } - } - - /// - /// Represents a namespace or a type. The name of the class was inspired by - /// section 10.8.1 (Fully Qualified Names). - /// - 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 ()); - } - } - - /// - /// Expression that evaluates to a type - /// - 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 (); - } - } - - /// - /// Fully resolved Expression that already evaluated to a type - /// - 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); - } - } - - /// - /// This class denotes an expression which evaluates to a member - /// of a struct or a class. - /// - 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; - - /// - /// The name of this member. - /// - public abstract string Name { - get; - } - - // - // When base.member is used - // - public bool IsBase { - get { return InstanceExpression is BaseThis; } - } - - /// - /// Whether this is an instance member. - /// - public abstract bool IsInstance { - get; - } - - /// - /// Whether this is a static member. - /// - 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 (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 (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 methods; - readonly int index; - readonly IMemberContext context; - - public ExtensionMethodCandidates (IMemberContext context, IList 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 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().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 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 ().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 - } - - /// - /// MethodGroupExpr represents a group of method candidates which - /// can be resolved to the best method overload - /// - public class MethodGroupExpr : MemberExpr, OverloadResolver.IBaseMembersProvider - { - static readonly MemberSpec[] Excluded = new MemberSpec[0]; - - protected IList Methods; - MethodSpec best_candidate; - TypeSpec best_candidate_return; - protected TypeArguments type_arguments; - - SimpleName simple_name; - protected TypeSpec queried_type; - - public MethodGroupExpr (IList 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 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); - } - - /// - /// 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. - /// - /// - 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 (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 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 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 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 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 members, Restrictions restrictions, Location loc) - : this (members, null, restrictions, loc) - { - } - - public OverloadResolver (IList 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 - // - 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, and Q has a return type Task - // 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; - } - - /// - /// Determines "Better function" between candidate - /// and the current best match - /// - /// - /// Returns a boolean indicating : - /// false if candidate ain't better - /// true if candidate is better than the current best match - /// - 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 with override Foo - // - 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 (ResolveContext rc, ref Arguments args) where T : MemberSpec, IParametersMember - { - List 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 (); - - 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 (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 - { - 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 : 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; - } - } - - /// - /// Fully resolved expression that evaluates to an Event - /// - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/enum.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/enum.cs deleted file mode 100644 index 96385f622..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/enum.cs +++ /dev/null @@ -1,339 +0,0 @@ -// -// 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); - } - - } - - /// - /// Enumeration container - /// - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/eval.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/eval.cs deleted file mode 100644 index aac77eee6..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/eval.cs +++ /dev/null @@ -1,1333 +0,0 @@ -// -// 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 -{ - - /// - /// Experimental! - /// - public delegate void ValueModificationHandler (string variableName, int row, int column, object value); - - /// - /// Evaluator: provides an API to evaluate C# statements and - /// expressions dynamically. - /// - /// - /// 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. - /// - 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> 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> (); - } - - void Init () - { - var loader = new DynamicLoader (importer, ctx); - - RootContext.ToplevelTypes = module; - - //var startup_files = new List (); - //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); - } - - /// - /// When set evaluator will automatically wait on Task of async methods. When not - /// set it's called responsibility to handle Task execution - /// - public bool WaitOnTask { get; set; } - - /// - /// If true, turns type expressions into valid expressions - /// and calls the describe method on it - /// - public bool DescribeTypeExpressions; - - /// - /// Whether the evaluator will use terse syntax, and the semicolons at the end are optional - /// - public bool Terse = true; - - /// - /// The base class for the classes that host the user generated code - /// - /// - /// - /// 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. - /// - public Type InteractiveBaseClass { - get { - return base_class; - } - set { - base_class = value; - - if (value != null && typeof (InteractiveBase).IsAssignableFrom (value)) - InteractiveBase.Evaluator = this; - } - } - - /// - /// Interrupts the evaluation of an expression executing in Evaluate. - /// - /// - /// Use this method to interrupt long-running invocations. - /// - public void Interrupt () - { - if (!inited || !invoking) - return; - - if (invoke_thread != null) - invoke_thread.Abort (); - } - - /// - /// Compiles the input string and returns a delegate that represents the compiled code. - /// - /// - /// - /// 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. - /// - /// - 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; - } - } - - /// - /// Compiles the input string and returns a delegate that represents the compiled code. - /// - /// - /// - /// 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. - /// - /// - 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 - } - - /// - /// Evaluates and expression or statement and returns any result values. - /// - /// - /// 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. - /// - 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 (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; - } - - /// - /// Executes the given expression or statement. - /// - /// - /// Executes the provided statement, returns true - /// on success, false on parsing errors. Exceptions - /// might be thrown by the called code. - /// - public bool Run (string statement) - { - object result; - bool result_set; - - return Evaluate (statement, out result, out result_set) == null; - } - - /// - /// Evaluates and expression or statement and returns the result. - /// - /// - /// 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. - /// - 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; - } - - /// - /// Experimental! - /// - 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 (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 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 - } - - /// - /// 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. - /// - internal static class QuitValue { } - - internal Tuple LookupField (string name) - { - Tuple 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 GetUsingList () - { - var res = new List (); - - 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 (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 = ""; - } - - sb.AppendFormat ("{0} {1} = {2}", fi.Item1.MemberType.GetSignatureForError (), de.Key, value); - sb.AppendLine (); - } - - return sb.ToString (); - } - } - - /// - /// Loads the given assembly and exposes the API to the user. - /// - 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); - } - } - - /// - /// Exposes the API of the given assembly to the Evaluator - /// - public void ReferenceAssembly (Assembly a) - { - lock (evaluator_lock){ - importer.ImportAssembly (a, module.GlobalRootNamespace); - } - } - } - - - /// - /// A delegate that can be used to invoke the - /// compiled expression or statement. - /// - /// - /// 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. - /// - - public delegate void CompiledMethod (ref object retvalue); - - /// - /// The default base class for every interaction line - /// - /// - /// 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 - /// - public class InteractiveBase { - /// - /// Determines where the standard output of methods in this class will go. - /// - public static TextWriter Output = Console.Out; - - /// - /// Determines where the standard error of methods in this class will go. - /// - public static TextWriter Error = Console.Error; - - /// - /// The primary prompt used for interactive use. - /// - public static string Prompt = "csharp> "; - - /// - /// The secondary prompt used for interactive use (used when - /// an expression is incomplete). - /// - public static string ContinuationPrompt = " > "; - - /// - /// Used to signal that the user has invoked the `quit' statement. - /// - public static bool QuitRequested; - - public static Evaluator Evaluator; - - /// - /// Shows all the variables defined so far. - /// - static public void ShowVars () - { - Output.Write (Evaluator.GetVars ()); - Output.Flush (); - } - - /// - /// Displays the using statements in effect at this point. - /// - static public void ShowUsing () - { - Output.Write (Evaluator.GetUsing ()); - Output.Flush (); - } - - /// - /// Times the execution of the given delegate - /// - static public TimeSpan Time (Action a) - { - DateTime start = DateTime.Now; - a (); - return DateTime.Now - start; - } - - /// - /// Loads the assemblies from a package - /// - /// - /// Loads the assemblies from a package. This is equivalent - /// to passing the -pkg: command line flag to the C# compiler - /// on the command line. - /// - 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; - } - } - } - - /// - /// Loads the assembly - /// - /// - /// 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. - /// - 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); - } - - /// - /// Returns a list of available static methods. - /// - 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"; - } - } - - /// - /// Indicates to the read-eval-print-loop that the interaction should be finished. - /// - static public object quit { - get { - QuitRequested = true; - - // To avoid print null at the exit - return typeof (Evaluator.QuitValue); - } - } - - /// - /// Same as quit - useful in script scenerios - /// - static public void Quit () { - QuitRequested = true; - } - -#if !NET_2_1 - /// - /// Describes an object or a type. - /// - /// - /// 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. - /// - static public string Describe (object x) - { - if (x == null) - return ""; - - 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); - } - } - - /// - /// 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. - /// - 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 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 (); - - 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 listeners = new Dictionary (); - - 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/expression.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/expression.cs deleted file mode 100644 index 3a076077d..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/expression.cs +++ /dev/null @@ -1,11921 +0,0 @@ -// -// 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 expr_tree; - - public UserOperatorCall (MethodSpec oper, Arguments args, Func 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; - } - - // - // This routine will attempt to simplify the unary expression when the - // argument is a constant. - // - 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); - } - } - - /// - /// Unary Mutator expressions (pre and post ++ and --) - /// - /// - /// - /// 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) - /// - /// - 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); - } - - } - - /// - /// Implementation of the `is' operator. - /// - 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); - } - } - - /// - /// Implementation of the `as' operator. - /// - 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); - } - } - - /// - /// Binary operators - /// - 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 - - /// - /// Returns a stringified representation of the Operator - /// - 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 left_operators = MemberCache.GetUserOperator (l, op, false); - IList 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 CreateLiftedOperators (ResolveContext rc, IList 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 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 (); - - // - // 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 CombineUserOperators (IList left, IList right) - { - var combined = new List (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 ()); - } - } - } - - /// - /// 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 - /// - 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 (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 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 (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 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); - } - } - - /// - /// Implements the ternary conditional operator (?:) - /// - 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); - } - } - - /// - /// This represents a reference to a parameter in the intermediate - /// representation. - /// - 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); - } - } - - /// - /// Invocation of methods or delegates. - /// - 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 - - /// - /// Converts complex core type syntax like 'new int ()' to simple constant - /// - 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 elements; - BlockVariable variable; - - public ArrayInitializer (List init, Location loc) - { - elements = init; - this.loc = loc; - } - - public ArrayInitializer (int count, Location loc) - : this (new List (count), loc) - { - } - - public ArrayInitializer (Location loc) - : this (4, loc) - { - } - - #region Properties - - public int Count { - get { return elements.Count; } - } - - public List 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 (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); - } - } - - /// - /// 14.5.10.2: Represents an array creation expression. - /// - /// - /// - /// 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. - /// - 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 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 array_data; - - Dictionary 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 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 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 (probe.Count); - bounds = new Dictionary (); - } - - 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 (); - - 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 (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; - } - } - - /// - /// Represents the `this' construct - /// - - 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); - } - } - - /// - /// Represents the `__arglist' construct - /// - 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); - } - } - - /// - /// Represents the `__arglist (....)' construct - /// - 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); - } - } - - /// - /// Implements the typeof operator - /// - 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 - { - 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 GetTypeFromHandle (EmitContext ec) - { - return ec.Module.PredefinedMembers.MethodInfoGetMethodFromHandle; - } - - protected override PredefinedMember GetTypeFromHandleGeneric (EmitContext ec) - { - return ec.Module.PredefinedMembers.MethodInfoGetMethodFromHandle2; - } - } - - abstract class TypeOfMember : 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 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 GetTypeFromHandle (EmitContext ec); - protected abstract PredefinedMember GetTypeFromHandleGeneric (EmitContext ec); - } - - sealed class TypeOfField : TypeOfMember - { - 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 GetTypeFromHandle (EmitContext ec) - { - return ec.Module.PredefinedMembers.FieldInfoGetFieldFromHandle; - } - - protected override PredefinedMember GetTypeFromHandleGeneric (EmitContext ec) - { - return ec.Module.PredefinedMembers.FieldInfoGetFieldFromHandle2; - } - } - - /// - /// Implements the sizeof expression - /// - 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); - } - } - - /// - /// Implements the qualified-alias-member (::) expression. - /// - 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); - } - } - - /// - /// Implements the member access expression - /// - 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; - } - } - - /// - /// Implements checked expressions - /// - 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); - } - } - - /// - /// Implements the unchecked expression - /// - 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); - } - } - - /// - /// An Element Access expression. - /// - /// During semantic analysis these are transformed into - /// IndexerAccess, ArrayAccess or a PointerArithmetic. - /// - 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); - } - } - - /// - /// Implements array access - /// - 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, OverloadResolver.IBaseMembersProvider - { - IList indexers; - Arguments arguments; - TypeSpec queried_type; - - public IndexerExpr (IList indexers, TypeSpec queriedType, ElementAccess ea) - : this (indexers, queriedType, ea.Expr, ea.Arguments, ea.Location) - { - } - - public IndexerExpr (IList 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 (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 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); - } - } - - /// - /// 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). - /// - 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; - } - } - - // - // 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. - // - 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 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 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 initializers; - bool is_collection_initialization; - - public CollectionOrObjectInitializers (Location loc) - : this (new Expression[0], loc) - { - } - - public CollectionOrObjectInitializers (IList 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 Initializers { - get { - return initializers; - } - } - - protected override void CloneTo (CloneContext clonectx, Expression target) - { - CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target; - - t.initializers = new List (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 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 (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 parameters; - readonly TypeContainer parent; - AnonymousTypeClass anonymous_type; - - public NewAnonymousType (List parameters, TypeContainer parent, Location loc) - : base (null, null, loc) - { - this.parameters = parameters; - this.parent = parent; - } - - public List 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 (parameters.Count); - foreach (AnonymousTypeParameter atp in parameters) - t.parameters.Add ((AnonymousTypeParameter) atp.Clone (clonectx)); - } - - AnonymousTypeClass CreateAnonymousType (ResolveContext ec, IList 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/field.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/field.cs deleted file mode 100644 index 265e43620..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/field.cs +++ /dev/null @@ -1,733 +0,0 @@ -// -// 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 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 Declarators { - get { - return this.declarators; - } - } - #endregion - - public void AddDeclarator (FieldDeclarator declarator) - { - if (declarators == null) - declarators = new List (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 ResolveMissingDependencies (MemberSpec caller) - { - return memberType.ResolveMissingDependencies (this); - } - } - - /// - /// Fixed buffer implementation - /// - 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 { - // - // Modifiers allowed in a class declaration - // - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/flowanalysis.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/flowanalysis.cs deleted file mode 100644 index dbb74a751..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/flowanalysis.cs +++ /dev/null @@ -1,685 +0,0 @@ -// -// 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 -{ - // - // 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. - // - public class TypeInfo - { - // - // Total number of bits a variable of this type consumes in the flow vector. - // - public readonly int TotalLength; - - // - // Number of bits the simple fields of a variable of this type consume - // in the flow vector. - // - public readonly int Length; - - // - // This is only used by sub-structs. - // - public readonly int Offset; - - // - // If this is a struct. - // - public readonly bool IsStruct; - - // - // If this is a struct, all fields which are structs theirselves. - // - public TypeInfo[] SubStructInfo; - - readonly StructInfo struct_info; - private static Dictionary type_hash; - - static readonly TypeInfo simple_type = new TypeInfo (1); - - static TypeInfo () - { - Reset (); - } - - public static void Reset () - { - type_hash = new Dictionary (); - StructInfo.field_type_hash = new Dictionary (); - } - - 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; - } - - // - // A struct's constructor must always assign all fields. - // This method checks whether it actually does so. - // - 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 fields; - public readonly TypeInfo[] StructFields; - public readonly int Length; - public readonly int TotalLength; - - public static Dictionary field_type_hash; - private Dictionary struct_field_hash; - private Dictionary 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 (); - field_hash = new Dictionary (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 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; - - // - // The bit offset of this variable in the flow vector. - // - readonly int Offset; - - // - // 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. - // - readonly int Length; - - // - // If this is a parameter of local variable. - // - 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 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/generic.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/generic.cs deleted file mode 100644 index f6d594fd0..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/generic.cs +++ /dev/null @@ -1,3660 +0,0 @@ -// -// 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 constraints; - readonly Location loc; - bool resolved; - bool resolving; - - public IEnumerable ConstraintExpressions { - get { - return constraints; - } - } - - public Constraints (SimpleMemberName tparam, List constraints, Location loc) - { - this.tparam = tparam; - this.constraints = constraints; - this.loc = loc; - } - - #region Properties - - public List 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 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 (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 - // 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 (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 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 (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 { override void Foo () {} } - // class B { virtual void Foo () 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 { void Foo where U : T; } - // class A : I { void Foo 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 (TypeParameterSpec[] tparams, Func 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 (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 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 { - // public static Nested Foo () { return null; } - // - // public class Nested {} - // } - // - // return type of Test.Foo() has to be Test.Nested - // - 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 (), class Foo {} - // - 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 { ITest 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 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 (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 (); - - 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; - } - } - - /// - /// A TypeExpr which already resolved to a type parameter. - /// - 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 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.Bar => Foo.Bar - // - // Any later inflation of Foo.Bar has to also inflate T if used inside Bar - // - List merged_targs = null; - List merged_tparams = null; - - var type = DeclaringType; - - do { - if (type.TypeArguments.Length > 0) { - if (merged_targs == null) { - merged_targs = new List (); - merged_tparams = new List (); - 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.Bar => string, bool, int - // - var all = new List (); - 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 { - // 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 (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 : Base.Nested> { - // class Nested {} - // } - // - // When inflating A. 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 : A {} - // - 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 (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 args; - TypeSpec[] atypes; - - public List Args { - get { return this.args; } - } - - public TypeArguments (params FullNamedExpression[] types) - { - this.args = new List (types); - } - - public void Add (FullNamedExpression type) - { - args.Add (type); - } - - /// - /// We may only be used after Resolve() is called and return the fully - /// resolved types. - /// - // 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 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 (); - } - - /// - /// Resolve the type arguments. - /// - 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 names; - TypeParameterSpec[] types; - - public TypeParameters () - { - names = new List (); - } - - public TypeParameters (int count) - { - names = new List (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; - - /// - /// Instantiate the generic type `t' with the type arguments `args'. - /// Use this constructor if you already know the fully resolved - /// generic type. - /// - 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 - { - 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 Members - - public bool Equals (BoundInfo other) - { - return Type == other.Type && Kind == other.Kind; - } - - #endregion - } - - readonly TypeSpec[] tp_args; - readonly TypeSpec[] fixed_types; - readonly List[] 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 [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 [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 (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 (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 and there is a unique type C - // such that U is identical to, inherits from (directly or indirectly), - // or implements (directly or indirectly) C - // - var u_candidates = new List (); - 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, - // class U : I, I then no type inference is made when inferring - // type I 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 (IList, IList) - // - // 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 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; - } - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/import.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/import.cs deleted file mode 100644 index 6dea50a33..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/import.cs +++ /dev/null @@ -1,2352 +0,0 @@ -// -// 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 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) 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 import_cache; - protected readonly Dictionary compiled_types; - protected readonly Dictionary 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 (1024, ReferenceEquality.Default); - compiled_types = new Dictionary (40, ReferenceEquality.Default); - assembly_2_definition = new Dictionary (ReferenceEquality.Default); - IgnorePrivateMembers = true; - } - - #region Properties - - public ICollection 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 { - // IFoo> foo; // A 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 agains IFoo - // 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 to typespec like - // A.B.C - // - var nested_hierarchy = new List (); - 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 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 tparams = null; - foreach (var ct in constraints) { - if (ct.IsGenericParameter) { - if (tparams == null) - tparams = new List (); - - 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 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 conditionals = null; - - // It should not throw any loading exception - IList 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 (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 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 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 (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 internals_visible_to; - Dictionary 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 (); - } 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 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 (); - - 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 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 possible_accessors = null; - List 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 (ReferenceEquality.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 (); - - 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 (); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/iterators.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/iterators.cs deleted file mode 100644 index 5dce0ed15..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/iterators.cs +++ /dev/null @@ -1,1260 +0,0 @@ -// -// 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 : 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; - 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 - { - 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 init = null; - if (host.hoisted_this != null) { - init = new List (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 (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) null, null, loc) - { - this.method = method; - eclass = ExprClass.Unresolved; - } - - protected override Expression DoResolve (ResolveContext ec) - { - Methods = new List (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 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 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 (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 (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 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 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 (); - - 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; - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/lambda.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/lambda.cs deleted file mode 100644 index 7868c6a2c..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/lambda.cs +++ /dev/null @@ -1,229 +0,0 @@ -// -// 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/linq.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/linq.cs deleted file mode 100644 index 11f01009d..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/linq.cs +++ /dev/null @@ -1,904 +0,0 @@ -// -// 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 (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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/literal.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/literal.cs deleted file mode 100644 index 1af2d0c9e..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/literal.cs +++ /dev/null @@ -1,333 +0,0 @@ -// -// 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/location.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/location.cs deleted file mode 100644 index a27ebf819..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/location.cs +++ /dev/null @@ -1,883 +0,0 @@ -// -// location.cs: Keeps track of the location of source code entity -// -// Author: -// Miguel de Icaza -// Atsushi Enomoto -// 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 - { - // - // Used by #line directive to track hidden sequence point - // regions - // - struct LocationRegion : IComparable - { - 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 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 (); - - hidden_lines.Add (new LocationRegion (start, end)); - } - - public override string ToString () - { - return String.Format ("SourceFile ({0}:{1}:{2})", Name, FullPathName, Index); - } - } - - /// - /// Keeps track of the location in the program - /// - /// - /// - /// 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 - /// - public struct Location : IEquatable - { - 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 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 (); - checkpoint_index = 0; - } - - public static void AddFile (SourceFile file) - { - source_list.Add (file); - } - - // - // 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. - // - static public void Initialize (List 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); - } - - /// - /// Whether the Location is Null - /// - 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 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 Codes = new List (); - - 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 Specials = new List (); - - 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> Modifiers { get; internal set; } - List locations; - - public MemberLocations (IList> mods, IEnumerable locs) - { - Modifiers = mods; - locations = locs != null ? new List (locs) : null; -/* - public readonly IList> Modifiers; - List locations; - - public MemberLocations (IList> mods) - { - Modifiers = mods; - } - - public MemberLocations (IList> mods, Location loc) - : this (mods) - { - AddLocations (loc); - } - - public MemberLocations (IList> mods, Location[] locs) - : this (mods) - { - AddLocations (locs); - } - - public MemberLocations (IList> mods, List 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 (); - } - - locations.Add (loc); - } - - public void AddLocations (params Location[] additional) - - { - - AddLocations ((IEnumerable)additional); - - } - public void AddLocations (IEnumerable additional) - { - if (additional == null) - return; - if (locations == null) { - locations = new List (additional); - } else { - locations.AddRange (additional); - } - } - } - - public MemberCore LastMember { - get; - private set; - } - - Dictionary> simple_locs = new Dictionary> (ReferenceEquality.Default); - Dictionary member_locs = new Dictionary (ReferenceEquality.Default); - - [Conditional ("FULL_AST")] - public void AddLocation (object element, params Location[] locations) - { - AddLocation (element, (IEnumerable)locations); - } - - [Conditional ("FULL_AST")] - public void AddLocation (object element, IEnumerable locations) - { - if (element == null || locations == null) - return; - List found; - if (!simple_locs.TryGetValue (element, out found)) { - simple_locs.Add (element, new List (locations)); - return; - } - found.AddRange(locations); - } - - [Conditional ("FULL_AST")] - public void InsertLocation (object element, int index, Location location) - { - List found; - if (!simple_locs.TryGetValue (element, out found)) { - found = new List (); - 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(locations)); - } - - [Conditional ("FULL_AST")] - public void AddMember (MemberCore member, IList> 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> modLocations, IEnumerable 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)locations); - - } - - [Conditional ("FULL_AST")] - public void AppendToMember (MemberCore existing, IEnumerable 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 GetLocations (object element) - { - if (element == null) - return null; - List found; - simple_locs.TryGetValue (element, out found); - return found; - } - - public MemberLocations GetMemberLocation (MemberCore element) - { - MemberLocations found; - member_locs.TryGetValue (element, out found); - return found; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/membercache.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/membercache.cs deleted file mode 100644 index 3837af2c2..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/membercache.cs +++ /dev/null @@ -1,1501 +0,0 @@ -// -// 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 - { - 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 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> member_hash; - Dictionary locase_members; - IList missing_abstract; - StateFlags state; // TODO: Move to TypeSpec or ITypeDefinition - - public static readonly string IndexerNameAlias = ""; - - public static readonly MemberCache Empty = new MemberCache (0); - - public MemberCache () - : this (16) - { - } - - public MemberCache (int capacity) - { - member_hash = new Dictionary> (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 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 (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 { 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 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 (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 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 { 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 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 { existing[0], member }; - return true; - } - - existing.Add (member); - return false; - } - - public static MemberSpec FindMember (TypeSpec container, MemberFilter filter, BindingRestriction restrictions) - { - do { - IList 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 FindMembers (TypeSpec container, string name, bool declaredOnlyClass) - { - IList 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 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 FindExtensionMethods (IMemberContext invocationContext, string name, int arity) - { - IList entries; - if (!member_hash.TryGetValue (name, out entries)) - return null; - - List 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 (); - 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 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 (TypeSpec container, T spec) where T : MemberSpec - { - IList 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 GetAllFieldsForDefiniteAssignment (TypeSpec container) - { - List 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 (); - - fields.Add (fs); - break; - } - } - - return fields ?? new List (0); - } - - public static IList GetCompletitionMembers (IMemberContext ctx, TypeSpec container, string name) - { - var matches = new List (); - 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 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 (); - 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 GetNotImplementedAbstractMethods (TypeSpec type) - { - if (type.MemberCache.missing_abstract != null) - return type.MemberCache.missing_abstract; - - var abstract_methods = new List (); - List 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 (); - - 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 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 GetUserOperator (TypeSpec container, Operator.OpType op, bool declaredOnly) - { - IList found = null; - bool shared_list = true; - IList 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 (); - found.Add (applicable[i]); - } else { - List prev; - if (shared_list) { - shared_list = false; - prev = new List (found.Count + 1); - prev.AddRange (found); - } else { - prev = (List) found; - } - - prev.Add (applicable[i]); - } - } - } else { - if (found == null) { - found = applicable; - shared_list = true; - } else { - List merged; - if (shared_list) { - shared_list = false; - merged = new List (found.Count + applicable.Count); - merged.AddRange (found); - found = merged; - } else { - merged = (List) 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 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 accessor_relation = null; - List 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 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 {} - // interface I : I {} - // - // class C: I {} - // - 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 (); - - accessor_members.Add (inflated); - continue; - } - - if (member.IsAccessor) { - if (accessor_relation == null) - accessor_relation = new Dictionary (); - 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 (member_hash.Count); // StringComparer.OrdinalIgnoreCase); - } else { - var btype = container.BaseType.GetDefinition (); - btype.MemberCache.VerifyClsCompliance (btype, report); - locase_members = new Dictionary (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 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/method.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/method.cs deleted file mode 100644 index 7c42dbc81..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/method.cs +++ /dev/null @@ -1,2890 +0,0 @@ -// -// 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; -using IKVM.Reflection; -using IKVM.Reflection.Emit; -#else -using MetaType = System.Type; -using SecurityType = System.Collections.Generic.Dictionary; -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 (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 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 (); - - 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 (); - - 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; - } - } - - /// - /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded). - /// - 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 { virtual void Foo () where U : class, T {} } - // class B : A { override void Foo {} } - // - 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"); - } - - 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; - - // - // Modifiers allowed for a constructor. - // - 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 - } - - /// - /// Interface for MethodData class. Holds links to parent members to avoid member duplication. - /// - 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 (); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/modifiers.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/modifiers.cs deleted file mode 100644 index c8c6b73e6..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/modifiers.cs +++ /dev/null @@ -1,282 +0,0 @@ -// -// 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; - } - - // - // Checks the object @mod modifiers to be in @allowed. - // Returns the new mask. Side effect: reports any - // incorrect attributes. - // - 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)); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/module.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/module.cs deleted file mode 100644 index 68f1b8ece..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/module.cs +++ /dev/null @@ -1,713 +0,0 @@ -// -// 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 size_types; - int fields; - - public StaticDataContainer (ModuleContainer module) - : base (module, new MemberName ("" + module.builder.ModuleVersionId.ToString ("B"), Location.Null), - Modifiers.STATIC | Modifiers.INTERNAL) - { - size_types = new Dictionary (); - } - - 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 ("", 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> anonymous_types; - readonly Dictionary array_types; - readonly Dictionary pointer_types; - readonly Dictionary reference_types; - readonly Dictionary attrs_cache; - readonly Dictionary awaiters; - - AssemblyDefinition assembly; - readonly CompilerContext context; - readonly RootNamespace global_ns; - readonly Dictionary 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 (); - anonymous_types = new Dictionary> (); - global_ns = new GlobalRootNamespace (); - alias_ns = new Dictionary (); - array_types = new Dictionary (); - pointer_types = new Dictionary (); - reference_types = new Dictionary (); - attrs_cache = new Dictionary (); - awaiters = new Dictionary (); - } - - #region Properties - - internal Dictionary ArrayTypesCache { - get { - return array_types; - } - } - - // - // Cache for parameter-less attributes - // - internal Dictionary 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 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 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 existing; - if (!anonymous_types.TryGetValue (type.Parameters.Count, out existing)) - if (existing == null) { - existing = new List (); - 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 parameters) - { - List 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 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 ""; - } - - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/namespace.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/namespace.cs deleted file mode 100644 index f4c5aba5b..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/namespace.cs +++ /dev/null @@ -1,1584 +0,0 @@ -// -// 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 all_namespaces; - - public RootNamespace (string alias_name) - : base () - { - this.alias_name = alias_name; - RegisterNamespace (this); - - all_namespaces = new Dictionary (); - 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 FindTypeNamespaces (IMemberContext ctx, string name, int arity) - { - List 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 (); - - res.Add (ns.Key); - } - } - - return res; - } - - // - // For better error reporting where compiler tries to guess missing using directive - // - public List FindExtensionMethodNamespaces (IMemberContext ctx, string name, int arity) - { - List 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 (); - - 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 namespaces; - protected Dictionary> types; - List extension_method_types; - Dictionary cached_types; - bool cls_checked; - - /// - /// Constructor Takes the current namespace and the - /// name. This is bootstrapped with parent == null - /// and name = "" - /// - 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 (); - cached_types = new Dictionary (); - } - - #region Properties - - /// - /// The qualified name of the current namespace - /// - public string Name { - get { return fullname; } - } - - /// - /// The parent of this namespace, used by the parser to "Pop" - /// the current namespace declaration - /// - 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 GetAllTypes (string name) - { - IList 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 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 CompletionGetTypesStartingWith (string prefix) - { - if (types == null) - return Enumerable.Empty (); - - 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 LookupExtensionMethod (IMemberContext invocationContext, string name, int arity) - { - if (extension_method_types == null) - return null; - - List 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> (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 (); - - extension_method_types.Add (ts); - } - } - - var name = ts.Name; - IList 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 (); - 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> (StringComparer.OrdinalIgnoreCase); - foreach (var tgroup in types.Values) { - foreach (var tm in tgroup) { - if ((tm.Modifiers & Modifiers.PUBLIC) == 0 || !tm.IsCLSCompliant ()) - continue; - - List found; - if (!locase_types.TryGetValue (tm.Name, out found)) { - found = new List (); - 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 include_files; - Dictionary 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 Conditionals { - get { - return conditionals ?? new Dictionary (); - } - } - - 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 (); - - if (!include_files.ContainsKey (file.FullPathName)) - include_files.Add (file.FullPathName, file); - } - - public void AddDefine (string value) - { - if (conditionals == null) - conditionals = new Dictionary (2); - - conditionals[value] = true; - } - - public void AddUndefine (string value) - { - if (conditionals == null) - conditionals = new Dictionary (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 clauses; - - // Used by parsed to check for parser errors - public bool DeclarationFound; - - Namespace[] namespace_using_table; - TypeSpec[] types_using_table; - Dictionary 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 (); - } - - protected NamespaceContainer (ModuleContainer parent) - : base (parent, null, null, MemberKind.Namespace) - { - ns = parent.GlobalRootNamespace; - containers = new List (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 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 (); - - 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 (); - } 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 { - // 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 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 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 all = Enumerable.Empty (); - - 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 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 (); - - 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 namespaces = null; - List 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 (); - - // - // 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 (); - - if (types.Contains (type)) { - Warning_DuplicateEntry (entry); - } else { - types.Add (type); - } - } else { - if (namespaces == null) - namespaces = new List (); - - 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/nullable.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/nullable.cs deleted file mode 100644 index e857e3654..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/nullable.cs +++ /dev/null @@ -1,1380 +0,0 @@ -// -// 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); - } - } -} - diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/outline.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/outline.cs deleted file mode 100644 index 1104b1c11..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/outline.cs +++ /dev/null @@ -1,1038 +0,0 @@ -// -// 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; - } -} -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/parameter.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/parameter.cs deleted file mode 100644 index 1a30ae384..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/parameter.cs +++ /dev/null @@ -1,1472 +0,0 @@ -// -// 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 { - - /// - /// Abstract Base class for parameters of a method. - /// - 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; - } - } - - /// - /// Class for applying custom attributes on the return type - /// - 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; - } - } - - /// - /// Is never called - /// - 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; - } - - // - // Resolve is used in method definitions - // - 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.E and e.g. parameter - // type of G.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; - } - } - - /// - /// Represents the methods parameters - /// - 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); - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/pending.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/pending.cs deleted file mode 100644 index 0f863a7bc..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/pending.cs +++ /dev/null @@ -1,734 +0,0 @@ -// -// 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 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 - { - /// - /// The container for this PendingImplementation - /// - readonly TypeDefinition container; - - /// - /// This is the array of TypeAndMethods that describes the pending implementations - /// (both interfaces and abstract methods in base class) - /// - 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 - } - - /// - /// Whether the specified method is an interface method implementation - /// - 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); - } - - /// - /// 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. - /// - /// - 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; - } - - /// - /// 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. - /// - 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 ()); - } - - /// - /// 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 - /// - 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; - } - - /// - /// Verifies that any pending abstract methods or interface methods - /// were implemented. - /// - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/property.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/property.cs deleted file mode 100644 index 979a8e83f..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/property.cs +++ /dev/null @@ -1,1807 +0,0 @@ -// -// 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 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; - } - } - } - - /// - /// For case when event is declared like property (with add and remove accessors). - /// - 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; - } - } - } - - /// - /// Event is declared like field. - /// - 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 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 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 (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 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 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 (); - - missing.AddRange (m); - } - - return missing; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/reflection.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/reflection.cs deleted file mode 100644 index b233b9439..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/reflection.cs +++ /dev/null @@ -1,550 +0,0 @@ -// -// 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 - { - 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 (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> 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); - } - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/report.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/report.cs deleted file mode 100644 index e9b16d1c0..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/report.cs +++ /dev/null @@ -1,1144 +0,0 @@ -// -// 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 warning_regions_table; - - ReportPrinter printer; - - int reporting_disabled; - - readonly CompilerSettings settings; - - /// - /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported. - /// - List extra_information = new List (); - - // - // 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 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); - } - - /// - /// 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. - /// - 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 (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 (); - } 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 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 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 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 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 (); - - 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 session_messages; - // - // A collection of exactly same messages reported in all sessions - // - List common_messages; - - // - // A collection of unique messages reported in all sessions - // - List 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 (); - - 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 (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 timer_names = new Dictionary { - { 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) - { - } - } - - /// - /// Handles #pragma warning - /// - 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 regions = new List (); - - 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; - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/settings.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/settings.cs deleted file mode 100644 index 9ba66c161..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/settings.cs +++ /dev/null @@ -1,1601 +0,0 @@ -// -// 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 AssemblyReferences; - - // - // External aliases for assemblies - // - public List> AssemblyReferencesAliases; - - // - // Modules to be embedded - // - public List Modules; - - // - // Lookup paths for referenced assemblies - // - public List 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 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 conditional_symbols; - - readonly List source_files; - - List warnings_as_error; - List warnings_only; - HashSet 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 (); - AssemblyReferencesAliases = new List> (); - Modules = new List (); - ReferencesLookupPaths = new List (); - - conditional_symbols = new List (); - // - // Add default mcs define - // - conditional_symbols.Add ("__MonoCS__"); - - source_files = new List (); - } - - #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 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 (); - - warnings_as_error.Add (id); - } - - public void AddWarningOnly (int id) - { - if (warnings_only == null) - warnings_only = new List (); - - 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 (); - - 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 source_file_index; - - public event Func 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 response_file_list = null; - bool parsing_options = true; - stop_argument = false; - source_file_index = new Dictionary (); - - 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 (); - - 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 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 (); - 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 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 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 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; } - } - } -} diff --git a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/statement.cs b/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/statement.cs deleted file mode 100644 index 18249431b..000000000 --- a/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/statement.cs +++ /dev/null @@ -1,8074 +0,0 @@ -// -// 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; - } - } - - /// - /// Resolves the statement, true means that all sub-statements - /// did resolve ok. - /// - public virtual bool Resolve (BlockContext bc) - { - return true; - } - - /// - /// Return value indicates whether all code paths emitted return. - /// - 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 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 (); - - 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 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 (); - - 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 statements; - - public StatementList (Statement first, Statement second) - { - statements = new List { first, second }; - } - - #region Properties - public IList 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 (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; - } - } - - /// - /// Implements the return statement - /// - 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'"); - } 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' return type", - ec.GetSignatureForError ()); - } - return false; - } - - // - // The return type is actually Task 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 (); - } 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); - } - } - - - /// - /// `goto default' statement - /// - 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); - } - } - - /// - /// `goto case' statement - /// - 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 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 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 (); - - 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); - } - } - - /// - /// Block represents a C# block. - /// - /// - /// - /// 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. - /// - 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 statements; - - protected List 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 (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 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 (); - - // - // 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 (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 (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 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 (); - - foreach (var entry in pb.labels) { - var list = entry.Value as List; - - if (list != null) { - var list_clone = new List (); - 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 list = (List) 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 names; - - List 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 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 (); - - object value; - if (!names.TryGetValue (name, out value)) { - names.Add (name, li); - return; - } - - INamedBlockVariable existing = value as INamedBlockVariable; - List existing_list; - if (existing != null) { - existing_list = new List (); - existing_list.Add (existing); - names[name] = existing_list; - } else { - existing_list = (List) 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 (); - - object value; - if (!labels.TryGetValue (name, out value)) { - labels.Add (name, label); - return; - } - - LabeledStatement existing = value as LabeledStatement; - List existing_list; - if (existing != null) { - existing_list = new List (); - existing_list.Add (existing); - labels[name] = existing_list; - } else { - existing_list = (List) 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 (); - - 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 list = (List) 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) n.Value) - if (v.Block.ParametersBlock == pb) - AddLocalName (n.Key, v, false); - } - } - } - - // - // 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. - // - 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 - { - public readonly long min; - public long max; - public readonly List label_values; - - public LabelsRange (long value) - { - min = max = value; - label_values = new List (); - label_values.Add (value); - } - - public LabelsRange (long min, long max, ICollection values) - { - this.min = min; - this.max = max; - this.label_values = new List (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 labels; - Dictionary string_labels; - List case_labels; - - List> goto_cases; - List end_reachable_das; - - /// - /// The governing switch type - /// - 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 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 ranges; - if (string_labels != null) { - // We have done all hard work for string already - // setup single range only - ranges = new List (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 (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 (); - } else { - labels = new Dictionary (); - } - - case_labels = new List (); - - 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> (); - - 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 (); - int counter = -1; - labels = new Dictionary (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 (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 (); - - 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 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 (); - 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 try_exit_dat; - List