diff options
author | Mikayla Hutchinson <m.j.hutchinson@gmail.com> | 2017-03-18 01:36:33 +0300 |
---|---|---|
committer | Mikayla Hutchinson <m.j.hutchinson@gmail.com> | 2017-03-18 01:36:33 +0300 |
commit | f84a4368b156875300e7a3206e73a28e2436033c (patch) | |
tree | 2355731ce6ad49f58a7ebc7f287d5a34518e526d /main/src/addins/TextTemplating | |
parent | 191a296fa05886f8286a9123a14913b6a53a99c6 (diff) | |
parent | e316531c1336cd290aa32b0cf06146535fff68ea (diff) |
Merge remote-tracking branch 'origin/master' into roslyn-ivt
Diffstat (limited to 'main/src/addins/TextTemplating')
41 files changed, 13 insertions, 7039 deletions
diff --git a/main/src/addins/TextTemplating/Makefile.am b/main/src/addins/TextTemplating/Makefile.am index 8bf41893d4..0a3a6e73dd 100644 --- a/main/src/addins/TextTemplating/Makefile.am +++ b/main/src/addins/TextTemplating/Makefile.am @@ -1,5 +1,2 @@ SUBDIRS = \ - Mono.TextTemplating \ - TextTransform \ - MonoDevelop.TextTemplating \ - Mono.TextTemplating.Tests + MonoDevelop.TextTemplating diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/DummyHost.cs b/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/DummyHost.cs deleted file mode 100644 index 027a2ddc7a..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/DummyHost.cs +++ /dev/null @@ -1,113 +0,0 @@ -// -// IncludeFileProviderHost.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.CodeDom.Compiler; -using Microsoft.VisualStudio.TextTemplating; - -namespace Mono.TextTemplating.Tests -{ - - public class DummyHost : ITextTemplatingEngineHost - { - public readonly Dictionary<string, string> Locations = new Dictionary<string, string> (); - public readonly Dictionary<string, string> Contents = new Dictionary<string, string> (); - public readonly Dictionary<string, object> HostOptions = new Dictionary<string, object> (); - List<string> standardAssemblyReferences = new List<string> (); - List<string> standardImports = new List<string> (); - public readonly CompilerErrorCollection Errors = new CompilerErrorCollection (); - public readonly Dictionary<string, Type> DirectiveProcessors = new Dictionary<string, Type> (); - - public virtual object GetHostOption (string optionName) - { - object o; - HostOptions.TryGetValue (optionName, out o); - return o; - } - - public virtual bool LoadIncludeText (string requestFileName, out string content, out string location) - { - content = null; - return Locations.TryGetValue (requestFileName, out location) - && Contents.TryGetValue (requestFileName, out content); - } - - public virtual void LogErrors (CompilerErrorCollection errors) - { - Errors.AddRange (errors); - } - - public virtual AppDomain ProvideTemplatingAppDomain (string content) - { - return null; - } - - public virtual string ResolveAssemblyReference (string assemblyReference) - { - throw new System.NotImplementedException(); - } - - public virtual Type ResolveDirectiveProcessor (string processorName) - { - Type t; - DirectiveProcessors.TryGetValue (processorName, out t); - return t; - } - - public virtual string ResolveParameterValue (string directiveId, string processorName, string parameterName) - { - throw new System.NotImplementedException(); - } - - public virtual string ResolvePath (string path) - { - throw new System.NotImplementedException(); - } - - public virtual void SetFileExtension (string extension) - { - throw new System.NotImplementedException(); - } - - public virtual void SetOutputEncoding (System.Text.Encoding encoding, bool fromOutputDirective) - { - throw new System.NotImplementedException(); - } - - public virtual IList<string> StandardAssemblyReferences { - get { return standardAssemblyReferences; } - } - - public virtual IList<string> StandardImports { - get { return standardImports; } - } - - public virtual string TemplateFile { - get; set; - } - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/EngineTests.cs b/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/EngineTests.cs deleted file mode 100644 index e81aee6164..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/EngineTests.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// EngineTests.cs -// -// Author: -// Mikayla Hutchinson <m.j.hutchinson@gmail.com> -// -// Copyright (c) 2016 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 NUnit.Framework; - -namespace Mono.TextTemplating.Tests -{ - [TestFixture] - public class EngineTests - { - #pragma warning disable 414 - static object [] ParameterParsingCases = { - new object [] { "foo=bar", true, "", "", "foo", "bar" }, - new object [] { "a=b", true, "", "", "a", "b" }, - new object [] { "a=b=c", true, "", "", "a", "b=c" }, - new object [] { "!!c!d", true, "", "", "c", "d" }, - new object [] { "!!!", false, "", "", "", "" }, - new object [] { "a=", true, "", "", "a", "" }, - new object [] { "=", false, "", "", "", "" }, - new object [] { "", false, "", "", "", "" }, - new object [] { "!", false, "", "", "", "" }, - new object [] { "a!", true, "", "", "a", "" }, - new object [] { "!b!c!d", true, "", "b", "c", "d" }, - new object [] { "a!b!c!d", true, "a", "b", "c", "d" }, - new object [] { "a=b!c!d!e", true, "", "", "a", "b!c!d!e" }, - new object [] { "a!b!c!d!e", true, "a", "b", "c", "d!e" }, - new object [] { "foo!bar!baz!wibb!le", true, "foo", "bar", "baz", "wibb!le" }, - }; - #pragma warning restore 414 - - [Test] - [TestCaseSource(nameof (ParameterParsingCases))] - public void ParameterParsing ( - string parameter, bool valid, - string expectedProcessor, string expectedDirective, - string expectedName, string expectedValue) - { - string processor, directive, name, value; - var success = TemplateGenerator.TryParseParameter (parameter, out processor, out directive, out name, out value); - - Assert.AreEqual (valid, success); - Assert.AreEqual (expectedProcessor, processor); - Assert.AreEqual (expectedDirective, directive); - Assert.AreEqual (expectedName, name); - Assert.AreEqual (expectedValue, value); - } - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/GenerateIndentedClassCodeTests.cs b/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/GenerateIndentedClassCodeTests.cs deleted file mode 100644 index 0810e2e783..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/GenerateIndentedClassCodeTests.cs +++ /dev/null @@ -1,108 +0,0 @@ -// -// GenerateIndentedClassCodeTests.cs -// -// Author: -// Matt Ward <matt.ward@xamarin.com> -// -// Copyright (c) 2015 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.CodeDom; -using System.CodeDom.Compiler; -using NUnit.Framework; -using System.IO; - -namespace Mono.TextTemplating.Tests -{ - [TestFixture] - public class GenerateIndentedClassCodeTests - { - [Test] - public void FieldAndPropertyGenerated () - { - var provider = CodeDomProvider.CreateProvider ("C#"); - var field = CreateBoolField (); - var property = CreateBoolProperty (); - - string output = TemplatingEngine.GenerateIndentedClassCode (provider, field, property); - output = FixOutput (output); - string expectedOutput = FixOutput (MethodAndFieldGeneratedOutput); - - Assert.AreEqual (expectedOutput, output); - } - - static CodeTypeMember CreateVoidMethod () - { - var meth = new CodeMemberMethod { Name = "MyMethod" }; - meth.ReturnType = new CodeTypeReference (typeof(void)); - return meth; - } - - static CodeTypeMember CreateBoolField () - { - var type = new CodeTypeReference (typeof(bool)); - return new CodeMemberField { Name = "myField", Type = type }; - } - - static CodeTypeMember CreateBoolProperty () - { - var type = new CodeTypeReference (typeof(bool)); - var prop = new CodeMemberProperty { Name = "MyProperty", Type = type }; - prop.GetStatements.Add ( - new CodeMethodReturnStatement ( - new CodePrimitiveExpression (true) - ) - ); - return prop; - } - - /// <summary> - /// Remove empty lines which are not generated on Mono. - /// </summary> - static string FixOutput (string output, string newLine = "\n") - { - using (var writer = new StringWriter ()) { - using (var reader = new StringReader (output)) { - - string line; - while ((line = reader.ReadLine ()) != null) { - if (!String.IsNullOrWhiteSpace (line)) { - writer.Write (line); - writer.Write (newLine); - } - } - } - return writer.ToString (); - } - } - - public static string MethodAndFieldGeneratedOutput = -@" - private bool myField; - - private bool MyProperty { - get { - return true; - } - } -"; - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/GenerationTests.cs b/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/GenerationTests.cs deleted file mode 100644 index 4455c393a1..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/GenerationTests.cs +++ /dev/null @@ -1,205 +0,0 @@ -// -// GenerationTests.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.IO; -using NUnit.Framework; -using Microsoft.VisualStudio.TextTemplating; - -namespace Mono.TextTemplating.Tests -{ - - - [TestFixture] - public class GenerationTests - { - [Test] - public void TemplateGeneratorTest () - { - var gen = new TemplateGenerator (); - string tmp = null; - gen.ProcessTemplate (null, "<#@ template language=\"C#\" #>", ref tmp, out tmp); - Assert.AreEqual (0, gen.Errors.Count, "ProcessTemplate"); - } - - [Test] - public void ImportReferencesTest () - { - var gen = new TemplateGenerator (); - string tmp = null; - gen.ReferencePaths.Add (Path.GetDirectoryName (typeof (Uri).Assembly.Location)); - gen.ReferencePaths.Add (Path.GetDirectoryName (typeof (System.Linq.Enumerable).Assembly.Location)); - gen.ProcessTemplate (null, "<#@ assembly name=\"System.dll\" #>\n<#@ assembly name=\"System.Core.dll\" #>", ref tmp, out tmp); - Assert.AreEqual (0, gen.Errors.Count, "ImportReferencesTest"); - } - - [Test] - public void Generate () - { - string Input = ParsingTests.ParseSample1; - string Output = OutputSample1; - Generate (Input, Output, "\n"); - } - - [Test] - public void GenerateMacNewlines () - { - string MacInput = ParsingTests.ParseSample1.Replace ("\n", "\r"); - string MacOutput = OutputSample1.Replace ("\\n", "\\r").Replace ("\n", "\r");; - Generate (MacInput, MacOutput, "\r"); - } - - [Test] - public void GenerateWindowsNewlines () - { - string WinInput = ParsingTests.ParseSample1.Replace ("\n", "\r\n"); - string WinOutput = OutputSample1.Replace ("\\n", "\\r\\n").Replace ("\n", "\r\n"); - Generate (WinInput, WinOutput, "\r\n"); - } - - [Test] - public void DefaultLanguage () - { - DummyHost host = new DummyHost (); - string template = @"<#= DateTime.Now #>"; - ParsedTemplate pt = ParsedTemplate.FromText (template, host); - Assert.AreEqual (0, host.Errors.Count); - TemplateSettings settings = TemplatingEngine.GetSettings (host, pt); - Assert.AreEqual (settings.Language, "C#"); - } - - //NOTE: we set the newline property on the code generator so that the whole files has matching newlines, - // in order to match the newlines in the verbatim code blocks - void Generate (string input, string expectedOutput, string newline) - { - DummyHost host = new DummyHost (); - string className = "GeneratedTextTransformation4f504ca0"; - string code = GenerateCode (host, input, className, newline); - Assert.AreEqual (0, host.Errors.Count); - - var generated = TemplatingEngineHelper.CleanCodeDom (code, newline); - expectedOutput = TemplatingEngineHelper.CleanCodeDom (expectedOutput, newline); - Assert.AreEqual (expectedOutput, generated); - } - - #region Helpers - - string GenerateCode (ITextTemplatingEngineHost host, string content, string name, string generatorNewline) - { - ParsedTemplate pt = ParsedTemplate.FromText (content, host); - if (pt.Errors.HasErrors) { - host.LogErrors (pt.Errors); - return null; - } - - TemplateSettings settings = TemplatingEngine.GetSettings (host, pt); - if (name != null) - settings.Name = name; - if (pt.Errors.HasErrors) { - host.LogErrors (pt.Errors); - return null; - } - - var ccu = TemplatingEngine.GenerateCompileUnit (host, content, pt, settings); - if (pt.Errors.HasErrors) { - host.LogErrors (pt.Errors); - return null; - } - - var opts = new System.CodeDom.Compiler.CodeGeneratorOptions (); - using (var writer = new System.IO.StringWriter ()) { - writer.NewLine = generatorNewline; - settings.Provider.GenerateCodeFromCompileUnit (ccu, writer, opts); - return writer.ToString (); - } - } - - #endregion - - #region Expected output strings - - public static string OutputSample1 = -@" -namespace Microsoft.VisualStudio.TextTemplating { - - - public partial class GeneratedTextTransformation4f504ca0 : global::Microsoft.VisualStudio.TextTemplating.TextTransformation { - - - #line 9 """" - -baz \#> - - #line default - #line hidden - - public override string TransformText() { - this.GenerationEnvironment = null; - - #line 2 """" - this.Write(""Line One\nLine Two\n""); - - #line default - #line hidden - - #line 4 """" - -foo - - - #line default - #line hidden - - #line 7 """" - this.Write(""Line Three ""); - - #line default - #line hidden - - #line 7 """" - this.Write(global::Microsoft.VisualStudio.TextTemplating.ToStringHelper.ToStringWithCulture( bar )); - - #line default - #line hidden - - #line 7 """" - this.Write(""\nLine Four\n""); - - #line default - #line hidden - return this.GenerationEnvironment.ToString(); - } - - public override void Initialize() { - base.Initialize(); - } - } -} -"; - #endregion - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/Makefile.am b/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/Makefile.am deleted file mode 100644 index c9cc87438f..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/Makefile.am +++ /dev/null @@ -1 +0,0 @@ -include $(top_srcdir)/xbuild.include diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/Mono.TextTemplating.Tests.csproj b/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/Mono.TextTemplating.Tests.csproj deleted file mode 100644 index e8fd9751f4..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/Mono.TextTemplating.Tests.csproj +++ /dev/null @@ -1,61 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0"> - <Import Project="..\..\..\..\MonoDevelop.props" /> - <PropertyGroup> - <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> - <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> - <ProductVersion>8.0.30703</ProductVersion> - <SchemaVersion>2.0</SchemaVersion> - <ProjectGuid>{CB590106-8331-4CBE-8131-B154E7BF79E1}</ProjectGuid> - <OutputType>Library</OutputType> - <AssemblyName>Mono.TextTemplating.Tests</AssemblyName> - <RootNamespace>Mono.TextTemplating.Tests</RootNamespace> - <TestRunnerCommand>..\..\..\..\build\bin\mdtool.exe</TestRunnerCommand> - <TestRunnerArgs>run-md-tests</TestRunnerArgs> - <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <DebugSymbols>True</DebugSymbols> - <DebugType>full</DebugType> - <Optimize>False</Optimize> - <OutputPath>..\..\..\..\build\tests</OutputPath> - <DefineConstants>DEBUG</DefineConstants> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - <NoWarn>1591;1573</NoWarn> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - <DebugType>pdbonly</DebugType> - <Optimize>true</Optimize> - <OutputPath>..\..\..\..\build\tests</OutputPath> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - <DebugSymbols>true</DebugSymbols> - <NoWarn>1591;1573</NoWarn> - </PropertyGroup> - <ItemGroup> - <Reference Include="System" /> - </ItemGroup> - <ItemGroup> - <Compile Include="ParsingTests.cs" /> - <Compile Include="DummyHost.cs" /> - <Compile Include="GenerationTests.cs" /> - <Compile Include="TemplatingEngineHelper.cs" /> - <Compile Include="TemplateEnginePreprocessTemplateTests.cs" /> - <Compile Include="GenerateIndentedClassCodeTests.cs" /> - <Compile Include="TextTemplatingSessionTests.cs" /> - <Compile Include="EngineTests.cs" /> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\Mono.TextTemplating\Mono.TextTemplating.csproj"> - <Project>{A2364D6A-00EF-417C-80A6-815726C70032}</Project> - <Name>Mono.TextTemplating</Name> - <Private>False</Private> - </ProjectReference> - <ProjectReference Include="..\..\..\..\external\guiunit\src\framework\GuiUnit_NET_4_5.csproj"> - <Project>{D12F0F7B-8DE3-43EC-BA49-41052D065A9B}</Project> - <Name>GuiUnit_NET_4_5</Name> - </ProjectReference> - </ItemGroup> - <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> -</Project> diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/ParsingTests.cs b/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/ParsingTests.cs deleted file mode 100644 index 5e2475091d..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/ParsingTests.cs +++ /dev/null @@ -1,191 +0,0 @@ -// -// Test.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using NUnit.Framework; - -namespace Mono.TextTemplating.Tests -{ - - - [TestFixture] - public class ParsingTests - { - public static string ParseSample1 = -@"<#@ template language=""C#v3.5"" #> -Line One -Line Two -<# -foo -#> -Line Three <#= bar #> -Line Four -<#+ -baz \#> -#> -"; - - [Test] - public void TokenTest () - { - string tf = "test.input"; - Tokeniser tk = new Tokeniser (tf, ParseSample1); - - //line 1 - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (new Location (tf, 1, 1), tk.Location); - Assert.AreEqual (State.Content, tk.State); - Assert.AreEqual ("", tk.Value); - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (State.Directive, tk.State); - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (new Location (tf, 1, 5), tk.Location); - Assert.AreEqual (State.DirectiveName, tk.State); - Assert.AreEqual ("template", tk.Value); - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (State.Directive, tk.State); - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (new Location (tf, 1, 14), tk.Location); - Assert.AreEqual (State.DirectiveName, tk.State); - Assert.AreEqual ("language", tk.Value); - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (State.Directive, tk.State); - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (State.DirectiveValue, tk.State); - Assert.AreEqual (new Location (tf, 1, 23), tk.Location); - Assert.AreEqual ("C#v3.5", tk.Value); - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (State.Directive, tk.State); - - //line 2, 3 - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (new Location (tf, 2, 1), tk.Location); - Assert.AreEqual (State.Content, tk.State); - Assert.AreEqual ("Line One\nLine Two\n", tk.Value); - - //line 4, 5, 6 - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (new Location (tf, 4, 1), tk.TagStartLocation); - Assert.AreEqual (new Location (tf, 4, 3), tk.Location); - Assert.AreEqual (new Location (tf, 6, 3), tk.TagEndLocation); - Assert.AreEqual (State.Block, tk.State); - Assert.AreEqual ("\nfoo\n", tk.Value); - - //line 7 - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (new Location (tf, 7, 1), tk.Location); - Assert.AreEqual (State.Content, tk.State); - Assert.AreEqual ("Line Three ", tk.Value); - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (new Location (tf, 7, 12), tk.TagStartLocation); - Assert.AreEqual (new Location (tf, 7, 15), tk.Location); - Assert.AreEqual (new Location (tf, 7, 22), tk.TagEndLocation); - Assert.AreEqual (State.Expression, tk.State); - Assert.AreEqual (" bar ", tk.Value); - - //line 8 - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (new Location (tf, 7, 22), tk.Location); - Assert.AreEqual (State.Content, tk.State); - Assert.AreEqual ("\nLine Four\n", tk.Value); - - //line 9, 10, 11 - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (new Location (tf, 9, 1), tk.TagStartLocation); - Assert.AreEqual (new Location (tf, 9, 4), tk.Location); - Assert.AreEqual (new Location (tf, 11, 3), tk.TagEndLocation); - Assert.AreEqual (State.Helper, tk.State); - Assert.AreEqual (" \nbaz \\#>\n", tk.Value); - - //line 12 - Assert.IsTrue (tk.Advance ()); - Assert.AreEqual (new Location (tf, 12, 1), tk.Location); - Assert.AreEqual (State.Content, tk.State); - Assert.AreEqual ("", tk.Value); - - //EOF - Assert.IsFalse (tk.Advance ()); - Assert.AreEqual (new Location (tf, 12, 1), tk.Location); - Assert.AreEqual (State.EOF, tk.State); - } - - [Test] - public void ParseTest () - { - string tf = "test.input"; - - ParsedTemplate pt = new ParsedTemplate ("test.input"); - Tokeniser tk = new Tokeniser (tf, ParseSample1); - DummyHost host = new DummyHost (); - pt.Parse (host, tk); - - Assert.AreEqual (0, pt.Errors.Count); - var content = new List<TemplateSegment> (pt.Content); - var dirs = new List<Directive> (pt.Directives); - - Assert.AreEqual (1, dirs.Count); - Assert.AreEqual (6, content.Count); - - Assert.AreEqual ("template", dirs[0].Name); - Assert.AreEqual (1, dirs[0].Attributes.Count); - Assert.AreEqual ("C#v3.5", dirs[0].Attributes["language"]); - Assert.AreEqual (new Location (tf, 1, 1), dirs[0].TagStartLocation); - Assert.AreEqual (new Location (tf, 1, 34), dirs[0].EndLocation); - - Assert.AreEqual ("Line One\nLine Two\n", content[0].Text); - Assert.AreEqual ("\nfoo\n", content[1].Text); - Assert.AreEqual ("Line Three ", content[2].Text); - Assert.AreEqual (" bar ", content[3].Text); - Assert.AreEqual ("\nLine Four\n", content[4].Text); - Assert.AreEqual (" \nbaz \\#>\n", content[5].Text); - - Assert.AreEqual (SegmentType.Content, content[0].Type); - Assert.AreEqual (SegmentType.Block, content[1].Type); - Assert.AreEqual (SegmentType.Content, content[2].Type); - Assert.AreEqual (SegmentType.Expression, content[3].Type); - Assert.AreEqual (SegmentType.Content, content[4].Type); - Assert.AreEqual (SegmentType.Helper, content[5].Type); - - Assert.AreEqual (new Location (tf, 4, 1), content[1].TagStartLocation); - Assert.AreEqual (new Location (tf, 7, 12), content[3].TagStartLocation); - Assert.AreEqual (new Location (tf, 9, 1), content[5].TagStartLocation); - - Assert.AreEqual (new Location (tf, 2, 1), content[0].StartLocation); - Assert.AreEqual (new Location (tf, 4, 3), content[1].StartLocation); - Assert.AreEqual (new Location (tf, 7, 1), content[2].StartLocation); - Assert.AreEqual (new Location (tf, 7, 15), content[3].StartLocation); - Assert.AreEqual (new Location (tf, 7, 22), content[4].StartLocation); - Assert.AreEqual (new Location (tf, 9, 4), content[5].StartLocation); - - Assert.AreEqual (new Location (tf, 6, 3), content[1].EndLocation); - Assert.AreEqual (new Location (tf, 7, 22), content[3].EndLocation); - Assert.AreEqual (new Location (tf, 11, 3), content[5].EndLocation); - } - - - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/TemplateEnginePreprocessTemplateTests.cs b/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/TemplateEnginePreprocessTemplateTests.cs deleted file mode 100644 index 3e71f4bbca..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/TemplateEnginePreprocessTemplateTests.cs +++ /dev/null @@ -1,636 +0,0 @@ -// -// TemplateEnginePreprocessTemplateTests.cs -// -// Author: -// Matt Ward -// -// Copyright (c) 2011 Matt Ward -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 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.Compiler; -using System.Collections.Generic; -using System.IO; -using NUnit.Framework; -using Microsoft.VisualStudio.TextTemplating; - -namespace Mono.TextTemplating.Tests -{ - [TestFixture] - public class TemplateEnginePreprocessTemplateTests - { - [Test] - public void Preprocess () - { - string input = - "<#@ template language=\"C#\" #>\r\n" + - "Test\r\n"; - - string expectedOutput = TemplatingEngineHelper.CleanCodeDom (OutputSample1, "\n"); - string output = Preprocess (input); - - Assert.AreEqual (expectedOutput, output); - } - - [Test] - public void Preprocess_ControlBlockAfterIncludedTemplateWithClassFeatureBlock_ReturnsValidCSharpOutput () - { - string input = InputTemplate_ControlBlockAfterIncludedTemplateWithClassFeatureBlock; - DummyHost host = CreateDummyHostForControlBlockAfterIncludedTemplateWithClassFeatureBlockTest (); - - string expectedOutput = TemplatingEngineHelper.CleanCodeDom (Output_ControlBlockAfterIncludedTemplateWithClassFeatureBlock, "\n"); - string output = Preprocess (input, host); - - Assert.AreEqual (expectedOutput, output, output); - } - - [Test] - public void CaptureEncodingAndExtension () - { - string input = InputTemplate_CaptureEncodingAndExtension; - string output = Preprocess (input); - string expectedOutput = TemplatingEngineHelper.CleanCodeDom (Output_CaptureEncodingAndExtension, "\n"); - - Assert.AreEqual (expectedOutput, output, output); - } - - #region Helpers - - string Preprocess (string input) - { - DummyHost host = new DummyHost (); - return Preprocess (input, host); - } - - string Preprocess (string input, DummyHost host) - { - string className = "PreprocessedTemplate"; - string classNamespace = "Templating"; - string language = null; - string[] references = null; - - TemplatingEngine engine = new TemplatingEngine (); - string output = engine.PreprocessTemplate (input, host, className, classNamespace, out language, out references); - ReportErrors (host.Errors); - if (output != null) { - return TemplatingEngineHelper.CleanCodeDom (output, "\n"); - } - return null; - } - - void ReportErrors(CompilerErrorCollection errors) - { - foreach (CompilerError error in errors) { - Console.WriteLine(error.ErrorText); - } - } - - DummyHost CreateDummyHostForControlBlockAfterIncludedTemplateWithClassFeatureBlockTest() - { - DummyHost host = new DummyHost (); - - string includeTemplateFileName = @"d:\test\IncludedFile.tt"; - host.Locations.Add (includeTemplateFileName, includeTemplateFileName); - host.Contents.Add (includeTemplateFileName, IncludedTemplate_ControlBlockAfterIncludedTemplate); - - return host; - } - - #endregion - - #region Input templates - - public static string InputTemplate_ControlBlockAfterIncludedTemplateWithClassFeatureBlock = -@" -<#@ template debug=""false"" language=""C#"" #> -<#@ output extension="".cs"" #> -Text Block 1 -<# - this.TemplateMethod(); -#> -Text Block 2 -<#@ include file=""d:\test\IncludedFile.tt"" #> -Text Block 3 -<# - this.IncludedMethod(); -#> -<#+ - void TemplateMethod() - { - } -#> -"; - - public static string IncludedTemplate_ControlBlockAfterIncludedTemplate = -@" -<#@ template debug=""false"" language=""C#"" #> -<#@ output extension="".cs"" #> -Included Text Block 1 -<# this.WriteLine(""Included statement block""); #> -Included Text Block 2 -<#+ - void IncludedMethod() - { -#> -Included Method Body Text Block -<#+ - } -#> -"; - - public static string InputTemplate_CaptureEncodingAndExtension = - @" -<#@ template debug=""false"" language=""C#"" inherits=""Foo"" hostspecific=""trueFromBase"" #> -<#@ output extension="".cs"" encoding=""utf-8"" #> -"; - - #endregion - - #region Expected output strings - - public static string OutputSample1 = -@" -namespace Templating { - - - public partial class PreprocessedTemplate : PreprocessedTemplateBase { - - public virtual string TransformText() { - this.GenerationEnvironment = null; - - #line 2 """" - - this.Write(""Test\r\n""); - - #line default - #line hidden - return this.GenerationEnvironment.ToString(); - } - - public virtual void Initialize() { - } - } - - public class PreprocessedTemplateBase { - - private global::System.Text.StringBuilder builder; - - private global::System.Collections.Generic.IDictionary<string, object> session; - - private global::System.CodeDom.Compiler.CompilerErrorCollection errors; - - private string currentIndent = string.Empty; - - private global::System.Collections.Generic.Stack<int> indents; - - private ToStringInstanceHelper _toStringHelper = new ToStringInstanceHelper(); - - public virtual global::System.Collections.Generic.IDictionary<string, object> Session { - get { - return this.session; - } - set { - this.session = value; - } - } - - public global::System.Text.StringBuilder GenerationEnvironment { - get { - if ((this.builder == null)) { - this.builder = new global::System.Text.StringBuilder(); - } - return this.builder; - } - set { - this.builder = value; - } - } - - protected global::System.CodeDom.Compiler.CompilerErrorCollection Errors { - get { - if ((this.errors == null)) { - this.errors = new global::System.CodeDom.Compiler.CompilerErrorCollection(); - } - return this.errors; - } - } - - public string CurrentIndent { - get { - return this.currentIndent; - } - } - - private global::System.Collections.Generic.Stack<int> Indents { - get { - if ((this.indents == null)) { - this.indents = new global::System.Collections.Generic.Stack<int>(); - } - return this.indents; - } - } - - public ToStringInstanceHelper ToStringHelper { - get { - return this._toStringHelper; - } - } - - public void Error(string message) { - this.Errors.Add(new global::System.CodeDom.Compiler.CompilerError(null, -1, -1, null, message)); - } - - public void Warning(string message) { - global::System.CodeDom.Compiler.CompilerError val = new global::System.CodeDom.Compiler.CompilerError(null, -1, -1, null, message); - val.IsWarning = true; - this.Errors.Add(val); - } - - public string PopIndent() { - if ((this.Indents.Count == 0)) { - return string.Empty; - } - int lastPos = (this.currentIndent.Length - this.Indents.Pop()); - string last = this.currentIndent.Substring(lastPos); - this.currentIndent = this.currentIndent.Substring(0, lastPos); - return last; - } - - public void PushIndent(string indent) { - this.Indents.Push(indent.Length); - this.currentIndent = (this.currentIndent + indent); - } - - public void ClearIndent() { - this.currentIndent = string.Empty; - this.Indents.Clear(); - } - - public void Write(string textToAppend) { - this.GenerationEnvironment.Append(textToAppend); - } - - public void Write(string format, params object[] args) { - this.GenerationEnvironment.AppendFormat(format, args); - } - - public void WriteLine(string textToAppend) { - this.GenerationEnvironment.Append(this.currentIndent); - this.GenerationEnvironment.AppendLine(textToAppend); - } - - public void WriteLine(string format, params object[] args) { - this.GenerationEnvironment.Append(this.currentIndent); - this.GenerationEnvironment.AppendFormat(format, args); - this.GenerationEnvironment.AppendLine(); - } - - public class ToStringInstanceHelper { - - private global::System.IFormatProvider formatProvider = global::System.Globalization.CultureInfo.InvariantCulture; - - public global::System.IFormatProvider FormatProvider { - get { - return this.formatProvider; - } - set { - if ((value != null)) { - this.formatProvider = value; - } - } - } - - public string ToStringWithCulture(object objectToConvert) { - if ((objectToConvert == null)) { - throw new global::System.ArgumentNullException(""objectToConvert""); - } - global::System.Type type = objectToConvert.GetType(); - global::System.Type iConvertibleType = typeof(global::System.IConvertible); - if (iConvertibleType.IsAssignableFrom(type)) { - return ((global::System.IConvertible)(objectToConvert)).ToString(this.formatProvider); - } - global::System.Reflection.MethodInfo methInfo = type.GetMethod(""ToString"", new global::System.Type[] { - iConvertibleType}); - if ((methInfo != null)) { - return ((string)(methInfo.Invoke(objectToConvert, new object[] { - this.formatProvider}))); - } - return objectToConvert.ToString(); - } - } - } -} -"; - - public static string Output_ControlBlockAfterIncludedTemplateWithClassFeatureBlock = -@" -namespace Templating { - - - public partial class PreprocessedTemplate : PreprocessedTemplateBase { - - - #line 14 """" - - void TemplateMethod() - { - } - - #line default - #line hidden - - - #line 7 ""d:\test\IncludedFile.tt"" - - void IncludedMethod() - { - - #line default - #line hidden - - - #line 11 ""d:\test\IncludedFile.tt"" - this.Write(""Included Method Body Text Block\n""); - - #line default - #line hidden - - - #line 12 ""d:\test\IncludedFile.tt"" - - } - - #line default - #line hidden - - public virtual string TransformText() { - this.GenerationEnvironment = null; - - #line 1 """" - this.Write(""\n""); - - #line default - #line hidden - - #line 4 """" - this.Write(""Text Block 1\n""); - - #line default - #line hidden - - #line 5 """" - - this.TemplateMethod(); - - - #line default - #line hidden - - #line 8 """" - this.Write(""Text Block 2\n""); - - #line default - #line hidden - - #line 1 ""d:\test\IncludedFile.tt"" - this.Write(""\n""); - - #line default - #line hidden - - #line 4 ""d:\test\IncludedFile.tt"" - this.Write(""Included Text Block 1\n""); - - #line default - #line hidden - - #line 5 ""d:\test\IncludedFile.tt"" - this.WriteLine(""Included statement block""); - - #line default - #line hidden - - #line 6 ""d:\test\IncludedFile.tt"" - this.Write(""Included Text Block 2\n""); - - #line default - #line hidden - - #line 10 """" - this.Write(""Text Block 3\n""); - - #line default - #line hidden - - #line 11 """" - - this.IncludedMethod(); - - - #line default - #line hidden - return this.GenerationEnvironment.ToString(); - } - - public virtual void Initialize() { - } - } - - public class PreprocessedTemplateBase { - - private global::System.Text.StringBuilder builder; - - private global::System.Collections.Generic.IDictionary<string, object> session; - - private global::System.CodeDom.Compiler.CompilerErrorCollection errors; - - private string currentIndent = string.Empty; - - private global::System.Collections.Generic.Stack<int> indents; - - private ToStringInstanceHelper _toStringHelper = new ToStringInstanceHelper(); - - public virtual global::System.Collections.Generic.IDictionary<string, object> Session { - get { - return this.session; - } - set { - this.session = value; - } - } - - public global::System.Text.StringBuilder GenerationEnvironment { - get { - if ((this.builder == null)) { - this.builder = new global::System.Text.StringBuilder(); - } - return this.builder; - } - set { - this.builder = value; - } - } - - protected global::System.CodeDom.Compiler.CompilerErrorCollection Errors { - get { - if ((this.errors == null)) { - this.errors = new global::System.CodeDom.Compiler.CompilerErrorCollection(); - } - return this.errors; - } - } - - public string CurrentIndent { - get { - return this.currentIndent; - } - } - - private global::System.Collections.Generic.Stack<int> Indents { - get { - if ((this.indents == null)) { - this.indents = new global::System.Collections.Generic.Stack<int>(); - } - return this.indents; - } - } - - public ToStringInstanceHelper ToStringHelper { - get { - return this._toStringHelper; - } - } - - public void Error(string message) { - this.Errors.Add(new global::System.CodeDom.Compiler.CompilerError(null, -1, -1, null, message)); - } - - public void Warning(string message) { - global::System.CodeDom.Compiler.CompilerError val = new global::System.CodeDom.Compiler.CompilerError(null, -1, -1, null, message); - val.IsWarning = true; - this.Errors.Add(val); - } - - public string PopIndent() { - if ((this.Indents.Count == 0)) { - return string.Empty; - } - int lastPos = (this.currentIndent.Length - this.Indents.Pop()); - string last = this.currentIndent.Substring(lastPos); - this.currentIndent = this.currentIndent.Substring(0, lastPos); - return last; - } - - public void PushIndent(string indent) { - this.Indents.Push(indent.Length); - this.currentIndent = (this.currentIndent + indent); - } - - public void ClearIndent() { - this.currentIndent = string.Empty; - this.Indents.Clear(); - } - - public void Write(string textToAppend) { - this.GenerationEnvironment.Append(textToAppend); - } - - public void Write(string format, params object[] args) { - this.GenerationEnvironment.AppendFormat(format, args); - } - - public void WriteLine(string textToAppend) { - this.GenerationEnvironment.Append(this.currentIndent); - this.GenerationEnvironment.AppendLine(textToAppend); - } - - public void WriteLine(string format, params object[] args) { - this.GenerationEnvironment.Append(this.currentIndent); - this.GenerationEnvironment.AppendFormat(format, args); - this.GenerationEnvironment.AppendLine(); - } - - public class ToStringInstanceHelper { - - private global::System.IFormatProvider formatProvider = global::System.Globalization.CultureInfo.InvariantCulture; - - public global::System.IFormatProvider FormatProvider { - get { - return this.formatProvider; - } - set { - if ((value != null)) { - this.formatProvider = value; - } - } - } - - public string ToStringWithCulture(object objectToConvert) { - if ((objectToConvert == null)) { - throw new global::System.ArgumentNullException(""objectToConvert""); - } - global::System.Type type = objectToConvert.GetType(); - global::System.Type iConvertibleType = typeof(global::System.IConvertible); - if (iConvertibleType.IsAssignableFrom(type)) { - return ((global::System.IConvertible)(objectToConvert)).ToString(this.formatProvider); - } - global::System.Reflection.MethodInfo methInfo = type.GetMethod(""ToString"", new global::System.Type[] { - iConvertibleType}); - if ((methInfo != null)) { - return ((string)(methInfo.Invoke(objectToConvert, new object[] { - this.formatProvider}))); - } - return objectToConvert.ToString(); - } - } - } -} -"; - - public static string Output_CaptureEncodingAndExtension = - - @"namespace Templating { - - - public partial class PreprocessedTemplate : Foo { - - public override string TransformText() { - this.GenerationEnvironment = null; - - #line 1 """" - this.Write(""\n""); - - #line default - #line hidden - return this.GenerationEnvironment.ToString(); - } - - public override void Initialize() { - if ((this.Host != null)) { - this.Host.SetFileExtension("".cs""); - this.Host.SetOutputEncoding(System.Text.Encoding.GetEncoding(65001, true)); - } - base.Initialize(); - } - } -}"; - #endregion - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/TemplatingEngineHelper.cs b/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/TemplatingEngineHelper.cs deleted file mode 100644 index da432927ba..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/TemplatingEngineHelper.cs +++ /dev/null @@ -1,72 +0,0 @@ -//
-// Test.cs
-//
-// Author:
-// Michael Hutchinson <mhutchinson@novell.com>
-//
-// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-using System.IO;
-
-namespace Mono.TextTemplating.Tests
-{
- public static class TemplatingEngineHelper
- {
- /// <summary> - /// Cleans CodeDOM generated code so that Windows/Mac and Mono/.NET output can be compared. - /// </summary> - public static string CleanCodeDom (string input, string newLine) - {
- using (var writer = new StringWriter ()) {
- using (var reader = new StringReader (input)) {
- - bool afterLineDirective = true; - bool stripHeader = true; - - string line;
- while ((line = reader.ReadLine ()) != null) {
- - if (stripHeader) { - if (line.StartsWith ("//", StringComparison.Ordinal) || string.IsNullOrWhiteSpace (line)) - continue; - stripHeader = false; - } - - if (afterLineDirective) { - if (string.IsNullOrWhiteSpace (line)) - continue; - afterLineDirective = false; - } - - if (line.Contains ("#line")) { - afterLineDirective = true; - } - - writer.Write (line);
- writer.Write (newLine);
- }
- }
- return writer.ToString ();
- }
- }
- }
-}
diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/TextTemplatingSessionTests.cs b/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/TextTemplatingSessionTests.cs deleted file mode 100644 index c5b0606394..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/TextTemplatingSessionTests.cs +++ /dev/null @@ -1,57 +0,0 @@ -//
-// TextTemplatingSessionTests.cs
-//
-// Author:
-// Matt Ward <matt.ward@xamarin.com>
-//
-// Copyright (c) 2016 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-using System.Reflection;
-using Microsoft.VisualStudio.TextTemplating;
-using NUnit.Framework;
-
-namespace Mono.TextTemplating.Tests
-{
- [TestFixture]
- public class TextTemplatingSessionTests
- {
- [Test]
- public void AppDomainSerializationTest ()
- {
- var guid = Guid.NewGuid ();
- var appDomain = AppDomain.CreateDomain ("TextTemplatingSessionSerializationTestAppDomain");
-
- var session = (TextTemplatingSession)appDomain.CreateInstanceFromAndUnwrap (
- typeof(TextTemplatingSession).Assembly.Location,
- typeof(TextTemplatingSession).FullName,
- false,
- BindingFlags.Public | BindingFlags.Instance,
- null,
- new object[] { guid },
- null,
- null);
-
- Assert.AreEqual (guid, session.Id);
- }
- }
-}
-
diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/AssemblyInfo.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/AssemblyInfo.cs deleted file mode 100644 index 13849716d3..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/AssemblyInfo.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// AssemblyInfo.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System.Reflection; -using System.Runtime.CompilerServices; -using System; - -[assembly: AssemblyTitle("Mono.TextTemplating")] -[assembly: AssemblyDescription("An implementation of Visual Studio's T4 text templating")] -[assembly: AssemblyCompany("The Mono Project")] -[assembly: AssemblyProduct("MonoDevelop")] -[assembly: AssemblyCopyright("MIT/X11")] -[assembly: CLSCompliant (true)] - -//[assembly: AssemblyVersion("1.0.0.0")] diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Makefile.am b/main/src/addins/TextTemplating/Mono.TextTemplating/Makefile.am deleted file mode 100644 index c9cc87438f..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Makefile.am +++ /dev/null @@ -1 +0,0 @@ -include $(top_srcdir)/xbuild.include diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessor.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessor.cs deleted file mode 100644 index 133bcb64ca..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessor.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -// DirectiveProcessor.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.CodeDom.Compiler; -using System.CodeDom; - -namespace Microsoft.VisualStudio.TextTemplating -{ - public abstract class DirectiveProcessor : IDirectiveProcessor - { - CompilerErrorCollection errors; - - protected DirectiveProcessor () - { - } - - public virtual void Initialize (ITextTemplatingEngineHost host) - { - if (host == null) - throw new ArgumentNullException ("host"); - } - - public virtual void StartProcessingRun (CodeDomProvider languageProvider, string templateContents, CompilerErrorCollection errors) - { - if (languageProvider == null) - throw new ArgumentNullException ("languageProvider"); - this.errors = errors; - } - - public abstract void FinishProcessingRun (); - public abstract string GetClassCodeForProcessingRun (); - public abstract string[] GetImportsForProcessingRun (); - public abstract string GetPostInitializationCodeForProcessingRun (); - public abstract string GetPreInitializationCodeForProcessingRun (); - public abstract string[] GetReferencesForProcessingRun (); - public abstract bool IsDirectiveSupported (string directiveName); - public abstract void ProcessDirective (string directiveName, IDictionary<string, string> arguments); - - public virtual CodeAttributeDeclarationCollection GetTemplateClassCustomAttributes () - { - return null; - } - - CompilerErrorCollection IDirectiveProcessor.Errors { get { return errors; } } - - void IDirectiveProcessor.SetProcessingRunIsHostSpecific (bool hostSpecific) - { - } - - bool IDirectiveProcessor.RequiresProcessingRunIsHostSpecific { - get { return false; } - } - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessorException.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessorException.cs deleted file mode 100644 index 1d95facae1..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessorException.cs +++ /dev/null @@ -1,56 +0,0 @@ -// -// DirectiveProcessorException.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Runtime.Serialization; - -namespace Microsoft.VisualStudio.TextTemplating -{ - - [Serializable] - public class DirectiveProcessorException : Exception - { - - public DirectiveProcessorException () - { - } - - public DirectiveProcessorException (string message) - : base (message) - { - } - - public DirectiveProcessorException (SerializationInfo info, StreamingContext context) - : base (info, context) - { - } - - public DirectiveProcessorException (string message, Exception inner) - : base (message, inner) - { - } - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/EncodingHelper.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/EncodingHelper.cs deleted file mode 100644 index beb7c9edb5..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/EncodingHelper.cs +++ /dev/null @@ -1,40 +0,0 @@ -//
-// EncodingHelper.cs
-//
-// Author:
-// Michael Hutchinson <mhutchinson@novell.com>
-//
-// Copyright (c) 2010 Novell, 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.Text;
-
-namespace Microsoft.VisualStudio.TextTemplating
-{
- public static class EncodingHelper
- {
- public static Encoding GetEncoding (string filePath)
- {
- throw new NotImplementedException ();
- }
- }
-}
-
diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Engine.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Engine.cs deleted file mode 100644 index fc9c9aacba..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Engine.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -// Engine.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.IO; -using System.Text; -using System.Collections.Generic; -using System.CodeDom; -using System.CodeDom.Compiler; -using Mono.TextTemplating; - -namespace Microsoft.VisualStudio.TextTemplating -{ - public class Engine : ITextTemplatingEngine - { - TemplatingEngine engine = new TemplatingEngine (); - - public Engine () - { - } - - public string ProcessTemplate (string content, ITextTemplatingEngineHost host) - { - return engine.ProcessTemplate (content, host); - } - - public string PreprocessTemplate (string content, ITextTemplatingEngineHost host, string className, - string classNamespace, out string language, out string[] references) - { - return engine.PreprocessTemplate (content, host, className, classNamespace, out language, out references); - } - - public const string CacheAssembliesOptionString = "CacheAssemblies"; - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Interfaces.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Interfaces.cs deleted file mode 100644 index bf7f62a23d..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Interfaces.cs +++ /dev/null @@ -1,104 +0,0 @@ -// -// ITextTemplatingEngineHost.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009-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.Text; -using System.CodeDom.Compiler; -using System.Collections.Generic; -using System.Collections; -using System.Runtime.Serialization; -using System.CodeDom; - -namespace Microsoft.VisualStudio.TextTemplating -{ - public interface IRecognizeHostSpecific - { - void SetProcessingRunIsHostSpecific (bool hostSpecific); - bool RequiresProcessingRunIsHostSpecific { get; } - } - - [CLSCompliant(true)] - public interface ITextTemplatingEngine - { - string ProcessTemplate (string content, ITextTemplatingEngineHost host); - string PreprocessTemplate (string content, ITextTemplatingEngineHost host, string className, - string classNamespace, out string language, out string[] references); - } - - [CLSCompliant(true)] - public interface ITextTemplatingEngineHost - { - object GetHostOption (string optionName); - bool LoadIncludeText (string requestFileName, out string content, out string location); - void LogErrors (CompilerErrorCollection errors); - AppDomain ProvideTemplatingAppDomain (string content); - string ResolveAssemblyReference (string assemblyReference); - Type ResolveDirectiveProcessor (string processorName); - string ResolveParameterValue (string directiveId, string processorName, string parameterName); - string ResolvePath (string path); - void SetFileExtension (string extension); - void SetOutputEncoding (Encoding encoding, bool fromOutputDirective); - IList<string> StandardAssemblyReferences { get; } - IList<string> StandardImports { get; } - string TemplateFile { get; } - } - - [CLSCompliant(true)] - public interface ITextTemplatingSession : - IEquatable<ITextTemplatingSession>, IEquatable<Guid>, IDictionary<string, Object>, - ICollection<KeyValuePair<string, Object>>, - IEnumerable<KeyValuePair<string, Object>>, - IEnumerable, ISerializable - { - Guid Id { get; } - } - - [CLSCompliant(true)] - public interface ITextTemplatingSessionHost - { - ITextTemplatingSession CreateSession (); - ITextTemplatingSession Session { get; set; } - } - - public interface IDirectiveProcessor - { - CompilerErrorCollection Errors { get; } - bool RequiresProcessingRunIsHostSpecific { get; } - - void FinishProcessingRun (); - string GetClassCodeForProcessingRun (); - string[] GetImportsForProcessingRun (); - string GetPostInitializationCodeForProcessingRun (); - string GetPreInitializationCodeForProcessingRun (); - string[] GetReferencesForProcessingRun (); - CodeAttributeDeclarationCollection GetTemplateClassCustomAttributes (); //TODO - void Initialize (ITextTemplatingEngineHost host); - bool IsDirectiveSupported (string directiveName); - void ProcessDirective (string directiveName, IDictionary<string, string> arguments); - void SetProcessingRunIsHostSpecific (bool hostSpecific); - void StartProcessingRun (CodeDomProvider languageProvider, string templateContents, CompilerErrorCollection errors); - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ParameterDirectiveProcessor.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ParameterDirectiveProcessor.cs deleted file mode 100644 index cc5eb4123d..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ParameterDirectiveProcessor.cs +++ /dev/null @@ -1,211 +0,0 @@ -// -// ParameterDirectiveProcessor.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2010 Novell, 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.CodeDom; -using System.CodeDom.Compiler; -using System.Collections.Generic; -using System.IO; -using Mono.TextTemplating; - -namespace Microsoft.VisualStudio.TextTemplating -{ - public sealed class ParameterDirectiveProcessor : DirectiveProcessor, IRecognizeHostSpecific - { - CodeDomProvider provider; - - bool hostSpecific; - readonly List<CodeStatement> postStatements = new List<CodeStatement> (); - readonly List<CodeTypeMember> members = new List<CodeTypeMember> (); - - public override void StartProcessingRun (CodeDomProvider languageProvider, string templateContents, CompilerErrorCollection errors) - { - base.StartProcessingRun (languageProvider, templateContents, errors); - provider = languageProvider; - postStatements.Clear (); - members.Clear (); - } - - public override void FinishProcessingRun () - { - var statement = new CodeConditionStatement ( - new CodeBinaryOperatorExpression ( - new CodePropertyReferenceExpression ( - new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "Errors"), "HasErrors"), - CodeBinaryOperatorType.ValueEquality, - new CodePrimitiveExpression (false)), - postStatements.ToArray ()); - - postStatements.Clear (); - postStatements.Add (statement); - } - - public override string GetClassCodeForProcessingRun () - { - return TemplatingEngine.GenerateIndentedClassCode (provider, members); - } - - public override string[] GetImportsForProcessingRun () - { - return null; - } - - public override string GetPostInitializationCodeForProcessingRun () - { - return TemplatingEngine.IndentSnippetText (provider, StatementsToCode (postStatements), " "); - } - - public override string GetPreInitializationCodeForProcessingRun () - { - return null; - } - - string StatementsToCode (List<CodeStatement> statements) - { - var options = new CodeGeneratorOptions (); - using (var sw = new StringWriter ()) { - foreach (var statement in statements) - provider.GenerateCodeFromStatement (statement, sw, options); - return sw.ToString (); - } - } - - public override string[] GetReferencesForProcessingRun () - { - return null; - } - - public override bool IsDirectiveSupported (string directiveName) - { - return directiveName == "parameter"; - } - - public override void ProcessDirective (string directiveName, IDictionary<string, string> arguments) - { - string name = arguments["name"]; - string type = arguments["type"]; - if (string.IsNullOrEmpty (name)) - throw new DirectiveProcessorException ("Parameter directive has no name argument"); - if (string.IsNullOrEmpty (type)) - throw new DirectiveProcessorException ("Parameter directive has no type argument"); - - string fieldName = "_" + name + "Field"; - var typeRef = new CodeTypeReference (type); - var thisRef = new CodeThisReferenceExpression (); - var fieldRef = new CodeFieldReferenceExpression (thisRef, fieldName); - - var property = new CodeMemberProperty () { - Name = name, - Attributes = MemberAttributes.Public | MemberAttributes.Final, - HasGet = true, - HasSet = false, - Type = typeRef - }; - property.GetStatements.Add (new CodeMethodReturnStatement (fieldRef)); - members.Add (new CodeMemberField (typeRef, fieldName)); - members.Add (property); - - string acquiredName = "_" + name + "Acquired"; - var valRef = new CodeVariableReferenceExpression ("data"); - var namePrimitive = new CodePrimitiveExpression (name); - var sessionRef = new CodePropertyReferenceExpression (thisRef, "Session"); - var callContextTypeRefExpr = new CodeTypeReferenceExpression ("System.Runtime.Remoting.Messaging.CallContext"); - var nullPrim = new CodePrimitiveExpression (null); - - var acquiredVariable = new CodeVariableDeclarationStatement (typeof (bool), acquiredName, new CodePrimitiveExpression (false)); - var acquiredVariableRef = new CodeVariableReferenceExpression (acquiredVariable.Name); - this.postStatements.Add (acquiredVariable); - - //checks the local called "data" can be cast and assigned to the field, and if successful, sets acquiredVariable to true - var checkCastThenAssignVal = new CodeConditionStatement ( - new CodeMethodInvokeExpression ( - new CodeTypeOfExpression (typeRef), "IsAssignableFrom", new CodeMethodInvokeExpression (valRef, "GetType")), - new CodeStatement[] { - new CodeAssignStatement (fieldRef, new CodeCastExpression (typeRef, valRef)), - new CodeAssignStatement (acquiredVariableRef, new CodePrimitiveExpression (true)), - }, - new CodeStatement[] { - new CodeExpressionStatement (new CodeMethodInvokeExpression (thisRef, "Error", - new CodePrimitiveExpression ("The type '" + type + "' of the parameter '" + name + - "' did not match the type passed to the template"))), - }); - - //tries to gets the value from the session - var checkSession = new CodeConditionStatement ( - new CodeBinaryOperatorExpression (NotNull (sessionRef), CodeBinaryOperatorType.BooleanAnd, - new CodeMethodInvokeExpression (sessionRef, "ContainsKey", namePrimitive)), - new CodeVariableDeclarationStatement (typeof (object), "data", new CodeIndexerExpression (sessionRef, namePrimitive)), - checkCastThenAssignVal); - - this.postStatements.Add (checkSession); - - //if acquiredVariable is false, tries to gets the value from the host - if (hostSpecific) { - var hostRef = new CodePropertyReferenceExpression (thisRef, "Host"); - var checkHost = new CodeConditionStatement ( - BooleanAnd (IsFalse (acquiredVariableRef), NotNull (hostRef)), - new CodeVariableDeclarationStatement (typeof (string), "data", - new CodeMethodInvokeExpression (hostRef, "ResolveParameterValue", nullPrim, nullPrim, namePrimitive)), - new CodeConditionStatement (NotNull (valRef), checkCastThenAssignVal)); - - this.postStatements.Add (checkHost); - } - - //if acquiredVariable is false, tries to gets the value from the call context - var checkCallContext = new CodeConditionStatement ( - IsFalse (acquiredVariableRef), - new CodeVariableDeclarationStatement (typeof (object), "data", - new CodeMethodInvokeExpression (callContextTypeRefExpr, "LogicalGetData", namePrimitive)), - new CodeConditionStatement (NotNull (valRef), checkCastThenAssignVal)); - - this.postStatements.Add (checkCallContext); - } - - static CodeBinaryOperatorExpression NotNull (CodeExpression reference) - { - return new CodeBinaryOperatorExpression (reference, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null)); - } - - static CodeBinaryOperatorExpression IsFalse (CodeExpression expr) - { - return new CodeBinaryOperatorExpression (expr, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (false)); - } - - static CodeBinaryOperatorExpression BooleanAnd (CodeExpression expr1, CodeExpression expr2) - { - return new CodeBinaryOperatorExpression (expr1, CodeBinaryOperatorType.BooleanAnd, expr2); - } - - void IRecognizeHostSpecific.SetProcessingRunIsHostSpecific (bool hostSpecific) - { - this.hostSpecific = hostSpecific; - } - - public bool RequiresProcessingRunIsHostSpecific { - get { return false; } - } - } -} - diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/RequiresProvidesDirectiveProcessor.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/RequiresProvidesDirectiveProcessor.cs deleted file mode 100644 index bb48357c32..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/RequiresProvidesDirectiveProcessor.cs +++ /dev/null @@ -1,196 +0,0 @@ -// -// RequiresProvidesDirectiveProcessor.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.CodeDom.Compiler; -using System.Text; - -namespace Microsoft.VisualStudio.TextTemplating -{ - - - public abstract class RequiresProvidesDirectiveProcessor : DirectiveProcessor - { - bool isInProcessingRun; - ITextTemplatingEngineHost host; - StringBuilder preInitBuffer = new StringBuilder (); - StringBuilder postInitBuffer = new StringBuilder (); - StringBuilder codeBuffer = new StringBuilder (); - CodeDomProvider languageProvider; - - protected RequiresProvidesDirectiveProcessor () - { - } - - public override void Initialize (ITextTemplatingEngineHost host) - { - base.Initialize (host); - this.host = host; - } - - protected abstract void InitializeProvidesDictionary (string directiveName, IDictionary<string, string> providesDictionary); - protected abstract void InitializeRequiresDictionary (string directiveName, IDictionary<string, string> requiresDictionary); - protected abstract string FriendlyName { get; } - - protected abstract void GeneratePostInitializationCode (string directiveName, StringBuilder codeBuffer, CodeDomProvider languageProvider, - IDictionary<string, string> requiresArguments, IDictionary<string, string> providesArguments); - protected abstract void GeneratePreInitializationCode (string directiveName, StringBuilder codeBuffer, CodeDomProvider languageProvider, - IDictionary<string, string> requiresArguments, IDictionary<string, string> providesArguments); - protected abstract void GenerateTransformCode (string directiveName, StringBuilder codeBuffer, CodeDomProvider languageProvider, - IDictionary<string, string> requiresArguments, IDictionary<string, string> providesArguments); - - protected virtual void PostProcessArguments (string directiveName, IDictionary<string, string> requiresArguments, - IDictionary<string, string> providesArguments) - { - } - - public override string GetClassCodeForProcessingRun () - { - AssertNotProcessing (); - return codeBuffer.ToString (); - } - - public override string[] GetImportsForProcessingRun () - { - AssertNotProcessing (); - return null; - } - - public override string[] GetReferencesForProcessingRun () - { - AssertNotProcessing (); - return null; - } - - public override string GetPostInitializationCodeForProcessingRun () - { - AssertNotProcessing (); - return postInitBuffer.ToString (); - } - - public override string GetPreInitializationCodeForProcessingRun () - { - AssertNotProcessing (); - return preInitBuffer.ToString (); - } - - public override void StartProcessingRun (CodeDomProvider languageProvider, string templateContents, CompilerErrorCollection errors) - { - AssertNotProcessing (); - isInProcessingRun = true; - base.StartProcessingRun (languageProvider, templateContents, errors); - - this.languageProvider = languageProvider; - codeBuffer.Length = 0; - preInitBuffer.Length = 0; - postInitBuffer.Length = 0; - } - - public override void FinishProcessingRun () - { - isInProcessingRun = false; - } - - void AssertNotProcessing () - { - if (isInProcessingRun) - throw new InvalidOperationException (); - } - - //FIXME: handle escaping - IEnumerable<KeyValuePair<string,string>> ParseArgs (string args) - { - var pairs = args.Split (';'); - foreach (var p in pairs) { - int eq = p.IndexOf ('='); - var k = p.Substring (0, eq); - var v = p.Substring (eq); - yield return new KeyValuePair<string, string> (k, v); - } - } - - public override void ProcessDirective (string directiveName, IDictionary<string, string> arguments) - { - if (directiveName == null) - throw new ArgumentNullException ("directiveName"); - if (arguments == null) - throw new ArgumentNullException ("arguments"); - - var providesDictionary = new Dictionary<string,string> (); - var requiresDictionary = new Dictionary<string,string> (); - - string provides; - if (arguments.TryGetValue ("provides", out provides)) { - foreach (var arg in ParseArgs (provides)) { - providesDictionary.Add (arg.Key, arg.Value); - } - } - - string requires; - if (arguments.TryGetValue ("requires", out requires)) { - foreach (var arg in ParseArgs (requires)) { - requiresDictionary.Add (arg.Key, arg.Value); - } - } - - InitializeRequiresDictionary (directiveName, requiresDictionary); - InitializeProvidesDictionary (directiveName, providesDictionary); - - var id = ProvideUniqueId (directiveName, arguments, requiresDictionary, providesDictionary); - - foreach (var req in requiresDictionary) { - var val = host.ResolveParameterValue (id, FriendlyName, req.Key); - if (val != null) - requiresDictionary[req.Key] = val; - else if (req.Value == null) - throw new DirectiveProcessorException ("Could not resolve required value '" + req.Key + "'"); - } - - foreach (var req in providesDictionary) { - var val = host.ResolveParameterValue (id, FriendlyName, req.Key); - if (val != null) - providesDictionary[req.Key] = val; - } - - PostProcessArguments (directiveName, requiresDictionary, providesDictionary); - - GeneratePreInitializationCode (directiveName, preInitBuffer, languageProvider, requiresDictionary, providesDictionary); - GeneratePostInitializationCode (directiveName, postInitBuffer, languageProvider, requiresDictionary, providesDictionary); - GenerateTransformCode (directiveName, codeBuffer, languageProvider, requiresDictionary, providesDictionary); - } - - protected virtual string ProvideUniqueId (string directiveName, IDictionary<string, string> arguments, - IDictionary<string, string> requiresArguments, IDictionary<string, string> providesArguments) - { - return directiveName; - } - - protected ITextTemplatingEngineHost Host { - get { return host; } - } - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTemplatingSession.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTemplatingSession.cs deleted file mode 100644 index cf1fc83b20..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTemplatingSession.cs +++ /dev/null @@ -1,83 +0,0 @@ -//
-// TextTemplatingSession.cs
-//
-// Author:
-// Michael Hutchinson <mhutchinson@novell.com>
-//
-// Copyright (c) 2010 Novell, 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.Collections;
-using System.Runtime.Serialization;
-
-namespace Microsoft.VisualStudio.TextTemplating
-{
- [Serializable]
- public sealed class TextTemplatingSession : Dictionary<string, Object>, ITextTemplatingSession, ISerializable
- {
- public TextTemplatingSession () : this (Guid.NewGuid ())
- {
- }
-
- TextTemplatingSession (SerializationInfo info, StreamingContext context)
- : base (info, context)
- {
- Id = (Guid)info.GetValue ("Id", typeof (Guid));
- }
-
- public TextTemplatingSession (Guid id)
- {
- this.Id = id;
- }
-
- public Guid Id {
- get; private set;
- }
-
- public override int GetHashCode ()
- {
- return Id.GetHashCode ();
- }
-
- public override bool Equals (object obj)
- {
- var o = obj as TextTemplatingSession;
- return o != null && o.Equals (this);
- }
-
- public bool Equals (Guid other)
- {
- return other.Equals (Id);
- }
-
- public bool Equals (ITextTemplatingSession other)
- {
- return other != null && other.Id == this.Id;
- }
-
- void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
- {
- base.GetObjectData (info, context);
- info.AddValue ("Id", Id);
- }
- }
-}
-
diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTransformation.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTransformation.cs deleted file mode 100644 index f6a597752d..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTransformation.cs +++ /dev/null @@ -1,216 +0,0 @@ -// -// TextTransformation.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.CodeDom.Compiler; -using System.Collections.Generic; -using System.Text; - -namespace Microsoft.VisualStudio.TextTemplating -{ - public abstract class TextTransformation : IDisposable - { - Stack<int> indents; - string currentIndent = string.Empty; - CompilerErrorCollection errors; - StringBuilder builder; - bool endsWithNewline; - - public TextTransformation () - { - } - - public virtual void Initialize () - { - } - - public abstract string TransformText (); - - public virtual IDictionary<string, object> Session { get; set; } - - #region Errors - - public void Error (string message) - { - Errors.Add (new CompilerError ("", 0, 0, "", message)); - } - - public void Warning (string message) - { - Errors.Add (new CompilerError ("", 0, 0, "", message) { IsWarning = true }); - } - - protected internal CompilerErrorCollection Errors { - get { - if (errors == null) - errors = new CompilerErrorCollection (); - return errors; - } - } - - Stack<int> Indents { - get { - if (indents == null) - indents = new Stack<int> (); - return indents; - } - } - - #endregion - - #region Indents - - public string PopIndent () - { - if (Indents.Count == 0) - return ""; - int lastPos = currentIndent.Length - Indents.Pop (); - string last = currentIndent.Substring (lastPos); - currentIndent = currentIndent.Substring (0, lastPos); - return last; - } - - public void PushIndent (string indent) - { - if (indent == null) - throw new ArgumentNullException ("indent"); - Indents.Push (indent.Length); - currentIndent += indent; - } - - public void ClearIndent () - { - currentIndent = string.Empty; - Indents.Clear (); - } - - public string CurrentIndent { - get { return currentIndent; } - } - - #endregion - - #region Writing - - protected StringBuilder GenerationEnvironment { - get { - if (builder == null) - builder = new StringBuilder (); - return builder; - } - set { - builder = value; - } - } - - public void Write (string textToAppend) - { - if (string.IsNullOrEmpty (textToAppend)) - return; - - if ((GenerationEnvironment.Length == 0 || endsWithNewline) && CurrentIndent.Length > 0) { - GenerationEnvironment.Append (CurrentIndent); - } - endsWithNewline = false; - - char last = textToAppend[textToAppend.Length-1]; - if (last == '\n' || last == '\r') { - endsWithNewline = true; - } - - if (CurrentIndent.Length == 0) { - GenerationEnvironment.Append (textToAppend); - return; - } - - //insert CurrentIndent after every newline (\n, \r, \r\n) - //but if there's one at the end of the string, ignore it, it'll be handled next time thanks to endsWithNewline - int lastNewline = 0; - for (int i = 0; i < textToAppend.Length - 1; i++) { - char c = textToAppend[i]; - if (c == '\r') { - if (textToAppend[i + 1] == '\n') { - i++; - if (i == textToAppend.Length - 1) - break; - } - } else if (c != '\n') { - continue; - } - i++; - int len = i - lastNewline; - if (len > 0) { - GenerationEnvironment.Append (textToAppend, lastNewline, i - lastNewline); - } - GenerationEnvironment.Append (CurrentIndent); - lastNewline = i; - } - if (lastNewline > 0) - GenerationEnvironment.Append (textToAppend, lastNewline, textToAppend.Length - lastNewline); - else - GenerationEnvironment.Append (textToAppend); - } - - public void Write (string format, params object[] args) - { - Write (string.Format (format, args)); - } - - public void WriteLine (string textToAppend) - { - Write (textToAppend); - GenerationEnvironment.AppendLine (); - endsWithNewline = true; - } - - public void WriteLine (string format, params object[] args) - { - WriteLine (string.Format (format, args)); - } - - #endregion - - #region Dispose - - public void Dispose () - { - Dispose (true); - GC.SuppressFinalize (this); - } - - protected virtual void Dispose (bool disposing) - { - } - - ~TextTransformation () - { - Dispose (false); - } - - #endregion - - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ToStringHelper.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ToStringHelper.cs deleted file mode 100644 index 7f5934e238..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ToStringHelper.cs +++ /dev/null @@ -1,69 +0,0 @@ -// -// ToStringHelper.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace Microsoft.VisualStudio.TextTemplating -{ - public static class ToStringHelper - { - static object [] formatProviderAsParameterArray; - - static IFormatProvider formatProvider = System.Globalization.CultureInfo.InvariantCulture; - - static ToStringHelper () - { - formatProviderAsParameterArray = new object[] { formatProvider }; - } - - public static string ToStringWithCulture (object objectToConvert) - { - if (objectToConvert == null) - throw new ArgumentNullException ("objectToConvert"); - - IConvertible conv = objectToConvert as IConvertible; - if (conv != null) - return conv.ToString (formatProvider); - - var str = objectToConvert as string; - if (str != null) - return str; - - //TODO: implement a cache of types and DynamicMethods - MethodInfo mi = objectToConvert.GetType ().GetMethod ("ToString", new Type[] { typeof (IFormatProvider) }); - if (mi != null) - return (string) mi.Invoke (objectToConvert, formatProviderAsParameterArray); - return objectToConvert.ToString (); - } - - public static IFormatProvider FormatProvider { - get { return (IFormatProvider)formatProviderAsParameterArray[0]; } - set { formatProviderAsParameterArray[0] = formatProvider = value; } - } - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating.csproj b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating.csproj deleted file mode 100644 index 0c9a3d1d8e..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating.csproj +++ /dev/null @@ -1,83 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0"> - <Import Project="..\..\..\..\MonoDevelop.props" /> - <PropertyGroup> - <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> - <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> - <ProductVersion>8.0.30703</ProductVersion> - <SchemaVersion>2.0</SchemaVersion> - <ProjectGuid>{A2364D6A-00EF-417C-80A6-815726C70032}</ProjectGuid> - <OutputType>Library</OutputType> - <RootNamespace>Mono.TextTemplating</RootNamespace> - <AssemblyName>Mono.TextTemplating</AssemblyName> - <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <DebugSymbols>True</DebugSymbols> - <DebugType>full</DebugType> - <Optimize>False</Optimize> - <OutputPath>..\..\..\..\build\AddIns\MonoDevelop.TextTemplating</OutputPath> - <DefineConstants>DEBUG</DefineConstants> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - <ConsolePause>False</ConsolePause> - <NoWarn>1591;1573</NoWarn> - <DocumentationFile>..\..\..\..\build\AddIns\MonoDevelop.TextTemplating\Mono.TextTemplating.xml</DocumentationFile> - <AllowUnsafeBlocks>true</AllowUnsafeBlocks> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - <DebugType>pdbonly</DebugType> - <Optimize>true</Optimize> - <OutputPath>..\..\..\..\build\AddIns\MonoDevelop.TextTemplating</OutputPath> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - <ConsolePause>False</ConsolePause> - <DebugSymbols>true</DebugSymbols> - <NoWarn>1591;1573</NoWarn> - <DocumentationFile>..\..\..\..\build\AddIns\MonoDevelop.TextTemplating\Mono.TextTemplating.xml</DocumentationFile> - <AllowUnsafeBlocks>true</AllowUnsafeBlocks> - </PropertyGroup> - <ItemGroup> - <Reference Include="System" /> - <Reference Include="System.Core" /> - </ItemGroup> - <ItemGroup> - <Compile Include="Microsoft.VisualStudio.TextTemplating\DirectiveProcessor.cs" /> - <Compile Include="Microsoft.VisualStudio.TextTemplating\DirectiveProcessorException.cs" /> - <Compile Include="Microsoft.VisualStudio.TextTemplating\Engine.cs" /> - <Compile Include="Microsoft.VisualStudio.TextTemplating\RequiresProvidesDirectiveProcessor.cs" /> - <Compile Include="Microsoft.VisualStudio.TextTemplating\TextTransformation.cs" /> - <Compile Include="Microsoft.VisualStudio.TextTemplating\ToStringHelper.cs" /> - <Compile Include="Mono.TextTemplating\CompiledTemplate.cs" /> - <Compile Include="Mono.TextTemplating\ParsedTemplate.cs" /> - <Compile Include="Mono.TextTemplating\Tokeniser.cs" /> - <Compile Include="AssemblyInfo.cs" /> - <Compile Include="Mono.TextTemplating\TemplateGenerator.cs" /> - <Compile Include="Mono.TextTemplating\TemplatingEngine.cs" /> - <Compile Include="Mono.TextTemplating\TemplateSettings.cs" /> - <Compile Include="Mono.TextTemplating\CrossAppDomainAssemblyResolver.cs" /> - <Compile Include="Microsoft.VisualStudio.TextTemplating\EncodingHelper.cs" /> - <Compile Include="Microsoft.VisualStudio.TextTemplating\ParameterDirectiveProcessor.cs" /> - <Compile Include="Microsoft.VisualStudio.TextTemplating\TextTemplatingSession.cs" /> - <Compile Include="Microsoft.VisualStudio.TextTemplating\Interfaces.cs" /> - <Compile Include="Mono.TextTemplating\RecyclableAppDomain.cs" /> - <Compile Include="Mono.TextTemplating\FileUtil.cs" /> - </ItemGroup> - <ItemGroup> - <Folder Include="Microsoft.VisualStudio.TextTemplating\" /> - <Folder Include="Mono.TextTemplating\" /> - </ItemGroup> - <ItemGroup> - <InternalsVisibleTo Include="Mono.TextTemplating.Tests" /> - </ItemGroup> - <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> - <ProjectExtensions> - <MonoDevelop> - <Properties> - <Policies> - <DotNetNamingPolicy DirectoryNamespaceAssociation="Flat" ResourceNamePolicy="FileName" /> - </Policies> - </Properties> - </MonoDevelop> - </ProjectExtensions> -</Project> diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating.nuspec b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating.nuspec deleted file mode 100644 index 9b294cf88e..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating.nuspec +++ /dev/null @@ -1,21 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?>
-<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
- <metadata>
- <id>Mono.TextTemplating</id>
- <version>1.1.0</version> - <title>Mono.TextTemplating</title>
- <authors>Mikayla Hutchinson</authors> - <licenseUrl>http://opensource.org/licenses/MIT</licenseUrl>
- <projectUrl>https://github.com/mono/monodevelop/tree/master/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating</projectUrl>
- <requireLicenseAcceptance>false</requireLicenseAcceptance>
- <description>Open-source implementation of the T4 templating engine.</description>
- <releaseNotes>Built from MonoDevelop git repository, commit ad93842159363eaaebcb36701ac95a4eaef23c87</releaseNotes>
- <copyright>2009-2011 Novell, Inc. 2011-2016 Xamarin Inc.</copyright> - <tags>T4, templating</tags>
- </metadata>
- <files>
- <file src="../../../../build/AddIns/MonoDevelop.TextTemplating/Mono.TextTemplating.dll" target="lib/net45/Mono.TextTemplating.dll" /> - <file src="../../../../build/AddIns/MonoDevelop.TextTemplating/TextTransform.exe" target="tools/TextTransform.exe" /> - <file src="../../../../build/AddIns/MonoDevelop.TextTemplating/Mono.TextTemplating.dll" target="tools/Mono.TextTemplating.dll" /> - </files>
-</package> diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/CompiledTemplate.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/CompiledTemplate.cs deleted file mode 100644 index 3679b6f860..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/CompiledTemplate.cs +++ /dev/null @@ -1,145 +0,0 @@ -// -// CompiledTemplate.cs -// -// Author: -// Nathan Baulch <nathan.baulch@gmail.com> -// -// Copyright (c) 2009 Nathan Baulch -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 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 Microsoft.VisualStudio.TextTemplating; -using System.CodeDom.Compiler; -using System.Globalization; -using System.Collections.Generic; - -namespace Mono.TextTemplating -{ - public sealed class CompiledTemplate : MarshalByRefObject, IDisposable - { - ITextTemplatingEngineHost host; - object textTransformation; - readonly CultureInfo culture; - readonly string[] assemblyFiles; - - public CompiledTemplate (ITextTemplatingEngineHost host, CompilerResults results, string fullName, CultureInfo culture, - string[] assemblyFiles) - { - AppDomain.CurrentDomain.AssemblyResolve += ResolveReferencedAssemblies; - this.host = host; - this.culture = culture; - this.assemblyFiles = assemblyFiles; - Load (results, fullName); - } - - void Load (CompilerResults results, string fullName) - { - var assembly = results.CompiledAssembly; - Type transformType = assembly.GetType (fullName); - //MS Templating Engine does not look on the type itself, - //it checks only that required methods are exists in the compiled type - textTransformation = Activator.CreateInstance (transformType); - - //set the host property if it exists - Type hostType = null; - var gen = host as TemplateGenerator; - if (gen != null) { - hostType = gen.SpecificHostType; - } - var hostProp = transformType.GetProperty ("Host", hostType ?? typeof(ITextTemplatingEngineHost)); - if (hostProp != null && hostProp.CanWrite) - hostProp.SetValue (textTransformation, host, null); - - var sessionHost = host as ITextTemplatingSessionHost; - if (sessionHost != null) { - //FIXME: should we create a session if it's null? - var sessionProp = transformType.GetProperty ("Session", typeof (IDictionary<string, object>)); - sessionProp.SetValue (textTransformation, sessionHost.Session, null); - } - } - - public string Process () - { - var ttType = textTransformation.GetType (); - - var errorProp = ttType.GetProperty ("Errors", BindingFlags.Instance | BindingFlags.NonPublic); - if (errorProp == null) - throw new ArgumentException ("Template must have 'Errors' property"); - var errorMethod = ttType.GetMethod ("Error",new Type[]{typeof(string)}); - if (errorMethod == null) { - throw new ArgumentException ("Template must have 'Error(string message)' method"); - } - - var errors = (CompilerErrorCollection) errorProp.GetValue (textTransformation); - errors.Clear (); - - //set the culture - if (culture != null) - ToStringHelper.FormatProvider = culture; - else - ToStringHelper.FormatProvider = CultureInfo.InvariantCulture; - - string output = null; - - var initMethod = ttType.GetMethod ("Initialize"); - var transformMethod = ttType.GetMethod ("TransformText"); - - if (initMethod == null) { - errorMethod.Invoke (textTransformation, new object[]{ "Error running transform: no method Initialize()" }); - } else if (transformMethod == null) { - errorMethod.Invoke (textTransformation, new object[]{ "Error running transform: no method TransformText()" }); - } else try { - initMethod.Invoke (textTransformation, null); - output = (string)transformMethod.Invoke (textTransformation, null); - } catch (Exception ex) { - errorMethod.Invoke (textTransformation, new object[]{ "Error running transform: " + ex }); - } - - host.LogErrors (errors); - - ToStringHelper.FormatProvider = CultureInfo.InvariantCulture; - return output; - } - - Assembly ResolveReferencedAssemblies (object sender, ResolveEventArgs args) - { - AssemblyName asmName = new AssemblyName (args.Name); - foreach (var asmFile in assemblyFiles) { - if (asmName.Name == System.IO.Path.GetFileNameWithoutExtension (asmFile)) - return Assembly.LoadFrom (asmFile); - } - - var path = host.ResolveAssemblyReference (asmName.Name + ".dll"); - if (System.IO.File.Exists (path)) - return Assembly.LoadFrom (path); - - return null; - } - - public void Dispose () - { - if (host != null) { - host = null; - AppDomain.CurrentDomain.AssemblyResolve -= ResolveReferencedAssemblies; - } - } - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/CrossAppDomainAssemblyResolver.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/CrossAppDomainAssemblyResolver.cs deleted file mode 100644 index b15feeba2e..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/CrossAppDomainAssemblyResolver.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// CrossAppDomainAssemblyResolver.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2010 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -namespace Mono.TextTemplating -{ - /// <summary> - /// Provides a handler for AssemblyResolve events that looks them up in the domain that created the resolver. - /// </summary> - [Serializable] - public class CrossAppDomainAssemblyResolver - { - readonly ParentDomainLookup parent = new ParentDomainLookup (); - - public System.Reflection.Assembly Resolve (object sender, ResolveEventArgs args) - { - var location = parent.GetAssemblyPath (args.Name); - if (location != null) - return System.Reflection.Assembly.LoadFrom (location); - return null; - } - - class ParentDomainLookup : MarshalByRefObject - { - public string GetAssemblyPath (string name) - { - var assem = System.Reflection.Assembly.Load (name); - if (assem != null) - return assem.Location; - return null; - } - } - } -} - diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/FileUtil.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/FileUtil.cs deleted file mode 100644 index 62289db3db..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/FileUtil.cs +++ /dev/null @@ -1,132 +0,0 @@ -// -// FileUtil.cs -// -// Author: -// Michael Hutchinson <m.j.hutchinson@gmail.com> -// -// Copyright (c) 2013 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.IO; - -namespace Mono.TextTemplating -{ - static class FileUtil - { - //from MonoDevelop.Core.FileService, copied here so Mono.TextTemplating can be used w/o MD dependency - public unsafe static string AbsoluteToRelativePath (string baseDirectoryPath, string absPath) - { - if (!Path.IsPathRooted (absPath) || string.IsNullOrEmpty (baseDirectoryPath)) - return absPath; - - absPath = GetFullPath (absPath); - baseDirectoryPath = GetFullPath (baseDirectoryPath).TrimEnd (Path.DirectorySeparatorChar); - - fixed (char* bPtr = baseDirectoryPath, aPtr = absPath) { - var bEnd = bPtr + baseDirectoryPath.Length; - var aEnd = aPtr + absPath.Length; - char* lastStartA = aEnd; - char* lastStartB = bEnd; - - int indx = 0; - // search common base path - var a = aPtr; - var b = bPtr; - while (a < aEnd) { - if (*a != *b) - break; - if (IsSeparator (*a)) { - indx++; - lastStartA = a + 1; - lastStartB = b; - } - a++; - b++; - if (b >= bEnd) { - if (a >= aEnd || IsSeparator (*a)) { - indx++; - lastStartA = a + 1; - lastStartB = b; - } - break; - } - } - if (indx == 0) - return absPath; - - if (lastStartA >= aEnd) - return "."; - - // handle case a: some/path b: some/path/deeper... - if (a >= aEnd) { - if (IsSeparator (*b)) { - lastStartA = a + 1; - lastStartB = b; - } - } - - // look how many levels to go up into the base path - int goUpCount = 0; - while (lastStartB < bEnd) { - if (IsSeparator (*lastStartB)) - goUpCount++; - lastStartB++; - } - var size = goUpCount * 2 + goUpCount + aEnd - lastStartA; - var result = new char [size]; - fixed (char* rPtr = result) { - // go paths up - var r = rPtr; - for (int i = 0; i < goUpCount; i++) { - *(r++) = '.'; - *(r++) = '.'; - *(r++) = Path.DirectorySeparatorChar; - } - // copy the remaining absulute path - while (lastStartA < aEnd) - *(r++) = *(lastStartA++); - } - return new string (result); - } - } - - static bool IsSeparator (char ch) - { - return ch == Path.DirectorySeparatorChar || ch == Path.AltDirectorySeparatorChar || ch == Path.VolumeSeparatorChar; - } - - static string GetFullPath (string path) - { - if (path == null) - throw new ArgumentNullException ("path"); - if (!isWindows || path.IndexOf ('*') == -1) - return Path.GetFullPath (path); - else { - // On Windows, GetFullPath doesn't work if the path contains wildcards. - path = path.Replace ("*", wildcardMarker); - path = Path.GetFullPath (path); - return path.Replace (wildcardMarker, "*"); - } - } - - static readonly string wildcardMarker = "_" + Guid.NewGuid () + "_"; - static readonly bool isWindows = Path.DirectorySeparatorChar == '\\'; - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/ParsedTemplate.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/ParsedTemplate.cs deleted file mode 100644 index 1e20c0cf49..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/ParsedTemplate.cs +++ /dev/null @@ -1,337 +0,0 @@ -// -// Template.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.CodeDom.Compiler; -using System.Collections.Generic; -using System.IO; -using Microsoft.VisualStudio.TextTemplating; - -namespace Mono.TextTemplating -{ - public class ParsedTemplate - { - readonly List<ISegment> segments = new List<ISegment> (); - readonly List<ISegment> importedHelperSegments = new List<ISegment> (); - readonly CompilerErrorCollection errors = new CompilerErrorCollection (); - readonly string rootFileName; - - public ParsedTemplate (string rootFileName) - { - this.rootFileName = rootFileName; - } - - public List<ISegment> RawSegments { - get { return segments; } - } - - public IEnumerable<Directive> Directives { - get { - foreach (ISegment seg in segments) { - var dir = seg as Directive; - if (dir != null) - yield return dir; - } - } - } - - public IEnumerable<TemplateSegment> Content { - get { - foreach (ISegment seg in segments) { - var ts = seg as TemplateSegment; - if (ts != null) - yield return ts; - } - } - } - - public CompilerErrorCollection Errors { - get { return errors; } - } - - public static ParsedTemplate FromText (string content, ITextTemplatingEngineHost host) - { - ParsedTemplate template = new ParsedTemplate (host.TemplateFile); - try { - template.Parse (host, new Tokeniser (host.TemplateFile, content)); - } catch (ParserException ex) { - template.LogError (ex.Message, ex.Location); - } - return template; - } - - public void Parse (ITextTemplatingEngineHost host, Tokeniser tokeniser) - { - Parse (host, tokeniser, true); - } - - public void ParseWithoutIncludes (Tokeniser tokeniser) - { - Parse (null, tokeniser, false); - } - - void Parse (ITextTemplatingEngineHost host, Tokeniser tokeniser, bool parseIncludes) - { - Parse (host, tokeniser, parseIncludes, false); - } - - void Parse (ITextTemplatingEngineHost host, Tokeniser tokeniser, bool parseIncludes, bool isImport) - { - bool skip = false; - bool addToImportedHelpers = false; - while ((skip || tokeniser.Advance ()) && tokeniser.State != State.EOF) { - skip = false; - ISegment seg = null; - switch (tokeniser.State) { - case State.Block: - if (!String.IsNullOrEmpty (tokeniser.Value)) - seg = new TemplateSegment (SegmentType.Block, tokeniser.Value, tokeniser.Location); - break; - case State.Content: - if (!String.IsNullOrEmpty (tokeniser.Value)) - seg = new TemplateSegment (SegmentType.Content, tokeniser.Value, tokeniser.Location); - break; - case State.Expression: - if (!String.IsNullOrEmpty (tokeniser.Value)) - seg = new TemplateSegment (SegmentType.Expression, tokeniser.Value, tokeniser.Location); - break; - case State.Helper: - addToImportedHelpers = isImport; - if (!String.IsNullOrEmpty (tokeniser.Value)) - seg = new TemplateSegment (SegmentType.Helper, tokeniser.Value, tokeniser.Location); - break; - case State.Directive: - Directive directive = null; - string attName = null; - while (!skip && tokeniser.Advance ()) { - switch (tokeniser.State) { - case State.DirectiveName: - if (directive == null) { - directive = new Directive (tokeniser.Value, tokeniser.Location); - directive.TagStartLocation = tokeniser.TagStartLocation; - if (!parseIncludes || !string.Equals (directive.Name, "include", StringComparison.OrdinalIgnoreCase)) - segments.Add (directive); - } else - attName = tokeniser.Value; - break; - case State.DirectiveValue: - if (attName != null && directive != null) - directive.Attributes[attName] = tokeniser.Value; - else - LogError ("Directive value without name", tokeniser.Location); - attName = null; - break; - case State.Directive: - if (directive != null) - directive.EndLocation = tokeniser.TagEndLocation; - break; - default: - skip = true; - break; - } - } - if (parseIncludes && directive != null && string.Equals (directive.Name, "include", StringComparison.OrdinalIgnoreCase)) - Import (host, directive, Path.GetDirectoryName (tokeniser.Location.FileName)); - break; - default: - throw new InvalidOperationException (); - } - if (seg != null) { - seg.TagStartLocation = tokeniser.TagStartLocation; - seg.EndLocation = tokeniser.TagEndLocation; - if (addToImportedHelpers) - importedHelperSegments.Add (seg); - else - segments.Add (seg); - } - } - if (!isImport) - AppendAnyImportedHelperSegments (); - } - - void Import (ITextTemplatingEngineHost host, Directive includeDirective, string relativeToDirectory) - { - string fileName; - if (includeDirective.Attributes.Count > 1 || !includeDirective.Attributes.TryGetValue ("file", out fileName)) { - LogError ("Unexpected attributes in include directive", includeDirective.StartLocation); - return; - } - - //try to resolve path relative to the file that included it - if (relativeToDirectory != null && !Path.IsPathRooted (fileName)) { - string possible = Path.Combine (relativeToDirectory, fileName); - if (File.Exists (possible)) - fileName = Path.GetFullPath (possible); - } - - string content, resolvedName; - if (host.LoadIncludeText (fileName, out content, out resolvedName)) - Parse (host, new Tokeniser (resolvedName, content), true, true); - else - LogError ("Could not resolve include file '" + fileName + "'.", includeDirective.StartLocation); - } - - void AppendAnyImportedHelperSegments () - { - segments.AddRange (importedHelperSegments); - importedHelperSegments.Clear (); - } - - void LogError (string message, Location location, bool isWarning) - { - var err = new CompilerError (); - err.ErrorText = message; - if (location.FileName != null) { - err.Line = location.Line; - err.Column = location.Column; - err.FileName = location.FileName ?? string.Empty; - } else { - err.FileName = rootFileName ?? string.Empty; - } - err.IsWarning = isWarning; - errors.Add (err); - } - - public void LogError (string message) - { - LogError (message, Location.Empty, false); - } - - public void LogWarning (string message) - { - LogError (message, Location.Empty, true); - } - - public void LogError (string message, Location location) - { - LogError (message, location, false); - } - - public void LogWarning (string message, Location location) - { - LogError (message, location, true); - } - } - - public interface ISegment - { - Location StartLocation { get; } - Location EndLocation { get; set; } - Location TagStartLocation {get; set; } - } - - public class TemplateSegment : ISegment - { - public TemplateSegment (SegmentType type, string text, Location start) - { - this.Type = type; - this.StartLocation = start; - this.Text = text; - } - - public SegmentType Type { get; private set; } - public string Text { get; private set; } - public Location TagStartLocation { get; set; } - public Location StartLocation { get; private set; } - public Location EndLocation { get; set; } - } - - public class Directive : ISegment - { - public Directive (string name, Location start) - { - this.Name = name; - this.Attributes = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase); - this.StartLocation = start; - } - - public string Name { get; private set; } - public Dictionary<string,string> Attributes { get; private set; } - public Location TagStartLocation { get; set; } - public Location StartLocation { get; private set; } - public Location EndLocation { get; set; } - - public string Extract (string key) - { - string value; - if (!Attributes.TryGetValue (key, out value)) - return null; - Attributes.Remove (key); - return value; - } - } - - public enum SegmentType - { - Block, - Expression, - Content, - Helper - } - - public struct Location : IEquatable<Location> - { - public Location (string fileName, int line, int column) : this() - { - FileName = fileName; - Column = column; - Line = line; - } - - public int Line { get; private set; } - public int Column { get; private set; } - public string FileName { get; private set; } - - public static Location Empty { - get { return new Location (null, -1, -1); } - } - - public Location AddLine () - { - return new Location (FileName, Line + 1, 1); - } - - public Location AddCol () - { - return AddCols (1); - } - - public Location AddCols (int number) - { - return new Location (this.FileName, this.Line, this.Column + number); - } - - public override string ToString () - { - return string.Format("[{0} ({1},{2})]", FileName, Line, Column); - } - - public bool Equals (Location other) - { - return other.Line == Line && other.Column == Column && other.FileName == FileName; - } - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/RecyclableAppDomain.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/RecyclableAppDomain.cs deleted file mode 100644 index 0de9c52226..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/RecyclableAppDomain.cs +++ /dev/null @@ -1,215 +0,0 @@ -//
-// RecyclableAppDomain.cs
-//
-// Author:
-// Michael Hutchinson <mhutch@xamarin.com>
-//
-// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
-// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com_
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-using System.Collections.Generic;
-
-namespace Mono.TextTemplating
-{
- public class TemplatingAppDomainRecycler
- {
- const int DEFAULT_TIMEOUT_MS = 2 * 60 * 1000;
- const int DEFAULT_MAX_USES = 20;
-
- readonly string name; - readonly object lockObj = new object (); -
- RecyclableAppDomain domain;
-
- public TemplatingAppDomainRecycler (string name)
- {
- this.name = name;
- }
-
- public TemplatingAppDomainRecycler.Handle GetHandle ()
- {
- lock (lockObj) {
- if (domain == null || domain.Domain == null || domain.UnusedHandles == 0) {
- domain = new RecyclableAppDomain (name);
- }
- return domain.GetHandle ();
- }
- }
-
- internal class RecyclableAppDomain
- {
- //TODO: implement timeout based recycling
- //DateTime lastUsed;
-
- AppDomain domain;
- DomainAssemblyLoader assemblyMap;
-
- int liveHandles; - int unusedHandles = DEFAULT_MAX_USES;
-
- public RecyclableAppDomain (string name)
- {
- var info = new AppDomainSetup () {
- //appbase needs to allow loading this assembly, for remoting
- ApplicationBase = System.IO.Path.GetDirectoryName (typeof (TemplatingAppDomainRecycler).Assembly.Location),
- DisallowBindingRedirects = false,
- DisallowCodeDownload = true,
- DisallowApplicationBaseProbing = false,
- ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile,
- };
- domain = AppDomain.CreateDomain (name, null, info);
- var t = typeof(DomainAssemblyLoader);
- AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
- assemblyMap = (DomainAssemblyLoader) domain.CreateInstanceFromAndUnwrap(t.Assembly.Location, t.FullName);
- AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
- domain.AssemblyResolve += assemblyMap.Resolve;// new DomainAssemblyLoader(assemblyMap).Resolve;
- }
-
- System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
- {
- var a = typeof(RecyclableAppDomain).Assembly;
- if (args.Name == a.FullName)
- return a;
- return null;
- }
-
- public int UnusedHandles { get { return unusedHandles; } }
- public int LiveHandles { get { return liveHandles; } }
- public AppDomain Domain { get { return domain; } }
-
- public void AddAssembly (System.Reflection.Assembly assembly)
- {
- assemblyMap.Add (assembly.FullName, assembly.Location);
- }
-
- public Handle GetHandle ()
- {
- lock (this) {
- if (unusedHandles <= 0) {
- throw new InvalidOperationException ("No handles left");
- }
- unusedHandles--;
- liveHandles++;
- }
- return new Handle (this);
- }
-
- public void ReleaseHandle ()
- {
- int lh;
- lock (this) {
- liveHandles--;
- lh = liveHandles;
- }
- //We must unload domain every time after using it for generation
- //Otherwise we could not load new version of the project-generated
- //assemblies into it. So remove checking for unusedHandles == 0
- if (lh == 0) {
- UnloadDomain ();
- }
- }
-
- void UnloadDomain ()
- {
- AppDomain.Unload (domain);
- domain = null;
- assemblyMap = null;
- GC.SuppressFinalize (this);
- }
-
- ~RecyclableAppDomain ()
- {
- if (liveHandles != 0)
- Console.WriteLine ("WARNING: recyclable AppDomain's handles were not all disposed");
- }
- }
-
- public class Handle : IDisposable
- {
- RecyclableAppDomain parent;
-
- internal Handle (RecyclableAppDomain parent)
- {
- this.parent = parent;
- }
-
- public AppDomain Domain {
- get { return parent.Domain; }
- }
-
- public void Dispose ()
- {
- if (parent == null)
- return;
- var p = parent;
- lock (this) {
- if (parent == null)
- return;
- parent = null;
- }
- p.ReleaseHandle ();
- }
-
- public void AddAssembly (System.Reflection.Assembly assembly)
- {
- parent.AddAssembly (assembly);
- }
- }
-
- [Serializable]
- class DomainAssemblyLoader : MarshalByRefObject
- {
- readonly Dictionary<string, string> map = new Dictionary<string, string>(); -
- public DomainAssemblyLoader ()
- {
- }
-
- public System.Reflection.Assembly Resolve (object sender, ResolveEventArgs args)
- {
- var assemblyFile = ResolveAssembly (args.Name);
- if (assemblyFile != null)
- return System.Reflection.Assembly.LoadFrom (assemblyFile);
- return null;
- }
-
- public string ResolveAssembly(string name)
- {
- string result;
- if (map.TryGetValue(name, out result))
- return result;
- return null;
- }
-
- public void Add(string name, string location)
- {
- map[name] = location;
- }
-
- //keep this alive as long as the app domain is alive
- public override object InitializeLifetimeService ()
- {
- return null;
- }
- }
- }
-}
\ No newline at end of file diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplateGenerator.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplateGenerator.cs deleted file mode 100644 index f4899d6068..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplateGenerator.cs +++ /dev/null @@ -1,466 +0,0 @@ -// -// TemplatingHost.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.CodeDom.Compiler; -using System.IO; -using System.Reflection; -using System.Text; -using Microsoft.VisualStudio.TextTemplating; - -namespace Mono.TextTemplating -{ - public class TemplateGenerator : MarshalByRefObject, ITextTemplatingEngineHost - { - //re-usable - TemplatingEngine engine; - - //per-run variables - string inputFile, outputFile; - Encoding encoding; - - //host fields - readonly CompilerErrorCollection errors = new CompilerErrorCollection (); - readonly List<string> refs = new List<string> (); - readonly List<string> imports = new List<string> (); - readonly List<string> includePaths = new List<string> (); - readonly List<string> referencePaths = new List<string> (); - - //host properties for consumers to access - public CompilerErrorCollection Errors { get { return errors; } } - public List<string> Refs { get { return refs; } } - public List<string> Imports { get { return imports; } } - public List<string> IncludePaths { get { return includePaths; } } - public List<string> ReferencePaths { get { return referencePaths; } } - public string OutputFile { get { return outputFile; } } - public bool UseRelativeLinePragmas { get; set; } - - public TemplateGenerator () - { - Refs.Add (typeof (TextTransformation).Assembly.Location); - Refs.Add (typeof(Uri).Assembly.Location); - Imports.Add ("System"); - } - - public CompiledTemplate CompileTemplate (string content) - { - if (String.IsNullOrEmpty (content)) - throw new ArgumentNullException ("content"); - - errors.Clear (); - encoding = Encoding.UTF8; - - return Engine.CompileTemplate (content, this); - } - - protected TemplatingEngine Engine { - get { - if (engine == null) - engine = new TemplatingEngine (); - return engine; - } - } - - public bool ProcessTemplate (string inputFile, string outputFile) - { - if (String.IsNullOrEmpty (inputFile)) - throw new ArgumentNullException ("inputFile"); - if (String.IsNullOrEmpty (outputFile)) - throw new ArgumentNullException ("outputFile"); - - string content; - try { - content = File.ReadAllText (inputFile); - } catch (IOException ex) { - errors.Clear (); - AddError ("Could not read input file '" + inputFile + "':\n" + ex); - return false; - } - - string output; - ProcessTemplate (inputFile, content, ref outputFile, out output); - - try { - if (!errors.HasErrors) - File.WriteAllText (outputFile, output, encoding); - } catch (IOException ex) { - AddError ("Could not write output file '" + outputFile + "':\n" + ex); - } - - return !errors.HasErrors; - } - - public bool ProcessTemplate (string inputFileName, string inputContent, ref string outputFileName, out string outputContent) - { - errors.Clear (); - encoding = Encoding.UTF8; - - outputFile = outputFileName; - inputFile = inputFileName; - outputContent = Engine.ProcessTemplate (inputContent, this); - outputFileName = outputFile; - - return !errors.HasErrors; - } - - public bool PreprocessTemplate (string inputFile, string className, string classNamespace, - string outputFile, Encoding encoding, out string language, out string[] references) - { - language = null; - references = null; - - if (string.IsNullOrEmpty (inputFile)) - throw new ArgumentNullException ("inputFile"); - if (string.IsNullOrEmpty (outputFile)) - throw new ArgumentNullException ("outputFile"); - - string content; - try { - content = File.ReadAllText (inputFile); - } catch (IOException ex) { - errors.Clear (); - AddError ("Could not read input file '" + inputFile + "':\n" + ex); - return false; - } - - string output; - PreprocessTemplate (inputFile, className, classNamespace, content, out language, out references, out output); - - try { - if (!errors.HasErrors) - File.WriteAllText (outputFile, output, encoding); - } catch (IOException ex) { - AddError ("Could not write output file '" + outputFile + "':\n" + ex); - } - - return !errors.HasErrors; - } - - public bool PreprocessTemplate (string inputFileName, string className, string classNamespace, string inputContent, - out string language, out string[] references, out string outputContent) - { - errors.Clear (); - encoding = Encoding.UTF8; - - inputFile = inputFileName; - outputContent = Engine.PreprocessTemplate (inputContent, this, className, classNamespace, out language, out references); - - return !errors.HasErrors; - } - - CompilerError AddError (string error) - { - var err = new CompilerError (); - err.ErrorText = error; - Errors.Add (err); - return err; - } - - #region Virtual members - - public virtual object GetHostOption (string optionName) - { - switch (optionName) { - case "UseRelativeLinePragmas": - return UseRelativeLinePragmas; - } - return null; - } - - public virtual AppDomain ProvideTemplatingAppDomain (string content) - { - return null; - } - - protected virtual string ResolveAssemblyReference (string assemblyReference) - { - if (System.IO.Path.IsPathRooted (assemblyReference)) - return assemblyReference; - foreach (string referencePath in ReferencePaths) { - var path = System.IO.Path.Combine (referencePath, assemblyReference); - if (System.IO.File.Exists (path)) - return path; - } -
- var assemblyName = new AssemblyName(assemblyReference); - if (assemblyName.Version != null)//Load via GAC and return full path - return Assembly.Load (assemblyName).Location; - - if (!assemblyReference.EndsWith (".dll", StringComparison.OrdinalIgnoreCase) && !assemblyReference.EndsWith (".exe", StringComparison.OrdinalIgnoreCase))
- return assemblyReference + ".dll"; - return assemblyReference; - } - - protected virtual string ResolveParameterValue (string directiveId, string processorName, string parameterName) - { - var key = new ParameterKey (processorName, directiveId, parameterName); - string value; - if (parameters.TryGetValue (key, out value)) - return value; - if (processorName != null || directiveId != null) - return ResolveParameterValue (null, null, parameterName); - return null; - } - - protected virtual Type ResolveDirectiveProcessor (string processorName) - { - KeyValuePair<string,string> value; - if (!directiveProcessors.TryGetValue (processorName, out value)) - throw new Exception (string.Format ("No directive processor registered as '{0}'", processorName)); - var asmPath = ResolveAssemblyReference (value.Value); - if (asmPath == null) - throw new Exception (string.Format ("Could not resolve assembly '{0}' for directive processor '{1}'", value.Value, processorName)); - var asm = Assembly.LoadFrom (asmPath); - return asm.GetType (value.Key, true); - } - - protected virtual string ResolvePath (string path) - { - path = Environment.ExpandEnvironmentVariables (path); - if (Path.IsPathRooted (path)) - return path; - var dir = Path.GetDirectoryName (inputFile); - var test = Path.Combine (dir, path); - if (File.Exists (test) || Directory.Exists (test)) - return test; - return path; - } - - #endregion - - readonly Dictionary<ParameterKey,string> parameters = new Dictionary<ParameterKey, string> (); - readonly Dictionary<string,KeyValuePair<string,string>> directiveProcessors = new Dictionary<string, KeyValuePair<string,string>> (); - - public void AddDirectiveProcessor (string name, string klass, string assembly) - { - directiveProcessors.Add (name, new KeyValuePair<string,string> (klass,assembly)); - } - - public void AddParameter (string processorName, string directiveName, string parameterName, string value) - { - parameters.Add (new ParameterKey (processorName, directiveName, parameterName), value); - } - - /// <summary> - /// Parses a parameter and adds it. - /// </summary> - /// <returns>Whether the parameter was parsed successfully.</returns> - /// <param name="unparsedParameter">Parameter in name=value or processor!directive!name!value format.</param> - public bool TryAddParameter (string unparsedParameter) - { - string processor, directive, name, value; - if (TryParseParameter (unparsedParameter, out processor, out directive, out name, out value)) { - AddParameter (processor, directive, name, value); - return true; - } - return false; - } - - internal static bool TryParseParameter (string parameter, out string processor, out string directive, out string name, out string value) - { - processor = directive = name = value = ""; - - int start = 0; - int end = parameter.IndexOfAny (new [] { '=', '!' }); - if (end < 0) - return false; - - //simple format n=v - if (parameter [end] == '=') { - name = parameter.Substring (start, end); - value = parameter.Substring (end + 1); - return !string.IsNullOrEmpty (name); - } - - //official format, p!d!n!v - processor = parameter.Substring (start, end); - - start = end + 1; - end = parameter.IndexOf ('!', start); - if (end < 0) { - //unlike official version, we allow you to omit processor/directive - name = processor; - value = parameter.Substring (start); - processor = ""; - return !string.IsNullOrEmpty (name); - } - - directive = parameter.Substring (start, end - start); - - - start = end + 1; - end = parameter.IndexOf ('!', start); - if (end < 0) { - //we also allow you just omit the processor - name = directive; - directive = processor; - value = parameter.Substring (start); - processor = ""; - return !string.IsNullOrEmpty (name); - } - - name = parameter.Substring (start, end - start); - value = parameter.Substring (end + 1); - - return !string.IsNullOrEmpty (name); - } - - protected virtual bool LoadIncludeText (string requestFileName, out string content, out string location) - { - content = ""; - location = ResolvePath (requestFileName); - - if (location == null || !File.Exists (location)) { - foreach (string path in includePaths) { - string f = Path.Combine (path, requestFileName); - if (File.Exists (f)) { - location = f; - break; - } - } - } - - if (location == null) - return false; - - try { - content = File.ReadAllText (location); - return true; - } catch (IOException ex) { - AddError ("Could not read included file '" + location + "':\n" + ex); - } - return false; - } - - #region Explicit ITextTemplatingEngineHost implementation - - bool ITextTemplatingEngineHost.LoadIncludeText (string requestFileName, out string content, out string location) - { - return LoadIncludeText (requestFileName, out content, out location); - } - - void ITextTemplatingEngineHost.LogErrors (CompilerErrorCollection errors) - { - this.errors.AddRange (errors); - } - - string ITextTemplatingEngineHost.ResolveAssemblyReference (string assemblyReference) - { - return ResolveAssemblyReference (assemblyReference); - } - - string ITextTemplatingEngineHost.ResolveParameterValue (string directiveId, string processorName, string parameterName) - { - return ResolveParameterValue (directiveId, processorName, parameterName); - } - - Type ITextTemplatingEngineHost.ResolveDirectiveProcessor (string processorName) - { - return ResolveDirectiveProcessor (processorName); - } - - string ITextTemplatingEngineHost.ResolvePath (string path) - { - return ResolvePath (path); - } - - void ITextTemplatingEngineHost.SetFileExtension (string extension) - { - extension = extension.TrimStart ('.'); - if (Path.HasExtension (outputFile)) { - outputFile = Path.ChangeExtension (outputFile, extension); - } else { - outputFile = outputFile + "." + extension; - } - } - - void ITextTemplatingEngineHost.SetOutputEncoding (Encoding encoding, bool fromOutputDirective) - { - this.encoding = encoding; - } - - IList<string> ITextTemplatingEngineHost.StandardAssemblyReferences { - get { return refs; } - } - - IList<string> ITextTemplatingEngineHost.StandardImports { - get { return imports; } - } - - string ITextTemplatingEngineHost.TemplateFile { - get { return inputFile; } - } - - #endregion - - struct ParameterKey : IEquatable<ParameterKey> - { - public ParameterKey (string processorName, string directiveName, string parameterName) - { - this.processorName = processorName ?? ""; - this.directiveName = directiveName ?? ""; - this.parameterName = parameterName ?? ""; - unchecked { - hashCode = this.processorName.GetHashCode () - ^ this.directiveName.GetHashCode () - ^ this.parameterName.GetHashCode (); - } - } - - string processorName, directiveName, parameterName; - readonly int hashCode; - - public override bool Equals (object obj) - { - return obj is ParameterKey && Equals ((ParameterKey)obj); - } - - public bool Equals (ParameterKey other) - { - return processorName == other.processorName && directiveName == other.directiveName && parameterName == other.parameterName; - } - - public override int GetHashCode () - { - return hashCode; - } - } - - /// <summary> - /// If non-null, the template's Host property will be the full type of this host. - /// </summary> - public virtual Type SpecificHostType { get { return null; } } - - /// <summary> - /// Gets any additional directive processors to be included in the processing run. - /// </summary> - public virtual IEnumerable<IDirectiveProcessor> GetAdditionalDirectiveProcessors () - { - yield break; - } - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplateSettings.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplateSettings.cs deleted file mode 100644 index 627dc76f47..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplateSettings.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -// TemplateSettings.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Text; -using System.Collections.Generic; -using Microsoft.VisualStudio.TextTemplating; - -namespace Mono.TextTemplating -{ - public class TemplateSettings - { - public TemplateSettings () - { - Imports = new HashSet<string> (); - Assemblies = new HashSet<string> (); - CustomDirectives = new List<CustomDirective> (); - DirectiveProcessors = new Dictionary<string, IDirectiveProcessor> (); - } - - public bool HostSpecific { get; set; } - public bool HostPropertyOnBase { get; set; } - public bool Debug { get; set; } - public string Inherits { get; set; } - public string Name { get; set; } - public string Namespace { get; set; } - public HashSet<string> Imports { get; private set; } - public HashSet<string> Assemblies { get; private set; } - public System.CodeDom.Compiler.CodeDomProvider Provider { get; set; } - public string Language { get; set; } - public string CompilerOptions { get; set; } - public Encoding Encoding { get; set; } - public string Extension { get; set; } - public System.Globalization.CultureInfo Culture { get; set; } - public List<CustomDirective> CustomDirectives { get; private set; } - public Dictionary<string,IDirectiveProcessor> DirectiveProcessors { get; private set; } - public bool IncludePreprocessingHelpers { get; set; } - public bool IsPreprocessed { get; set; } - public bool RelativeLinePragmas { get; set; } - public bool NoLinePragmas { get; set; } - public bool InternalVisibility { get; set; } - public Type HostType { get; set; } - } - - public class CustomDirective - { - public CustomDirective (string processorName, Directive directive) - { - this.ProcessorName = processorName; - this.Directive = directive; - } - - public string ProcessorName { get; set; } - public Directive Directive { get; set; } - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplatingEngine.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplatingEngine.cs deleted file mode 100644 index 7720093b36..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplatingEngine.cs +++ /dev/null @@ -1,1169 +0,0 @@ -// -// Engine.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.IO; -using System.Text; -using System.Collections.Generic; -using System.CodeDom; -using System.CodeDom.Compiler; -using Microsoft.CSharp; -using Microsoft.VisualStudio.TextTemplating; -using System.Linq; -using System.Reflection; - -namespace Mono.TextTemplating -{ - public class TemplatingEngine : MarshalByRefObject, ITextTemplatingEngine - { - public string ProcessTemplate (string content, ITextTemplatingEngineHost host) - { - var tpl = CompileTemplate (content, host); - try { - if (tpl != null) - return tpl.Process (); - return null; - } finally { - if (tpl != null) - tpl.Dispose (); - } - } - - public string PreprocessTemplate (string content, ITextTemplatingEngineHost host, string className, - string classNamespace, out string language, out string[] references) - { - if (content == null) - throw new ArgumentNullException ("content"); - if (host == null) - throw new ArgumentNullException ("host"); - if (className == null) - throw new ArgumentNullException ("className"); - if (classNamespace == null) - throw new ArgumentNullException ("classNamespace"); - - language = null; - references = null; - - var pt = ParsedTemplate.FromText (content, host); - if (pt.Errors.HasErrors) { - host.LogErrors (pt.Errors); - return null; - } - - var settings = GetSettings (host, pt); - if (pt.Errors.HasErrors) { - host.LogErrors (pt.Errors); - return null; - } - settings.Name = className; - settings.Namespace = classNamespace; - settings.IncludePreprocessingHelpers = string.IsNullOrEmpty (settings.Inherits); - settings.IsPreprocessed = true; - language = settings.Language; - - var ccu = GenerateCompileUnit (host, content, pt, settings); - references = ProcessReferences (host, pt, settings).ToArray (); - - host.LogErrors (pt.Errors); - if (pt.Errors.HasErrors) { - return null; - } - - var options = new CodeGeneratorOptions (); - using (var sw = new StringWriter ()) { - settings.Provider.GenerateCodeFromCompileUnit (ccu, sw, options); - return sw.ToString (); - } - } - - public CompiledTemplate CompileTemplate (string content, ITextTemplatingEngineHost host) - { - if (content == null) - throw new ArgumentNullException ("content"); - if (host == null) - throw new ArgumentNullException ("host"); - - var pt = ParsedTemplate.FromText (content, host); - if (pt.Errors.HasErrors) { - host.LogErrors (pt.Errors); - return null; - } - - var settings = GetSettings (host, pt); - if (pt.Errors.HasErrors) { - host.LogErrors (pt.Errors); - return null; - } - - if (!string.IsNullOrEmpty (settings.Extension)) { - host.SetFileExtension (settings.Extension); - } - if (settings.Encoding != null) { - //FIXME: when is this called with false? - host.SetOutputEncoding (settings.Encoding, true); - } - - var ccu = GenerateCompileUnit (host, content, pt, settings); - var references = ProcessReferences (host, pt, settings); - if (pt.Errors.HasErrors) { - host.LogErrors (pt.Errors); - return null; - } - - var results = GenerateCode (references, settings, ccu); - if (results.Errors.HasErrors) { - host.LogErrors (pt.Errors); - host.LogErrors (results.Errors); - return null; - } - - var templateClassFullName = settings.Namespace + "." + settings.Name; - var domain = host.ProvideTemplatingAppDomain (content); - if (domain != null) { - var type = typeof(CompiledTemplate); - var obj = domain.CreateInstanceFromAndUnwrap (type.Assembly.Location, type.FullName, false, - BindingFlags.Default, null, - new object[] { host, results, templateClassFullName, settings.Culture, references.ToArray () }, - null, null); - return (CompiledTemplate)obj; - } - return new CompiledTemplate (host, results, templateClassFullName, settings.Culture, references.ToArray ()); - } - - static CompilerResults GenerateCode (IEnumerable<string> references, TemplateSettings settings, CodeCompileUnit ccu) - { - var pars = new CompilerParameters { - GenerateExecutable = false, - CompilerOptions = settings.CompilerOptions, - IncludeDebugInformation = settings.Debug, - GenerateInMemory = false, - }; - - foreach (var r in references) - pars.ReferencedAssemblies.Add (r); - - if (settings.Debug) - pars.TempFiles.KeepFiles = true; - if (string.IsNullOrWhiteSpace (pars.CompilerOptions)) - pars.CompilerOptions = "/noconfig"; - else if (!pars.CompilerOptions.Contains ("/noconfig")) - pars.CompilerOptions = "/noconfig " + pars.CompilerOptions; - return settings.Provider.CompileAssemblyFromDom (pars, ccu); - } - - static string [] ProcessReferences (ITextTemplatingEngineHost host, ParsedTemplate pt, TemplateSettings settings) - { - var resolved = new Dictionary<string, string> (); - - foreach (string assem in settings.Assemblies.Union (host.StandardAssemblyReferences)) { - if (resolved.Values.Contains (assem)) - continue; - - string resolvedAssem = host.ResolveAssemblyReference (assem); - if (!string.IsNullOrEmpty (resolvedAssem)) { - var assemblyName = resolvedAssem; - if (File.Exists (resolvedAssem)) - assemblyName = AssemblyName.GetAssemblyName (resolvedAssem).FullName; - resolved [assemblyName] = resolvedAssem; - } else { - pt.LogError ("Could not resolve assembly reference '" + assem + "'"); - return null; - } - } - return resolved.Values.ToArray (); - } - - public static TemplateSettings GetSettings (ITextTemplatingEngineHost host, ParsedTemplate pt) - { - var settings = new TemplateSettings (); - - bool relativeLinePragmas = host.GetHostOption ("UseRelativeLinePragmas") as bool? ?? false; - - foreach (Directive dt in pt.Directives) { - switch (dt.Name.ToLowerInvariant ()) { - case "template": - string val = dt.Extract ("language"); - if (val != null) - settings.Language = val; - val = dt.Extract ("debug"); - if (val != null) - settings.Debug = string.Compare (val, "true", StringComparison.OrdinalIgnoreCase) == 0; - val = dt.Extract ("inherits"); - if (val != null) - settings.Inherits = val; - val = dt.Extract ("culture"); - if (val != null) { - System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.GetCultureInfo (val); - if (culture == null) - pt.LogWarning ("Could not find culture '" + val + "'", dt.StartLocation); - else - settings.Culture = culture; - } - val = dt.Extract ("hostspecific"); - if (val != null) { - if (string.Compare (val, "trueFromBase", StringComparison.OrdinalIgnoreCase) == 0) { - settings.HostPropertyOnBase = true; - settings.HostSpecific = true; - } else { - settings.HostSpecific = string.Compare (val, "true", StringComparison.OrdinalIgnoreCase) == 0; - } - } - val = dt.Extract ("CompilerOptions"); - if (val != null) { - settings.CompilerOptions = val; - } - val = dt.Extract ("relativeLinePragmas"); - if (val != null) { - relativeLinePragmas = string.Compare (val, "true", StringComparison.OrdinalIgnoreCase) == 0; - } - val = dt.Extract ("linePragmas"); - if (val != null) { - settings.NoLinePragmas = string.Compare (val, "false", StringComparison.OrdinalIgnoreCase) == 0; - } - val = dt.Extract ("visibility"); - if (val != null) { - settings.InternalVisibility = string.Compare (val, "internal", StringComparison.OrdinalIgnoreCase) == 0; - } - break; - - case "assembly": - string name = dt.Extract ("name"); - if (name == null) - pt.LogError ("Missing name attribute in assembly directive", dt.StartLocation); - else - settings.Assemblies.Add (name); - break; - - case "import": - string namespac = dt.Extract ("namespace"); - if (namespac == null) - pt.LogError ("Missing namespace attribute in import directive", dt.StartLocation); - else - settings.Imports.Add (namespac); - break; - - case "output": - settings.Extension = dt.Extract ("extension"); - string encoding = dt.Extract ("encoding"); - if (encoding != null) - settings.Encoding = Encoding.GetEncoding (encoding); - break; - - case "include": - throw new InvalidOperationException ("Include is handled in the parser"); - - case "parameter": - AddDirective (settings, host, "ParameterDirectiveProcessor", dt); - continue; - - default: - string processorName = dt.Extract ("Processor"); - if (processorName == null) - throw new InvalidOperationException ("Custom directive '" + dt.Name + "' does not specify a processor"); - - AddDirective (settings, host, processorName, dt); - continue; - } - ComplainExcessAttributes (dt, pt); - } - - var gen = host as TemplateGenerator; - if (gen != null) { - settings.HostType = gen.SpecificHostType; - if (settings.HostType != null) { - settings.Assemblies.Add (settings.HostType.Assembly.Location); - } else { - settings.HostType = typeof(ITextTemplatingEngineHost); - } - foreach (var processor in gen.GetAdditionalDirectiveProcessors ()) { - settings.DirectiveProcessors [processor.GetType ().FullName] = processor; - } - } - - //initialize the custom processors - foreach (var kv in settings.DirectiveProcessors) { - kv.Value.Initialize (host); - - IRecognizeHostSpecific hs; - if (settings.HostSpecific || ( - !((IDirectiveProcessor)kv.Value).RequiresProcessingRunIsHostSpecific && - ((hs = kv.Value as IRecognizeHostSpecific) == null || !hs.RequiresProcessingRunIsHostSpecific))) - continue; - - settings.HostSpecific = true; - pt.LogWarning ("Directive processor '" + kv.Key + "' requires hostspecific=true, forcing on."); - } - - foreach (var kv in settings.DirectiveProcessors) { - ((IDirectiveProcessor)kv.Value).SetProcessingRunIsHostSpecific (settings.HostSpecific); - var hs = kv.Value as IRecognizeHostSpecific; - if (hs != null) - hs.SetProcessingRunIsHostSpecific (settings.HostSpecific); - } - - if (settings.Name == null) - settings.Name = string.Format ("GeneratedTextTransformation{0:x}", new Random ().Next ()); - if (settings.Namespace == null) - settings.Namespace = typeof (TextTransformation).Namespace; - - //resolve the CodeDOM provider - if (String.IsNullOrEmpty (settings.Language)) { - settings.Language = "C#"; - } - - if (settings.Language == "C#v3.5") { - var providerOptions = new Dictionary<string, string> (); - providerOptions.Add ("CompilerVersion", "v3.5"); - settings.Provider = new CSharpCodeProvider (providerOptions); - } - else { - settings.Provider = CodeDomProvider.CreateProvider (settings.Language); - } - - if (settings.Provider == null) { - pt.LogError ("A provider could not be found for the language '" + settings.Language + "'"); - return settings; - } - - settings.RelativeLinePragmas = relativeLinePragmas; - - return settings; - } - - public static string IndentSnippetText (CodeDomProvider provider, string text, string indent) - { - if (provider is CSharpCodeProvider) - return IndentSnippetText (text, indent); - return text; - } - - public static string IndentSnippetText (string text, string indent) - { - var builder = new StringBuilder (text.Length); - builder.Append (indent); - int lastNewline = 0; - for (int i = 0; i < text.Length - 1; i++) { - char c = text[i]; - if (c == '\r') { - if (text[i + 1] == '\n') { - i++; - if (i == text.Length - 1) - break; - } - } else if (c != '\n') { - continue; - } - i++; - int len = i - lastNewline; - if (len > 0) { - builder.Append (text, lastNewline, i - lastNewline); - } - builder.Append (indent); - lastNewline = i; - } - if (lastNewline > 0) - builder.Append (text, lastNewline, text.Length - lastNewline); - else - builder.Append (text); - return builder.ToString (); - } - - static void AddDirective (TemplateSettings settings, ITextTemplatingEngineHost host, string processorName, Directive directive) - { - IDirectiveProcessor processor; - if (!settings.DirectiveProcessors.TryGetValue (processorName, out processor)) { - switch (processorName) { - case "ParameterDirectiveProcessor": - processor = new ParameterDirectiveProcessor (); - break; - default: - Type processorType = host.ResolveDirectiveProcessor (processorName); - processor = (IDirectiveProcessor) Activator.CreateInstance (processorType); - break; - } - if (!processor.IsDirectiveSupported (directive.Name)) - throw new InvalidOperationException ("Directive processor '" + processorName + "' does not support directive '" + directive.Name + "'"); - - settings.DirectiveProcessors [processorName] = processor; - } - settings.CustomDirectives.Add (new CustomDirective (processorName, directive)); - } - - static bool ComplainExcessAttributes (Directive dt, ParsedTemplate pt) - { - if (dt.Attributes.Count == 0) - return false; - var sb = new StringBuilder ("Unknown attributes "); - bool first = true; - foreach (string key in dt.Attributes.Keys) { - if (!first) { - sb.Append (", "); - } else { - first = false; - } - sb.Append (key); - } - sb.Append (" found in "); - sb.Append (dt.Name); - sb.Append (" directive."); - pt.LogWarning (sb.ToString (), dt.StartLocation); - return false; - } - - static void ProcessDirectives (string content, ParsedTemplate pt, TemplateSettings settings) - { - foreach (var processor in settings.DirectiveProcessors.Values) { - processor.StartProcessingRun (settings.Provider, content, pt.Errors); - } - - foreach (var dt in settings.CustomDirectives) { - var processor = settings.DirectiveProcessors[dt.ProcessorName]; - processor.ProcessDirective (dt.Directive.Name, dt.Directive.Attributes); - } - - foreach (var processor in settings.DirectiveProcessors.Values) { - processor.FinishProcessingRun (); - - var imports = processor.GetImportsForProcessingRun (); - if (imports != null) - settings.Imports.UnionWith (imports); - var references = processor.GetReferencesForProcessingRun (); - if (references != null) - settings.Assemblies.UnionWith (references); - } - } - - public static CodeCompileUnit GenerateCompileUnit (ITextTemplatingEngineHost host, string content, ParsedTemplate pt, TemplateSettings settings) - { - ProcessDirectives (content, pt, settings); - - string baseDirectory = Path.GetDirectoryName (host.TemplateFile); - - //prep the compile unit - var ccu = new CodeCompileUnit (); - var namespac = new CodeNamespace (settings.Namespace); - ccu.Namespaces.Add (namespac); - - foreach (string ns in settings.Imports.Union (host.StandardImports)) - namespac.Imports.Add (new CodeNamespaceImport (ns)); - - //prep the type - var type = new CodeTypeDeclaration (settings.Name); - type.IsPartial = true; - if (settings.InternalVisibility) { - type.TypeAttributes = (type.TypeAttributes & ~TypeAttributes.VisibilityMask) | TypeAttributes.NotPublic; - } - if (!string.IsNullOrEmpty (settings.Inherits)) { - type.BaseTypes.Add (new CodeTypeReference (settings.Inherits)); - } else if (!settings.IncludePreprocessingHelpers) { - type.BaseTypes.Add (TypeRef<TextTransformation> ()); - } else { - type.BaseTypes.Add (new CodeTypeReference (settings.Name + "Base")); - } - namespac.Types.Add (type); - - //prep the transform method - var transformMeth = new CodeMemberMethod { - Name = "TransformText", - ReturnType = new CodeTypeReference (typeof (String)), - Attributes = MemberAttributes.Public, - }; - if (!settings.IncludePreprocessingHelpers) - transformMeth.Attributes |= MemberAttributes.Override; - - transformMeth.Statements.Add (new CodeAssignStatement ( - new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "GenerationEnvironment"), - new CodePrimitiveExpression (null))); - - CodeExpression toStringHelper; - if (settings.IsPreprocessed) { - toStringHelper = new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "ToStringHelper"); - } else { - toStringHelper = new CodeTypeReferenceExpression ( - new CodeTypeReference (typeof (ToStringHelper), CodeTypeReferenceOptions.GlobalReference)); - } - - //method references that will need to be used multiple times - var writeMeth = new CodeMethodReferenceExpression (new CodeThisReferenceExpression (), "Write"); - var toStringMeth = new CodeMethodReferenceExpression (toStringHelper, "ToStringWithCulture"); - bool helperMode = false; - - //build the code from the segments - foreach (TemplateSegment seg in pt.Content) { - CodeStatement st = null; - CodeLinePragma location = null; - if (!settings.NoLinePragmas) { - var f = seg.StartLocation.FileName ?? host.TemplateFile; - if (settings.RelativeLinePragmas) - f = FileUtil.AbsoluteToRelativePath (baseDirectory, f).Replace ('\\', '/'); - location = new CodeLinePragma (f, seg.StartLocation.Line); - } - switch (seg.Type) { - case SegmentType.Block: - if (helperMode) - //TODO: are blocks permitted after helpers? - pt.LogError ("Blocks are not permitted after helpers", seg.TagStartLocation); - st = new CodeSnippetStatement (seg.Text); - break; - case SegmentType.Expression: - st = new CodeExpressionStatement ( - new CodeMethodInvokeExpression (writeMeth, - new CodeMethodInvokeExpression (toStringMeth, new CodeSnippetExpression (seg.Text)))); - break; - case SegmentType.Content: - st = new CodeExpressionStatement (new CodeMethodInvokeExpression (writeMeth, new CodePrimitiveExpression (seg.Text))); - break; - case SegmentType.Helper: - if (!string.IsNullOrEmpty (seg.Text)) - type.Members.Add (CreateSnippetMember (seg.Text, location)); - helperMode = true; - break; - default: - throw new InvalidOperationException (); - } - if (st != null) { - if (helperMode) { - //convert the statement into a snippet member and attach it to the top level type - //TODO: is there a way to do this for languages that use indentation for blocks, e.g. python? - using (var writer = new StringWriter ()) { - settings.Provider.GenerateCodeFromStatement (st, writer, null); - var text = writer.ToString (); - if (!string.IsNullOrEmpty (text)) - type.Members.Add (CreateSnippetMember (text, location)); - } - } else { - st.LinePragma = location; - transformMeth.Statements.Add (st); - continue; - } - } - } - - //complete the transform method - transformMeth.Statements.Add (new CodeMethodReturnStatement ( - new CodeMethodInvokeExpression ( - new CodePropertyReferenceExpression ( - new CodeThisReferenceExpression (), - "GenerationEnvironment"), - "ToString"))); - type.Members.Add (transformMeth); - - //class code and attributes from processors - foreach (var processor in settings.DirectiveProcessors.Values) { - string classCode = processor.GetClassCodeForProcessingRun (); - if (!string.IsNullOrEmpty (classCode)) - type.Members.Add (CreateSnippetMember (classCode)); - var atts = processor.GetTemplateClassCustomAttributes (); - if (atts != null) { - if (type.CustomAttributes == null) - type.CustomAttributes = new CodeAttributeDeclarationCollection (); - type.CustomAttributes.AddRange (atts); - } - } - - //generate the Host property if needed - if (settings.HostSpecific && !settings.HostPropertyOnBase) { - GenerateHostProperty (type, settings.HostType); - } - - GenerateInitializationMethod (type, settings); - - if (settings.IncludePreprocessingHelpers) { - var baseClass = new CodeTypeDeclaration (settings.Name + "Base"); - GenerateProcessingHelpers (baseClass, settings); - AddToStringHelper (baseClass, settings); - namespac.Types.Add (baseClass); - } - return ccu; - } - - static CodeSnippetTypeMember CreateSnippetMember (string value, CodeLinePragma location = null) - { - //HACK: workaround for code generator not indenting first line of member snippet when inserting into class - const string indent = "\n "; - if (!char.IsWhiteSpace (value[0])) - value = indent + value; - - return new CodeSnippetTypeMember (value) { - LinePragma = location - }; - } - - static void GenerateHostProperty (CodeTypeDeclaration type, Type hostType) - { - var hostTypeRef = new CodeTypeReference (hostType, CodeTypeReferenceOptions.GlobalReference); - var hostField = new CodeMemberField (hostTypeRef, "hostValue"); - hostField.Attributes = (hostField.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private; - type.Members.Add (hostField); - - var hostProp = GenerateGetterSetterProperty ("Host", hostField); - hostProp.Attributes = MemberAttributes.Public | MemberAttributes.Final; - type.Members.Add (hostProp); - } - - static void GenerateInitializationMethod (CodeTypeDeclaration type, TemplateSettings settings) - { - //initialization method - var initializeMeth = new CodeMemberMethod { - Name = "Initialize", - ReturnType = new CodeTypeReference (typeof (void), CodeTypeReferenceOptions.GlobalReference), - Attributes = MemberAttributes.Public - }; - if (!settings.IncludePreprocessingHelpers) - initializeMeth.Attributes |= MemberAttributes.Override; - - //if preprocessed, pass the extension and encoding to the host - if (settings.IsPreprocessed && settings.HostSpecific) { - var hostProp = new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "Host"); - var statements = new List<CodeStatement> (); - - if (!string.IsNullOrEmpty (settings.Extension)) { - statements.Add (new CodeExpressionStatement (new CodeMethodInvokeExpression ( - hostProp, - "SetFileExtension", - new CodePrimitiveExpression (settings.Extension) - ))); - } - - if (settings.Encoding != null) { - statements.Add (new CodeExpressionStatement (new CodeMethodInvokeExpression ( - hostProp, - "SetOutputEncoding", - new CodeMethodInvokeExpression( - new CodeTypeReferenceExpression (typeof(Encoding)), - "GetEncoding", - new CodePrimitiveExpression (settings.Encoding.CodePage), - new CodePrimitiveExpression(true) - ) - ))); - } - - if (statements.Count > 0) { - initializeMeth.Statements.Add (new CodeConditionStatement ( - new CodeBinaryOperatorExpression ( - hostProp, - CodeBinaryOperatorType.IdentityInequality, - new CodePrimitiveExpression (null) - ), - statements.ToArray() - )); - } - } - - //pre-init code from processors - foreach (var processor in settings.DirectiveProcessors.Values) { - string code = processor.GetPreInitializationCodeForProcessingRun (); - if (code != null) - initializeMeth.Statements.Add (new CodeSnippetStatement (code)); - } - - //base call - if (!settings.IncludePreprocessingHelpers) { - initializeMeth.Statements.Add ( - new CodeMethodInvokeExpression ( - new CodeMethodReferenceExpression ( - new CodeBaseReferenceExpression (), - "Initialize"))); - } - - //post-init code from processors - foreach (var processor in settings.DirectiveProcessors.Values) { - string code = processor.GetPostInitializationCodeForProcessingRun (); - if (code != null) - initializeMeth.Statements.Add (new CodeSnippetStatement (code)); - } - - type.Members.Add (initializeMeth); - } - - static void GenerateProcessingHelpers (CodeTypeDeclaration type, TemplateSettings settings) - { - var thisRef = new CodeThisReferenceExpression (); - var sbTypeRef = TypeRef<StringBuilder> (); - - var sessionField = PrivateField (TypeRef<IDictionary<string,object>> (), "session"); - var sessionProp = GenerateGetterSetterProperty ("Session", sessionField); - sessionProp.Attributes = MemberAttributes.Public; - - var builderField = PrivateField (sbTypeRef, "builder"); - var builderFieldRef = new CodeFieldReferenceExpression (thisRef, builderField.Name); - - var generationEnvironmentProp = GenerateGetterSetterProperty ("GenerationEnvironment", builderField); - AddPropertyGetterInitializationIfFieldIsNull (generationEnvironmentProp, builderFieldRef, TypeRef<StringBuilder> ()); - - type.Members.Add (builderField); - type.Members.Add (sessionField); - type.Members.Add (sessionProp); - type.Members.Add (generationEnvironmentProp); - - AddErrorHelpers (type); - AddIndentHelpers (type); - AddWriteHelpers (type); - } -
- static void AddPropertyGetterInitializationIfFieldIsNull (CodeMemberProperty property, CodeFieldReferenceExpression fieldRef, CodeTypeReference typeRef)
- {
- var fieldInit = FieldInitializationIfNull (fieldRef, typeRef);
- property.GetStatements.Insert (0, fieldInit);
- }
-
- static CodeConditionStatement FieldInitializationIfNull (CodeExpression fieldRef, CodeTypeReference typeRef) - {
- return new CodeConditionStatement (
- new CodeBinaryOperatorExpression (fieldRef,
- CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (null)),
- new CodeAssignStatement (fieldRef, new CodeObjectCreateExpression (typeRef)));
- }
- - static void AddErrorHelpers (CodeTypeDeclaration type) - { - var cecTypeRef = TypeRef<CompilerErrorCollection> (); - var thisRef = new CodeThisReferenceExpression (); - var stringTypeRef = TypeRef<string> (); - var nullPrim = new CodePrimitiveExpression (null); - var minusOnePrim = new CodePrimitiveExpression (-1); - - var errorsField = PrivateField (cecTypeRef, "errors"); - var errorsFieldRef = new CodeFieldReferenceExpression (thisRef, errorsField.Name); - - var errorsProp = GenerateGetterProperty ("Errors", errorsField); - errorsProp.Attributes = MemberAttributes.Family | MemberAttributes.Final; - errorsProp.GetStatements.Insert (0, FieldInitializationIfNull (errorsFieldRef, TypeRef<CompilerErrorCollection>())); - - var errorsPropRef = new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "Errors"); - - var compilerErrorTypeRef = TypeRef<CompilerError> (); - var errorMeth = new CodeMemberMethod { - Name = "Error", - Attributes = MemberAttributes.Public | MemberAttributes.Final, - }; - errorMeth.Parameters.Add (new CodeParameterDeclarationExpression (stringTypeRef, "message")); - errorMeth.Statements.Add (new CodeMethodInvokeExpression (errorsPropRef, "Add", - new CodeObjectCreateExpression (compilerErrorTypeRef, nullPrim, minusOnePrim, minusOnePrim, nullPrim, - new CodeArgumentReferenceExpression ("message")))); - - var warningMeth = new CodeMemberMethod { - Name = "Warning", - Attributes = MemberAttributes.Public | MemberAttributes.Final, - }; - warningMeth.Parameters.Add (new CodeParameterDeclarationExpression (stringTypeRef, "message")); - warningMeth.Statements.Add (new CodeVariableDeclarationStatement (compilerErrorTypeRef, "val", - new CodeObjectCreateExpression (compilerErrorTypeRef, nullPrim, minusOnePrim, minusOnePrim, nullPrim, - new CodeArgumentReferenceExpression ("message")))); - warningMeth.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression ( - new CodeVariableReferenceExpression ("val"), "IsWarning"), new CodePrimitiveExpression (true))); - warningMeth.Statements.Add (new CodeMethodInvokeExpression (errorsPropRef, "Add", - new CodeVariableReferenceExpression ("val"))); - - type.Members.Add (errorsField); - type.Members.Add (errorMeth); - type.Members.Add (warningMeth); - type.Members.Add (errorsProp); - } - - static void AddIndentHelpers (CodeTypeDeclaration type) - { - var stringTypeRef = TypeRef<string> (); - var thisRef = new CodeThisReferenceExpression (); - var zeroPrim = new CodePrimitiveExpression (0); - var stringEmptyRef = new CodeFieldReferenceExpression (new CodeTypeReferenceExpression (stringTypeRef), "Empty"); - var intTypeRef = TypeRef<int> (); - var stackIntTypeRef = TypeRef<Stack<int>> (); - - var indentsField = PrivateField (stackIntTypeRef, "indents"); - var indentsFieldRef = new CodeFieldReferenceExpression (thisRef, indentsField.Name); - - var indentsProp = GenerateGetterProperty ("Indents", indentsField); - indentsProp.Attributes = MemberAttributes.Private; - AddPropertyGetterInitializationIfFieldIsNull (indentsProp, indentsFieldRef, TypeRef<Stack<int>> ()); - - var indentsPropRef = new CodeFieldReferenceExpression (thisRef, indentsProp.Name); - - var currentIndentField = PrivateField (stringTypeRef, "currentIndent"); - currentIndentField.InitExpression = stringEmptyRef; - var currentIndentFieldRef = new CodeFieldReferenceExpression (thisRef, currentIndentField.Name); - - var popIndentMeth = new CodeMemberMethod { - Name = "PopIndent", - ReturnType = stringTypeRef, - Attributes = MemberAttributes.Public | MemberAttributes.Final, - }; - popIndentMeth.Statements.Add (new CodeConditionStatement ( - new CodeBinaryOperatorExpression (new CodePropertyReferenceExpression (indentsPropRef, "Count"), - CodeBinaryOperatorType.ValueEquality, zeroPrim), - new CodeMethodReturnStatement (stringEmptyRef))); - popIndentMeth.Statements.Add (new CodeVariableDeclarationStatement (intTypeRef, "lastPos", - new CodeBinaryOperatorExpression ( - new CodePropertyReferenceExpression (currentIndentFieldRef, "Length"), - CodeBinaryOperatorType.Subtract, - new CodeMethodInvokeExpression (indentsPropRef, "Pop")))); - popIndentMeth.Statements.Add (new CodeVariableDeclarationStatement (stringTypeRef, "last", - new CodeMethodInvokeExpression (currentIndentFieldRef, "Substring", new CodeVariableReferenceExpression ("lastPos")))); - popIndentMeth.Statements.Add (new CodeAssignStatement (currentIndentFieldRef, - new CodeMethodInvokeExpression (currentIndentFieldRef, "Substring", zeroPrim, new CodeVariableReferenceExpression ("lastPos")))); - popIndentMeth.Statements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("last"))); - - var pushIndentMeth = new CodeMemberMethod { - Name = "PushIndent", - Attributes = MemberAttributes.Public | MemberAttributes.Final, - }; - pushIndentMeth.Parameters.Add (new CodeParameterDeclarationExpression (stringTypeRef, "indent")); - pushIndentMeth.Statements.Add (new CodeMethodInvokeExpression (indentsPropRef, "Push", - new CodePropertyReferenceExpression (new CodeArgumentReferenceExpression ("indent"), "Length"))); - pushIndentMeth.Statements.Add (new CodeAssignStatement (currentIndentFieldRef, - new CodeBinaryOperatorExpression (currentIndentFieldRef, CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("indent")))); - - var clearIndentMeth = new CodeMemberMethod { - Name = "ClearIndent", - Attributes = MemberAttributes.Public | MemberAttributes.Final, - }; - clearIndentMeth.Statements.Add (new CodeAssignStatement (currentIndentFieldRef, stringEmptyRef)); - clearIndentMeth.Statements.Add (new CodeMethodInvokeExpression (indentsPropRef, "Clear")); - - var currentIndentProp = GenerateGetterProperty ("CurrentIndent", currentIndentField); - type.Members.Add (currentIndentField); - type.Members.Add (indentsField); - type.Members.Add (popIndentMeth); - type.Members.Add (pushIndentMeth); - type.Members.Add (clearIndentMeth); - type.Members.Add (currentIndentProp); - type.Members.Add (indentsProp); - } - - static void AddWriteHelpers (CodeTypeDeclaration type) - { - var stringTypeRef = TypeRef<string> (); - var thisRef = new CodeThisReferenceExpression (); - var genEnvPropRef = new CodePropertyReferenceExpression (thisRef, "GenerationEnvironment"); - var currentIndentFieldRef = new CodeFieldReferenceExpression (thisRef, "currentIndent"); - - var textToAppendParam = new CodeParameterDeclarationExpression (stringTypeRef, "textToAppend"); - var formatParam = new CodeParameterDeclarationExpression (stringTypeRef, "format"); - var argsParam = new CodeParameterDeclarationExpression (TypeRef<object[]> (), "args"); - argsParam.CustomAttributes.Add (new CodeAttributeDeclaration (TypeRef<ParamArrayAttribute> ())); - - var textToAppendParamRef = new CodeArgumentReferenceExpression ("textToAppend"); - var formatParamRef = new CodeArgumentReferenceExpression ("format"); - var argsParamRef = new CodeArgumentReferenceExpression ("args"); - - var writeMeth = new CodeMemberMethod { - Name = "Write", - Attributes = MemberAttributes.Public | MemberAttributes.Final, - }; - writeMeth.Parameters.Add (textToAppendParam); - writeMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "Append", new CodeArgumentReferenceExpression ("textToAppend"))); - - var writeArgsMeth = new CodeMemberMethod { - Name = "Write", - Attributes = MemberAttributes.Public | MemberAttributes.Final, - }; - writeArgsMeth.Parameters.Add (formatParam); - writeArgsMeth.Parameters.Add (argsParam); - writeArgsMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "AppendFormat", formatParamRef, argsParamRef)); - - var writeLineMeth = new CodeMemberMethod { - Name = "WriteLine", - Attributes = MemberAttributes.Public | MemberAttributes.Final, - }; - writeLineMeth.Parameters.Add (textToAppendParam); - writeLineMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "Append", currentIndentFieldRef)); - writeLineMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "AppendLine", textToAppendParamRef)); - - var writeLineArgsMeth = new CodeMemberMethod { - Name = "WriteLine", - Attributes = MemberAttributes.Public | MemberAttributes.Final, - }; - writeLineArgsMeth.Parameters.Add (formatParam); - writeLineArgsMeth.Parameters.Add (argsParam); - writeLineArgsMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "Append", currentIndentFieldRef)); - writeLineArgsMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "AppendFormat", formatParamRef, argsParamRef)); - writeLineArgsMeth.Statements.Add (new CodeMethodInvokeExpression (genEnvPropRef, "AppendLine")); - - type.Members.Add (writeMeth); - type.Members.Add (writeArgsMeth); - type.Members.Add (writeLineMeth); - type.Members.Add (writeLineArgsMeth); - } - - static void AddToStringHelper (CodeTypeDeclaration type, TemplateSettings settings) - { - var helperCls = new CodeTypeDeclaration ("ToStringInstanceHelper") { - IsClass = true, - TypeAttributes = TypeAttributes.NestedPublic, - }; - - var formatProviderField = PrivateField (TypeRef<IFormatProvider> (), "formatProvider"); - formatProviderField.InitExpression = new CodePropertyReferenceExpression ( - new CodeTypeReferenceExpression (TypeRef<System.Globalization.CultureInfo> ()), "InvariantCulture"); - var formatProviderFieldRef = new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), formatProviderField.Name); - - var formatProviderProp = GenerateGetterSetterProperty ("FormatProvider", formatProviderField); - MakeSimpleSetterIgnoreNull (formatProviderProp); - - helperCls.Members.Add (formatProviderField); - helperCls.Members.Add (formatProviderProp); - - var meth = new CodeMemberMethod { - Name = "ToStringWithCulture", - Attributes = MemberAttributes.Public | MemberAttributes.Final, - ReturnType = TypeRef<string> (), - }; - meth.Parameters.Add (new CodeParameterDeclarationExpression (TypeRef<object> (), "objectToConvert")); - var paramRef = new CodeArgumentReferenceExpression ("objectToConvert"); - - meth.Statements.Add (NullCheck (paramRef, paramRef.ParameterName)); - - var typeLocal = new CodeVariableDeclarationStatement (TypeRef<Type> (), "type", new CodeMethodInvokeExpression (paramRef, "GetType")); - var typeLocalRef = new CodeVariableReferenceExpression (typeLocal.Name); - meth.Statements.Add (typeLocal); - - var iConvertibleTypeLocal = new CodeVariableDeclarationStatement (TypeRef<Type> (), "iConvertibleType", - new CodeTypeOfExpression (TypeRef<IConvertible> ())); - var iConvertibleTypeLocalRef = new CodeVariableReferenceExpression (iConvertibleTypeLocal.Name); - meth.Statements.Add (iConvertibleTypeLocal); - - meth.Statements.Add (new CodeConditionStatement ( - new CodeMethodInvokeExpression (iConvertibleTypeLocalRef, "IsAssignableFrom", typeLocalRef), - new CodeMethodReturnStatement (new CodeMethodInvokeExpression ( - new CodeCastExpression (TypeRef<IConvertible> (), paramRef), "ToString", formatProviderFieldRef)))); - - var methInfoLocal = new CodeVariableDeclarationStatement (TypeRef<MethodInfo> (), "methInfo", - new CodeMethodInvokeExpression (typeLocalRef, "GetMethod", - new CodePrimitiveExpression ("ToString"), - new CodeArrayCreateExpression (TypeRef<Type> (), new CodeExpression [] { iConvertibleTypeLocalRef }))); - meth.Statements.Add (methInfoLocal); - var methInfoLocalRef = new CodeVariableReferenceExpression (methInfoLocal.Name); - meth.Statements.Add (new CodeConditionStatement (NotNull (methInfoLocalRef), - new CodeMethodReturnStatement (new CodeCastExpression (TypeRef<string> (), - new CodeMethodInvokeExpression ( - methInfoLocalRef, "Invoke", paramRef, - new CodeArrayCreateExpression (TypeRef<object> (), new CodeExpression [] { formatProviderFieldRef } )))))); - - meth.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (paramRef, "ToString"))); - - helperCls.Members.Add (meth); - - - var helperFieldName = settings.Provider.CreateValidIdentifier ("_toStringHelper"); - var helperField = PrivateField (new CodeTypeReference (helperCls.Name), helperFieldName); - helperField.InitExpression = new CodeObjectCreateExpression (helperField.Type); - type.Members.Add (helperField); - type.Members.Add (GenerateGetterProperty ("ToStringHelper", helperField)); - type.Members.Add (helperCls); - } - - #region CodeDom helpers - - static CodeTypeReference TypeRef<T> () - { - return new CodeTypeReference (typeof (T), CodeTypeReferenceOptions.GlobalReference); - } - - static CodeMemberProperty GenerateGetterSetterProperty (string propertyName, CodeMemberField field) - { - var prop = new CodeMemberProperty { - Name = propertyName, - Attributes = MemberAttributes.Public | MemberAttributes.Final, - Type = field.Type - }; - var fieldRef = new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), field.Name); - AddGetter (prop, fieldRef); - AddSetter (prop, fieldRef); - return prop; - } - - static CodeMemberProperty GenerateGetterProperty (string propertyName, CodeMemberField field) - { - var prop = new CodeMemberProperty { - Name = propertyName, - Attributes = MemberAttributes.Public | MemberAttributes.Final, - HasSet = false, - Type = field.Type - }; - var fieldRef = new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), field.Name); - AddGetter (prop, fieldRef); - return prop; - } - - static void AddSetter (CodeMemberProperty property, CodeFieldReferenceExpression fieldRef) - { - property.HasSet = true; - property.SetStatements.Add (new CodeAssignStatement (fieldRef, new CodePropertySetValueReferenceExpression ())); - } - - static void AddGetter (CodeMemberProperty property, CodeFieldReferenceExpression fieldRef) - { - property.HasGet = true; - property.GetStatements.Add (new CodeMethodReturnStatement (fieldRef)); - } - - static void MakeGetterLazy (CodeMemberProperty property, CodeFieldReferenceExpression fieldRef, CodeExpression initExpression) - { - property.GetStatements.Insert (0, new CodeConditionStatement ( - NotNull (fieldRef), - new CodeAssignStatement (fieldRef, initExpression)) - ); - } - - static void MakeSimpleSetterIgnoreNull (CodeMemberProperty property) - { - property.SetStatements [0] = new CodeConditionStatement ( - NotNull (new CodePropertySetValueReferenceExpression ()), - property.SetStatements [0]); - } - - static CodeStatement NullCheck (CodeExpression expr, string exceptionMessage) - { - return new CodeConditionStatement ( - IsNull (expr), - new CodeThrowExceptionStatement (new CodeObjectCreateExpression ( - new CodeTypeReference (typeof (ArgumentNullException), CodeTypeReferenceOptions.GlobalReference), - new CodePrimitiveExpression (exceptionMessage))) - ); - } - - static CodeBinaryOperatorExpression NotNull (CodeExpression reference) - { - return new CodeBinaryOperatorExpression (reference, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null)); - } - - static CodeBinaryOperatorExpression IsNull (CodeExpression reference) - { - return new CodeBinaryOperatorExpression (reference, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (null)); - } - - static CodeBinaryOperatorExpression IsFalse (CodeExpression expr) - { - return new CodeBinaryOperatorExpression (expr, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (false)); - } - - static CodeBinaryOperatorExpression BooleanAnd (CodeExpression expr1, CodeExpression expr2) - { - return new CodeBinaryOperatorExpression (expr1, CodeBinaryOperatorType.BooleanAnd, expr2); - } - - static CodeStatement ArgNullCheck (CodeExpression value, params CodeExpression[] argNullExcArgs) - { - return new CodeConditionStatement ( - new CodeBinaryOperatorExpression (value, - CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (null)), - new CodeThrowExceptionStatement (new CodeObjectCreateExpression (typeof (ArgumentNullException), argNullExcArgs))); - } - - static CodeMemberField PrivateField (CodeTypeReference typeRef, string name) - { - return new CodeMemberField (typeRef, name) { - Attributes = MemberAttributes.Private - }; - } - - #endregion - - //HACK: Mono as of 2.10.2 doesn't implement GenerateCodeFromMember - static readonly bool useMonoHack = Type.GetType ("Mono.Runtime") != null; - - /// <summary> - /// An implementation of CodeDomProvider.GenerateCodeFromMember that works on Mono. - /// </summary> - public static void GenerateCodeFromMembers (CodeDomProvider provider, CodeGeneratorOptions options, StringWriter sw, IEnumerable<CodeTypeMember> members) - { - if (!useMonoHack) { - foreach (CodeTypeMember member in members) - provider.GenerateCodeFromMember (member, sw, options); - return; - } - - var cgType = typeof (CodeGenerator); - var initializeCodeGenerator = GetInitializeCodeGeneratorAction (cgType); - var cgFieldGen = cgType.GetMethod ("GenerateField", BindingFlags.NonPublic | BindingFlags.Instance); - var cgPropGen = cgType.GetMethod ("GenerateProperty", BindingFlags.NonPublic | BindingFlags.Instance); - var cgMethGen = cgType.GetMethod ("GenerateMethod", BindingFlags.NonPublic | BindingFlags.Instance); - - #pragma warning disable 0618 - var generator = (CodeGenerator) provider.CreateGenerator (); - #pragma warning restore 0618 - var dummy = new CodeTypeDeclaration ("Foo"); - - foreach (CodeTypeMember member in members) { - var f = member as CodeMemberField; - if (f != null) { - initializeCodeGenerator (generator, sw, options); - cgFieldGen.Invoke (generator, new object[] { f }); - continue; - } - var p = member as CodeMemberProperty; - if (p != null) { - initializeCodeGenerator (generator, sw, options); - cgPropGen.Invoke (generator, new object[] { p, dummy }); - continue; - } - var m = member as CodeMemberMethod; - if (m != null) { - initializeCodeGenerator (generator, sw, options); - cgMethGen.Invoke (generator, new object[] { m, dummy }); - continue; - } - } - } - - static Action<CodeGenerator, StringWriter, CodeGeneratorOptions> GetInitializeCodeGeneratorAction (Type cgType) - { - var cgInit = cgType.GetMethod ("InitOutput", BindingFlags.NonPublic | BindingFlags.Instance); - if (cgInit != null) { - return new Action<CodeGenerator, StringWriter, CodeGeneratorOptions> ((generator, sw, options) => { - cgInit.Invoke (generator, new object[] { sw, options }); - }); - } - - var cgOptions = cgType.GetField ("options", BindingFlags.NonPublic | BindingFlags.Instance); - var cgOutput = cgType.GetField ("output", BindingFlags.NonPublic | BindingFlags.Instance); - - if (cgOptions != null && cgOutput != null) { - return new Action<CodeGenerator, StringWriter, CodeGeneratorOptions> ((generator, sw, options) => { - var output = new IndentedTextWriter (sw); - cgOptions.SetValue (generator, options); - cgOutput.SetValue (generator, output); - }); - } - - throw new InvalidOperationException ("Unable to initialize CodeGenerator."); - } - - public static string GenerateIndentedClassCode (CodeDomProvider provider, params CodeTypeMember[] members) - { - return GenerateIndentedClassCode (provider, (IEnumerable<CodeTypeMember>)members); - } - - public static string GenerateIndentedClassCode (CodeDomProvider provider, IEnumerable<CodeTypeMember> members) - { - var options = new CodeGeneratorOptions (); - using (var sw = new StringWriter ()) { - TemplatingEngine.GenerateCodeFromMembers (provider, options, sw, members); - return TemplatingEngine.IndentSnippetText (provider, sw.ToString (), " "); - } - } - } -} diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/Tokeniser.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/Tokeniser.cs deleted file mode 100644 index 1ff578ed8e..0000000000 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/Tokeniser.cs +++ /dev/null @@ -1,293 +0,0 @@ -// -// Tokeniser.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -namespace Mono.TextTemplating -{ - - public class Tokeniser - { - readonly string content; - int position; - string value; - State nextState = State.Content; - Location nextStateLocation; - Location nextStateTagStartLocation; - - public Tokeniser (string fileName, string content) - { - State = State.Content; - this.content = content; - this.Location = this.nextStateLocation = this.nextStateTagStartLocation = new Location (fileName, 1, 1); - } - - public bool Advance () - { - value = null; - State = nextState; - Location = nextStateLocation; - TagStartLocation = nextStateTagStartLocation; - if (nextState == State.EOF) - return false; - nextState = GetNextStateAndCurrentValue (); - return true; - } - - State GetNextStateAndCurrentValue () - { - switch (State) { - case State.Block: - case State.Expression: - case State.Helper: - return GetBlockEnd (); - - case State.Directive: - return NextStateInDirective (); - - case State.Content: - return NextStateInContent (); - - case State.DirectiveName: - return GetDirectiveName (); - - case State.DirectiveValue: - return GetDirectiveValue (); - - default: - throw new InvalidOperationException ("Unexpected state '" + State + "'"); - } - } - - State GetBlockEnd () - { - int start = position; - for (; position < content.Length; position++) { - char c = content[position]; - nextStateTagStartLocation = nextStateLocation; - nextStateLocation = nextStateLocation.AddCol (); - if (c == '\r') { - if (position + 1 < content.Length && content[position + 1] == '\n') - position++; - nextStateLocation = nextStateLocation.AddLine(); - } else if (c == '\n') { - nextStateLocation = nextStateLocation.AddLine(); - } else if (c =='>' && content[position-1] == '#' && content[position-2] != '\\') { - value = content.Substring (start, position - start - 1); - position++; - TagEndLocation = nextStateLocation; - - //skip newlines directly after blocks, unless they're expressions - if (State != State.Expression && (position += IsNewLine()) > 0) { - nextStateLocation = nextStateLocation.AddLine (); - } - return State.Content; - } - } - throw new ParserException ("Unexpected end of file.", nextStateLocation); - } - - State GetDirectiveName () - { - int start = position; - for (; position < content.Length; position++) { - char c = content [position]; - if (!Char.IsLetterOrDigit (c)) { - value = content.Substring (start, position - start); - return State.Directive; - } - nextStateLocation = nextStateLocation.AddCol (); - } - throw new ParserException ("Unexpected end of file.", nextStateLocation); - } - - State GetDirectiveValue () - { - int start = position; - int delimiter = '\0'; - for (; position < content.Length; position++) { - char c = content[position]; - nextStateLocation = nextStateLocation.AddCol (); - if (c == '\r') { - if (position + 1 < content.Length && content[position + 1] == '\n') - position++; - nextStateLocation = nextStateLocation.AddLine(); - } else if (c == '\n') - nextStateLocation = nextStateLocation.AddLine(); - if (delimiter == '\0') { - if (c == '\'' || c == '"') { - start = position; - delimiter = c; - } else if (!Char.IsWhiteSpace (c)) { - throw new ParserException ("Unexpected character '" + c + "'. Expecting attribute value.", nextStateLocation); - } - continue; - } - if (c == delimiter) { - value = content.Substring (start + 1, position - start - 1); - position++; - return State.Directive; - } - } - throw new ParserException ("Unexpected end of file.", nextStateLocation); - } - - State NextStateInContent () - { - int start = position; - for (; position < content.Length; position++) { - char c = content[position]; - nextStateTagStartLocation = nextStateLocation; - nextStateLocation = nextStateLocation.AddCol (); - if (c == '\r') { - if (position + 1 < content.Length && content[position + 1] == '\n') - position++; - nextStateLocation = nextStateLocation.AddLine(); - } else if (c == '\n') { - nextStateLocation = nextStateLocation.AddLine(); - } else if (c =='<' && position + 2 < content.Length && content[position+1] == '#') { - TagEndLocation = nextStateLocation; - char type = content [position + 2]; - if (type == '@') { - nextStateLocation = nextStateLocation.AddCols (2); - value = content.Substring (start, position - start); - position += 3; - return State.Directive; - } - if (type == '=') { - nextStateLocation = nextStateLocation.AddCols (2); - value = content.Substring (start, position - start); - position += 3; - return State.Expression; - } - if (type == '+') { - nextStateLocation = nextStateLocation.AddCols (2); - value = content.Substring (start, position - start); - position += 3; - return State.Helper; - } - value = content.Substring (start, position - start); - nextStateLocation = nextStateLocation.AddCol (); - position += 2; - return State.Block; - } - } - //EOF is only valid when we're in content - value = content.Substring (start); - return State.EOF; - } - - int IsNewLine() { - int found = 0; - - if (position < content.Length && content[position] == '\r') { - found++; - } - if (position+found < content.Length && content[position+found] == '\n') { - found++; - } - return found; - } - - State NextStateInDirective () { - for (; position < content.Length; position++) { - char c = content[position]; - if (c == '\r') { - if (position + 1 < content.Length && content[position + 1] == '\n') - position++; - nextStateLocation = nextStateLocation.AddLine(); - } else if (c == '\n') { - nextStateLocation = nextStateLocation.AddLine(); - } else if (Char.IsLetter (c)) { - return State.DirectiveName; - } else if (c == '=') { - nextStateLocation = nextStateLocation.AddCol (); - position++; - return State.DirectiveValue; - } else if (c == '#' && position + 1 < content.Length && content[position+1] == '>') { - position+=2; - TagEndLocation = nextStateLocation.AddCols (2); - nextStateLocation = nextStateLocation.AddCols (3); - - //skip newlines directly after directives - if ((position += IsNewLine()) > 0) { - nextStateLocation = nextStateLocation.AddLine(); - } - - return State.Content; - } else if (!Char.IsWhiteSpace (c)) { - throw new ParserException ("Directive ended unexpectedly with character '" + c + "'", nextStateLocation); - } else { - nextStateLocation = nextStateLocation.AddCol (); - } - } - throw new ParserException ("Unexpected end of file.", nextStateLocation); - } - - public State State { - get; private set; - } - - public int Position { - get { return position; } - } - - public string Content { - get { return content; } - } - - public string Value { - get { return value; } - } - - public Location Location { get; private set; } - public Location TagStartLocation { get; private set; } - public Location TagEndLocation { get; private set; } - } - - public enum State - { - Content = 0, - Directive, - Expression, - Block, - Helper, - DirectiveName, - DirectiveValue, - Name, - EOF - } - - public class ParserException : Exception - { - public ParserException (string message, Location location) : base (message) - { - Location = location; - } - - public Location Location { get; private set; } - } -} diff --git a/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/MonoDevelop.TextTemplating.csproj b/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/MonoDevelop.TextTemplating.csproj index 8df136c0bc..70532b3906 100644 --- a/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/MonoDevelop.TextTemplating.csproj +++ b/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/MonoDevelop.TextTemplating.csproj @@ -82,6 +82,9 @@ <HintPath>..\..\..\..\build\bin\Microsoft.CodeAnalysis.dll</HintPath> <Private>False</Private> </Reference> + <Reference Include="Mono.TextTemplating"> + <HintPath>..\..\..\..\packages\Mono.TextTemplating.1.3.0\lib\net45\Mono.TextTemplating.dll</HintPath> + </Reference> </ItemGroup> <ItemGroup> <Folder Include="Parser\" /> @@ -89,11 +92,6 @@ <Folder Include="Templates\" /> </ItemGroup> <ItemGroup> - <ProjectReference Include="..\Mono.TextTemplating\Mono.TextTemplating.csproj"> - <Project>{A2364D6A-00EF-417C-80A6-815726C70032}</Project> - <Name>Mono.TextTemplating</Name> - <Private>False</Private> - </ProjectReference> <ProjectReference Include="..\..\..\core\MonoDevelop.Core\MonoDevelop.Core.csproj"> <Project>{7525BB88-6142-4A26-93B9-A30C6983390A}</Project> <Name>MonoDevelop.Core</Name> @@ -128,6 +126,11 @@ <None Include="Templates\T4PreprocessedTemplateCSharp.xft.xml"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> + <None Include="packages.config" /> + <None Include="..\..\..\..\packages\Mono.TextTemplating.1.3.0\tools\TextTransform.exe"> + <Link>TextTransform.exe</Link> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> </Project> diff --git a/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/packages.config b/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/packages.config new file mode 100644 index 0000000000..f2cdb24097 --- /dev/null +++ b/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/packages.config @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="Mono.TextTemplating" version="1.3.0" targetFramework="net45" /> +</packages> diff --git a/main/src/addins/TextTemplating/TextTransform/AssemblyInfo.cs b/main/src/addins/TextTemplating/TextTransform/AssemblyInfo.cs deleted file mode 100644 index abe1e8b46d..0000000000 --- a/main/src/addins/TextTemplating/TextTransform/AssemblyInfo.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// AssemblyInfo.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System.Reflection; -using System.Runtime.CompilerServices; - -// Information about this assembly is defined by the following attributes. -// Change them to the values specific to your project. - -[assembly: AssemblyTitle("TextTransform")] -[assembly: AssemblyDescription("T4 text transformation tool")] -[assembly: AssemblyCompany("The Mono Project")] -[assembly: AssemblyProduct("MonoDevelop")] -[assembly: AssemblyCopyright("MIT/X11")] - -//[assembly: AssemblyVersion("1.0.0.0")] - diff --git a/main/src/addins/TextTemplating/TextTransform/Makefile.am b/main/src/addins/TextTemplating/TextTransform/Makefile.am deleted file mode 100644 index c9cc87438f..0000000000 --- a/main/src/addins/TextTemplating/TextTransform/Makefile.am +++ /dev/null @@ -1 +0,0 @@ -include $(top_srcdir)/xbuild.include diff --git a/main/src/addins/TextTemplating/TextTransform/Options.cs b/main/src/addins/TextTemplating/TextTransform/Options.cs deleted file mode 100644 index 124ad72fd3..0000000000 --- a/main/src/addins/TextTemplating/TextTransform/Options.cs +++ /dev/null @@ -1,1099 +0,0 @@ -// -// Options.cs -// -// Authors: -// Jonathan Pryor <jpryor@novell.com> -// -// Copyright (C) 2008 Novell (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. -// - -// Compile With: -// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll -// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll -// -// The LINQ version just changes the implementation of -// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. - -// -// A Getopt::Long-inspired option parsing library for C#. -// -// NDesk.Options.OptionSet is built upon a key/value table, where the -// key is a option format string and the value is a delegate that is -// invoked when the format string is matched. -// -// Option format strings: -// Regex-like BNF Grammar: -// name: .+ -// type: [=:] -// sep: ( [^{}]+ | '{' .+ '}' )? -// aliases: ( name type sep ) ( '|' name type sep )* -// -// Each '|'-delimited name is an alias for the associated action. If the -// format string ends in a '=', it has a required value. If the format -// string ends in a ':', it has an optional value. If neither '=' or ':' -// is present, no value is supported. `=' or `:' need only be defined on one -// alias, but if they are provided on more than one they must be consistent. -// -// Each alias portion may also end with a "key/value separator", which is used -// to split option values if the option accepts > 1 value. If not specified, -// it defaults to '=' and ':'. If specified, it can be any character except -// '{' and '}' OR the *string* between '{' and '}'. If no separator should be -// used (i.e. the separate values should be distinct arguments), then "{}" -// should be used as the separator. -// -// Options are extracted either from the current option by looking for -// the option name followed by an '=' or ':', or is taken from the -// following option IFF: -// - The current option does not contain a '=' or a ':' -// - The current option requires a value (i.e. not a Option type of ':') -// -// The `name' used in the option format string does NOT include any leading -// option indicator, such as '-', '--', or '/'. All three of these are -// permitted/required on any named option. -// -// Option bundling is permitted so long as: -// - '-' is used to start the option group -// - all of the bundled options are a single character -// - at most one of the bundled options accepts a value, and the value -// provided starts from the next character to the end of the string. -// -// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' -// as '-Dname=value'. -// -// Option processing is disabled by specifying "--". All options after "--" -// are returned by OptionSet.Parse() unchanged and unprocessed. -// -// Unprocessed options are returned from OptionSet.Parse(). -// -// Examples: -// int verbose = 0; -// OptionSet p = new OptionSet () -// .Add ("v", v => ++verbose) -// .Add ("name=|value=", v => Console.WriteLine (v)); -// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); -// -// The above would parse the argument string array, and would invoke the -// lambda expression three times, setting `verbose' to 3 when complete. -// It would also print out "A" and "B" to standard output. -// The returned array would contain the string "extra". -// -// C# 3.0 collection initializers are supported and encouraged: -// var p = new OptionSet () { -// { "h|?|help", v => ShowHelp () }, -// }; -// -// System.ComponentModel.TypeConverter is also supported, allowing the use of -// custom data types in the callback type; TypeConverter.ConvertFromString() -// is used to convert the value option to an instance of the specified -// type: -// -// var p = new OptionSet () { -// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, -// }; -// -// Random other tidbits: -// - Boolean options (those w/o '=' or ':' in the option format string) -// are explicitly enabled if they are followed with '+', and explicitly -// disabled if they are followed with '-': -// string a = null; -// var p = new OptionSet () { -// { "a", s => a = s }, -// }; -// p.Parse (new string[]{"-a"}); // sets v != null -// p.Parse (new string[]{"-a+"}); // sets v != null -// p.Parse (new string[]{"-a-"}); // sets v == null -// - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Globalization; -using System.IO; -using System.Runtime.Serialization; -using System.Security.Permissions; -using System.Text; -using System.Text.RegularExpressions; - -#if LINQ -using System.Linq; -#endif - -#if TEST -using NDesk.Options; -#endif - -#if NDESK_OPTIONS -namespace NDesk.Options -#else -namespace Mono.Options -#endif -{ - public class OptionValueCollection : IList, IList<string> { - - List<string> values = new List<string> (); - OptionContext c; - - internal OptionValueCollection (OptionContext c) - { - this.c = c; - } - - #region ICollection - void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} - bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}} - object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}} - #endregion - - #region ICollection<T> - public void Add (string item) {values.Add (item);} - public void Clear () {values.Clear ();} - public bool Contains (string item) {return values.Contains (item);} - public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} - public bool Remove (string item) {return values.Remove (item);} - public int Count {get {return values.Count;}} - public bool IsReadOnly {get {return false;}} - #endregion - - #region IEnumerable - IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} - #endregion - - #region IEnumerable<T> - public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();} - #endregion - - #region IList - int IList.Add (object value) {return (values as IList).Add (value);} - bool IList.Contains (object value) {return (values as IList).Contains (value);} - int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} - void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} - void IList.Remove (object value) {(values as IList).Remove (value);} - void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} - bool IList.IsFixedSize {get {return false;}} - object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}} - #endregion - - #region IList<T> - public int IndexOf (string item) {return values.IndexOf (item);} - public void Insert (int index, string item) {values.Insert (index, item);} - public void RemoveAt (int index) {values.RemoveAt (index);} - - private void AssertValid (int index) - { - if (c.Option == null) - throw new InvalidOperationException ("OptionContext.Option is null."); - if (index >= c.Option.MaxValueCount) - throw new ArgumentOutOfRangeException ("index"); - if (c.Option.OptionValueType == OptionValueType.Required && - index >= values.Count) - throw new OptionException (string.Format ( - c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), - c.OptionName); - } - - public string this [int index] { - get { - AssertValid (index); - return index >= values.Count ? null : values [index]; - } - set { - values [index] = value; - } - } - #endregion - - public List<string> ToList () - { - return new List<string> (values); - } - - public string[] ToArray () - { - return values.ToArray (); - } - - public override string ToString () - { - return string.Join (", ", values.ToArray ()); - } - } - - public class OptionContext { - private Option option; - private string name; - private int index; - private OptionSet set; - private OptionValueCollection c; - - public OptionContext (OptionSet set) - { - this.set = set; - this.c = new OptionValueCollection (this); - } - - public Option Option { - get {return option;} - set {option = value;} - } - - public string OptionName { - get {return name;} - set {name = value;} - } - - public int OptionIndex { - get {return index;} - set {index = value;} - } - - public OptionSet OptionSet { - get {return set;} - } - - public OptionValueCollection OptionValues { - get {return c;} - } - } - - public enum OptionValueType { - None, - Optional, - Required, - } - - public abstract class Option { - string prototype, description; - string[] names; - OptionValueType type; - int count; - string[] separators; - - protected Option (string prototype, string description) - : this (prototype, description, 1) - { - } - - protected Option (string prototype, string description, int maxValueCount) - { - if (prototype == null) - throw new ArgumentNullException ("prototype"); - if (prototype.Length == 0) - throw new ArgumentException ("Cannot be the empty string.", "prototype"); - if (maxValueCount < 0) - throw new ArgumentOutOfRangeException ("maxValueCount"); - - this.prototype = prototype; - this.names = prototype.Split ('|'); - this.description = description; - this.count = maxValueCount; - this.type = ParsePrototype (); - - if (this.count == 0 && type != OptionValueType.None) - throw new ArgumentException ( - "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + - "OptionValueType.Optional.", - "maxValueCount"); - if (this.type == OptionValueType.None && maxValueCount > 1) - throw new ArgumentException ( - string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), - "maxValueCount"); - if (Array.IndexOf (names, "<>") >= 0 && - ((names.Length == 1 && this.type != OptionValueType.None) || - (names.Length > 1 && this.MaxValueCount > 1))) - throw new ArgumentException ( - "The default option handler '<>' cannot require values.", - "prototype"); - } - - public string Prototype {get {return prototype;}} - public string Description {get {return description;}} - public OptionValueType OptionValueType {get {return type;}} - public int MaxValueCount {get {return count;}} - - public string[] GetNames () - { - return (string[]) names.Clone (); - } - - public string[] GetValueSeparators () - { - if (separators == null) - return new string [0]; - return (string[]) separators.Clone (); - } - - protected static T Parse<T> (string value, OptionContext c) - { - Type tt = typeof (T); - bool nullable = tt.IsValueType && tt.IsGenericType && - !tt.IsGenericTypeDefinition && - tt.GetGenericTypeDefinition () == typeof (Nullable<>); - Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T); - TypeConverter conv = TypeDescriptor.GetConverter (targetType); - T t = default (T); - try { - if (value != null) - t = (T) conv.ConvertFromString (value); - } - catch (Exception e) { - throw new OptionException ( - string.Format ( - c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."), - value, targetType.Name, c.OptionName), - c.OptionName, e); - } - return t; - } - - internal string[] Names {get {return names;}} - internal string[] ValueSeparators {get {return separators;}} - - static readonly char[] NameTerminator = new char[]{'=', ':'}; - - private OptionValueType ParsePrototype () - { - char type = '\0'; - List<string> seps = new List<string> (); - for (int i = 0; i < names.Length; ++i) { - string name = names [i]; - if (name.Length == 0) - throw new ArgumentException ("Empty option names are not supported.", "prototype"); - - int end = name.IndexOfAny (NameTerminator); - if (end == -1) - continue; - names [i] = name.Substring (0, end); - if (type == '\0' || type == name [end]) - type = name [end]; - else - throw new ArgumentException ( - string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]), - "prototype"); - AddSeparators (name, end, seps); - } - - if (type == '\0') - return OptionValueType.None; - - if (count <= 1 && seps.Count != 0) - throw new ArgumentException ( - string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count), - "prototype"); - if (count > 1) { - if (seps.Count == 0) - this.separators = new string[]{":", "="}; - else if (seps.Count == 1 && seps [0].Length == 0) - this.separators = null; - else - this.separators = seps.ToArray (); - } - - return type == '=' ? OptionValueType.Required : OptionValueType.Optional; - } - - private static void AddSeparators (string name, int end, ICollection<string> seps) - { - int start = -1; - for (int i = end+1; i < name.Length; ++i) { - switch (name [i]) { - case '{': - if (start != -1) - throw new ArgumentException ( - string.Format ("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - start = i+1; - break; - case '}': - if (start == -1) - throw new ArgumentException ( - string.Format ("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - seps.Add (name.Substring (start, i-start)); - start = -1; - break; - default: - if (start == -1) - seps.Add (name [i].ToString ()); - break; - } - } - if (start != -1) - throw new ArgumentException ( - string.Format ("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - } - - public void Invoke (OptionContext c) - { - OnParseComplete (c); - c.OptionName = null; - c.Option = null; - c.OptionValues.Clear (); - } - - protected abstract void OnParseComplete (OptionContext c); - - public override string ToString () - { - return Prototype; - } - } - - [Serializable] - public class OptionException : Exception { - private string option; - - public OptionException () - { - } - - public OptionException (string message, string optionName) - : base (message) - { - this.option = optionName; - } - - public OptionException (string message, string optionName, Exception innerException) - : base (message, innerException) - { - this.option = optionName; - } - - protected OptionException (SerializationInfo info, StreamingContext context) - : base (info, context) - { - this.option = info.GetString ("OptionName"); - } - - public string OptionName { - get {return this.option;} - } - - [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] - public override void GetObjectData (SerializationInfo info, StreamingContext context) - { - base.GetObjectData (info, context); - info.AddValue ("OptionName", option); - } - } - - public delegate void OptionAction<TKey, TValue> (TKey key, TValue value); - - public class OptionSet : KeyedCollection<string, Option> - { - public OptionSet () - : this (delegate (string f) {return f;}) - { - } - - public OptionSet (Converter<string, string> localizer) - { - this.localizer = localizer; - } - - Converter<string, string> localizer; - - public Converter<string, string> MessageLocalizer { - get {return localizer;} - } - - protected override string GetKeyForItem (Option item) - { - if (item == null) - throw new ArgumentNullException ("option"); - if (item.Names != null && item.Names.Length > 0) - return item.Names [0]; - // This should never happen, as it's invalid for Option to be - // constructed w/o any names. - throw new InvalidOperationException ("Option has no names!"); - } - - protected override void InsertItem (int index, Option item) - { - base.InsertItem (index, item); - AddImpl (item); - } - - protected override void RemoveItem (int index) - { - base.RemoveItem (index); - Option p = Items [index]; - // KeyedCollection.RemoveItem() handles the 0th item - for (int i = 1; i < p.Names.Length; ++i) { - Dictionary.Remove (p.Names [i]); - } - } - - protected override void SetItem (int index, Option item) - { - base.SetItem (index, item); - RemoveItem (index); - AddImpl (item); - } - - private void AddImpl (Option option) - { - if (option == null) - throw new ArgumentNullException ("option"); - List<string> added = new List<string> (option.Names.Length); - try { - // KeyedCollection.InsertItem/SetItem handle the 0th name. - for (int i = 1; i < option.Names.Length; ++i) { - Dictionary.Add (option.Names [i], option); - added.Add (option.Names [i]); - } - } - catch (Exception) { - foreach (string name in added) - Dictionary.Remove (name); - throw; - } - } - - public new OptionSet Add (Option option) - { - base.Add (option); - return this; - } - - sealed class ActionOption : Option { - Action<OptionValueCollection> action; - - public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action) - : base (prototype, description, count) - { - if (action == null) - throw new ArgumentNullException ("action"); - this.action = action; - } - - protected override void OnParseComplete (OptionContext c) - { - action (c.OptionValues); - } - } - - public OptionSet Add (string prototype, Action<string> action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, Action<string> action) - { - if (action == null) - throw new ArgumentNullException ("action"); - Option p = new ActionOption (prototype, description, 1, - delegate (OptionValueCollection v) { action (v [0]); }); - base.Add (p); - return this; - } - - public OptionSet Add (string prototype, OptionAction<string, string> action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, OptionAction<string, string> action) - { - if (action == null) - throw new ArgumentNullException ("action"); - Option p = new ActionOption (prototype, description, 2, - delegate (OptionValueCollection v) {action (v [0], v [1]);}); - base.Add (p); - return this; - } - - sealed class ActionOption<T> : Option { - Action<T> action; - - public ActionOption (string prototype, string description, Action<T> action) - : base (prototype, description, 1) - { - if (action == null) - throw new ArgumentNullException ("action"); - this.action = action; - } - - protected override void OnParseComplete (OptionContext c) - { - action (Parse<T> (c.OptionValues [0], c)); - } - } - - sealed class ActionOption<TKey, TValue> : Option { - OptionAction<TKey, TValue> action; - - public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action) - : base (prototype, description, 2) - { - if (action == null) - throw new ArgumentNullException ("action"); - this.action = action; - } - - protected override void OnParseComplete (OptionContext c) - { - action ( - Parse<TKey> (c.OptionValues [0], c), - Parse<TValue> (c.OptionValues [1], c)); - } - } - - public OptionSet Add<T> (string prototype, Action<T> action) - { - return Add (prototype, null, action); - } - - public OptionSet Add<T> (string prototype, string description, Action<T> action) - { - return Add (new ActionOption<T> (prototype, description, action)); - } - - public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action) - { - return Add (prototype, null, action); - } - - public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action) - { - return Add (new ActionOption<TKey, TValue> (prototype, description, action)); - } - - protected virtual OptionContext CreateOptionContext () - { - return new OptionContext (this); - } - -#if LINQ - public List<string> Parse (IEnumerable<string> arguments) - { - bool process = true; - OptionContext c = CreateOptionContext (); - c.OptionIndex = -1; - var def = GetOptionForName ("<>"); - var unprocessed = - from argument in arguments - where ++c.OptionIndex >= 0 && (process || def != null) - ? process - ? argument == "--" - ? (process = false) - : !Parse (argument, c) - ? def != null - ? Unprocessed (null, def, c, argument) - : true - : false - : def != null - ? Unprocessed (null, def, c, argument) - : true - : true - select argument; - List<string> r = unprocessed.ToList (); - if (c.Option != null) - c.Option.Invoke (c); - return r; - } -#else - public List<string> Parse (IEnumerable<string> arguments) - { - OptionContext c = CreateOptionContext (); - c.OptionIndex = -1; - bool process = true; - List<string> unprocessed = new List<string> (); - Option def = Contains ("<>") ? this ["<>"] : null; - foreach (string argument in arguments) { - ++c.OptionIndex; - if (argument == "--") { - process = false; - continue; - } - if (!process) { - Unprocessed (unprocessed, def, c, argument); - continue; - } - if (!Parse (argument, c)) - Unprocessed (unprocessed, def, c, argument); - } - if (c.Option != null) - c.Option.Invoke (c); - return unprocessed; - } -#endif - - private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument) - { - if (def == null) { - extra.Add (argument); - return false; - } - c.OptionValues.Add (argument); - c.Option = def; - c.Option.Invoke (c); - return false; - } - - private readonly Regex ValueOption = new Regex ( - @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$"); - - protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) - { - if (argument == null) - throw new ArgumentNullException ("argument"); - - flag = name = sep = value = null; - Match m = ValueOption.Match (argument); - if (!m.Success) { - return false; - } - flag = m.Groups ["flag"].Value; - name = m.Groups ["name"].Value; - if (m.Groups ["sep"].Success && m.Groups ["value"].Success) { - sep = m.Groups ["sep"].Value; - value = m.Groups ["value"].Value; - } - return true; - } - - protected virtual bool Parse (string argument, OptionContext c) - { - if (c.Option != null) { - ParseValue (argument, c); - return true; - } - - string f, n, s, v; - if (!GetOptionParts (argument, out f, out n, out s, out v)) - return false; - - Option p; - if (Contains (n)) { - p = this [n]; - c.OptionName = f + n; - c.Option = p; - switch (p.OptionValueType) { - case OptionValueType.None: - c.OptionValues.Add (n); - c.Option.Invoke (c); - break; - case OptionValueType.Optional: - case OptionValueType.Required: - ParseValue (v, c); - break; - } - return true; - } - // no match; is it a bool option? - if (ParseBool (argument, n, c)) - return true; - // is it a bundled option? - if (ParseBundledValue (f, string.Concat (n + s + v), c)) - return true; - - return false; - } - - private void ParseValue (string option, OptionContext c) - { - if (option != null) - foreach (string o in c.Option.ValueSeparators != null - ? option.Split (c.Option.ValueSeparators, StringSplitOptions.None) - : new string[]{option}) { - c.OptionValues.Add (o); - } - if (c.OptionValues.Count == c.Option.MaxValueCount || - c.Option.OptionValueType == OptionValueType.Optional) - c.Option.Invoke (c); - else if (c.OptionValues.Count > c.Option.MaxValueCount) { - throw new OptionException (localizer (string.Format ( - "Error: Found {0} option values when expecting {1}.", - c.OptionValues.Count, c.Option.MaxValueCount)), - c.OptionName); - } - } - - private bool ParseBool (string option, string n, OptionContext c) - { - Option p; - string rn; - if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') && - Contains ((rn = n.Substring (0, n.Length-1)))) { - p = this [rn]; - string v = n [n.Length-1] == '+' ? option : null; - c.OptionName = option; - c.Option = p; - c.OptionValues.Add (v); - p.Invoke (c); - return true; - } - return false; - } - - private bool ParseBundledValue (string f, string n, OptionContext c) - { - if (f != "-") - return false; - for (int i = 0; i < n.Length; ++i) { - Option p; - string opt = f + n [i].ToString (); - string rn = n [i].ToString (); - if (!Contains (rn)) { - if (i == 0) - return false; - throw new OptionException (string.Format (localizer ( - "Cannot bundle unregistered option '{0}'."), opt), opt); - } - p = this [rn]; - switch (p.OptionValueType) { - case OptionValueType.None: - Invoke (c, opt, n, p); - break; - case OptionValueType.Optional: - case OptionValueType.Required: { - string v = n.Substring (i+1); - c.Option = p; - c.OptionName = opt; - ParseValue (v.Length != 0 ? v : null, c); - return true; - } - default: - throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType); - } - } - return true; - } - - private static void Invoke (OptionContext c, string name, string value, Option option) - { - c.OptionName = name; - c.Option = option; - c.OptionValues.Add (value); - option.Invoke (c); - } - - private const int OptionWidth = 29; - - public void WriteOptionDescriptions (TextWriter o) - { - foreach (Option p in this) { - int written = 0; - if (!WriteOptionPrototype (o, p, ref written)) - continue; - - if (written < OptionWidth) - o.Write (new string (' ', OptionWidth - written)); - else { - o.WriteLine (); - o.Write (new string (' ', OptionWidth)); - } - - List<string> lines = GetLines (localizer (GetDescription (p.Description))); - o.WriteLine (lines [0]); - string prefix = new string (' ', OptionWidth+2); - for (int i = 1; i < lines.Count; ++i) { - o.Write (prefix); - o.WriteLine (lines [i]); - } - } - } - - bool WriteOptionPrototype (TextWriter o, Option p, ref int written) - { - string[] names = p.Names; - - int i = GetNextOptionIndex (names, 0); - if (i == names.Length) - return false; - - if (names [i].Length == 1) { - Write (o, ref written, " -"); - Write (o, ref written, names [0]); - } - else { - Write (o, ref written, " --"); - Write (o, ref written, names [0]); - } - - for ( i = GetNextOptionIndex (names, i+1); - i < names.Length; i = GetNextOptionIndex (names, i+1)) { - Write (o, ref written, ", "); - Write (o, ref written, names [i].Length == 1 ? "-" : "--"); - Write (o, ref written, names [i]); - } - - if (p.OptionValueType == OptionValueType.Optional || - p.OptionValueType == OptionValueType.Required) { - if (p.OptionValueType == OptionValueType.Optional) { - Write (o, ref written, localizer ("[")); - } - Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); - string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 - ? p.ValueSeparators [0] - : " "; - for (int c = 1; c < p.MaxValueCount; ++c) { - Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); - } - if (p.OptionValueType == OptionValueType.Optional) { - Write (o, ref written, localizer ("]")); - } - } - return true; - } - - static int GetNextOptionIndex (string[] names, int i) - { - while (i < names.Length && names [i] == "<>") { - ++i; - } - return i; - } - - static void Write (TextWriter o, ref int n, string s) - { - n += s.Length; - o.Write (s); - } - - private static string GetArgumentName (int index, int maxIndex, string description) - { - if (description == null) - return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); - string[] nameStart; - if (maxIndex == 1) - nameStart = new string[]{"{0:", "{"}; - else - nameStart = new string[]{"{" + index + ":"}; - for (int i = 0; i < nameStart.Length; ++i) { - int start, j = 0; - do { - start = description.IndexOf (nameStart [i], j); - } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false); - if (start == -1) - continue; - int end = description.IndexOf ("}", start); - if (end == -1) - continue; - return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length); - } - return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); - } - - private static string GetDescription (string description) - { - if (description == null) - return string.Empty; - StringBuilder sb = new StringBuilder (description.Length); - int start = -1; - for (int i = 0; i < description.Length; ++i) { - switch (description [i]) { - case '{': - if (i == start) { - sb.Append ('{'); - start = -1; - } - else if (start < 0) - start = i + 1; - break; - case '}': - if (start < 0) { - if ((i+1) == description.Length || description [i+1] != '}') - throw new InvalidOperationException ("Invalid option description: " + description); - ++i; - sb.Append ("}"); - } - else { - sb.Append (description, start, i - start); - start = -1; - } - break; - case ':': - if (start < 0) - goto default; - start = i + 1; - break; - default: - if (start < 0) - sb.Append (description [i]); - break; - } - } - return sb.ToString (); - } - - private static List<string> GetLines (string description) - { - List<string> lines = new List<string> (); - if (string.IsNullOrEmpty (description)) { - lines.Add (string.Empty); - return lines; - } - int length = 80 - OptionWidth - 2; - int start = 0, end; - do { - end = GetLineEnd (start, length, description); - bool cont = false; - if (end < description.Length) { - char c = description [end]; - if (c == '-' || (char.IsWhiteSpace (c) && c != '\n')) - ++end; - else if (c != '\n') { - cont = true; - --end; - } - } - lines.Add (description.Substring (start, end - start)); - if (cont) { - lines [lines.Count-1] += "-"; - } - start = end; - if (start < description.Length && description [start] == '\n') - ++start; - } while (end < description.Length); - return lines; - } - - private static int GetLineEnd (int start, int length, string description) - { - int end = System.Math.Min (start + length, description.Length); - int sep = -1; - for (int i = start; i < end; ++i) { - switch (description [i]) { - case ' ': - case '\t': - case '\v': - case '-': - case ',': - case '.': - case ';': - sep = i; - break; - case '\n': - return i; - } - } - if (sep == -1 || end == description.Length) - return end; - return sep; - } - } -} - diff --git a/main/src/addins/TextTemplating/TextTransform/TextTransform.cs b/main/src/addins/TextTemplating/TextTransform/TextTransform.cs deleted file mode 100644 index 914b739fe9..0000000000 --- a/main/src/addins/TextTemplating/TextTransform/TextTransform.cs +++ /dev/null @@ -1,171 +0,0 @@ -// -// Main.cs -// -// Author: -// Michael Hutchinson <mhutchinson@novell.com> -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.IO; -using System.Collections.Generic; -using Mono.Options; - -namespace Mono.TextTemplating -{ - class TextTransform - { - static OptionSet optionSet; - const string name ="TextTransform.exe"; - - public static int Main (string[] args) - {
- try {
- return MainInternal(args);
- }
- catch (Exception e) {
- Console.Error.WriteLine(e);
- return -1;
- }
- } - - private static int MainInternal (string[] args) - { - if (args.Length == 0) { - ShowHelp (true); - } - - var generator = new TemplateGenerator (); - string outputFile = null, inputFile = null; - var directives = new List<string> (); - var parameters = new List<string> (); - // var session = new Microsoft.VisualStudio.TextTemplating.TextTemplatingSession (); - string preprocess = null; - - optionSet = new OptionSet () { - { "o=|out=", "The name of the output {file}", s => outputFile = s }, - { "r=", "Assemblies to reference", s => generator.Refs.Add (s) }, - { "u=", "Namespaces to import <{0:namespace}>", s => generator.Imports.Add (s) }, - { "I=", "Paths to search for included files", s => generator.IncludePaths.Add (s) }, - { "P=", "Paths to search for referenced assemblies", s => generator.ReferencePaths.Add (s) }, - { "dp=", "Directive processor (name!class!assembly)", s => directives.Add (s) }, - { "a=", "Parameters (name=value) or ([processorName!][directiveName!]name!value)", s => parameters.Add (s) }, - { "h|?|help", "Show help", s => ShowHelp (false) }, - // { "k=,", "Session {key},{value} pairs", (s, t) => session.Add (s, t) }, - { "c=", "Preprocess the template into {0:class}", (s) => preprocess = s }, - }; - - var remainingArgs = optionSet.Parse (args); - - if (remainingArgs.Count != 1) { - Console.Error.WriteLine ("No input file specified."); - return -1; - } - inputFile = remainingArgs [0]; - - if (!File.Exists (inputFile)) { - Console.Error.WriteLine ("Input file '{0}' does not exist.", inputFile); - return -1; - } - - if (string.IsNullOrEmpty (outputFile)) { - outputFile = inputFile; - if (Path.HasExtension (outputFile)) { - var dir = Path.GetDirectoryName (outputFile); - var fn = Path.GetFileNameWithoutExtension (outputFile); - outputFile = Path.Combine (dir, fn + ".txt"); - } else { - outputFile = outputFile + ".txt"; - } - } - - foreach (var par in parameters) { - if (!generator.TryAddParameter (par)) { - Console.Error.WriteLine ("Parameter has incorrect format: {0}", par); - return -1; - } - } - - foreach (var dir in directives) { - var split = dir.Split ('!'); - - if (split.Length != 3) { - Console.Error.WriteLine ("Directive must have 3 values: {0}", dir); - return -1; - } - - for (int i = 0; i < 3; i++) { - string s = split [i]; - if (string.IsNullOrEmpty (s)) { - string kind = i == 0? "name" : (i == 1 ? "class" : "assembly"); - Console.Error.WriteLine ("Directive has missing {0} value: {1}", kind, dir); - return -1; - } - } - - generator.AddDirectiveProcessor (split[0], split[1], split[2]); - } - - if (preprocess == null) { - generator.ProcessTemplate (inputFile, outputFile); - if (generator.Errors.HasErrors) { - Console.WriteLine ("Processing '{0}' failed.", inputFile); - } - } else { - string className = preprocess; - string classNamespace = null; - int s = preprocess.LastIndexOf ('.'); - if (s > 0) { - classNamespace = preprocess.Substring (0, s); - className = preprocess.Substring (s + 1); - } - - string language; - string[] references; - generator.PreprocessTemplate (inputFile, className, classNamespace, outputFile, System.Text.Encoding.UTF8, - out language, out references); - if (generator.Errors.HasErrors) { - Console.Write ("Preprocessing '{0}' into class '{1}.{2}' failed.", inputFile, classNamespace, className); - } - } - - foreach (System.CodeDom.Compiler.CompilerError err in generator.Errors) - Console.Error.WriteLine ("{0}({1},{2}): {3} {4}", err.FileName, err.Line, err.Column, - err.IsWarning? "WARNING" : "ERROR", err.ErrorText); - - return generator.Errors.HasErrors? -1 : 0; - } - - static void ShowHelp (bool concise) - { - Console.WriteLine ("TextTransform command line T4 processor"); - Console.WriteLine ("Usage: {0} [options] input-file", name); - if (concise) { - Console.WriteLine ("Use --help to display options."); - } else { - Console.WriteLine ("Options:"); - optionSet.WriteOptionDescriptions (System.Console.Out); - } - Console.WriteLine (); - Environment.Exit (0); - } - } -}
\ No newline at end of file diff --git a/main/src/addins/TextTemplating/TextTransform/TextTransform.csproj b/main/src/addins/TextTemplating/TextTransform/TextTransform.csproj deleted file mode 100644 index 4664b454d6..0000000000 --- a/main/src/addins/TextTemplating/TextTransform/TextTransform.csproj +++ /dev/null @@ -1,55 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0"> - <Import Project="..\..\..\..\MonoDevelop.props" /> - <PropertyGroup> - <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> - <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> - <ProductVersion>8.0.30703</ProductVersion> - <SchemaVersion>2.0</SchemaVersion> - <ProjectGuid>{D1D35409-C814-47F6-B038-B9B5BF0FE490}</ProjectGuid> - <OutputType>Exe</OutputType> - <AssemblyName>TextTransform</AssemblyName> - <RootNamespace>Mono.TextTemplating</RootNamespace> - <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> - <DebugSymbols>True</DebugSymbols> - <DebugType>full</DebugType> - <Optimize>False</Optimize> - <OutputPath>..\..\..\..\build\AddIns\MonoDevelop.TextTemplating</OutputPath> - <DefineConstants>DEBUG</DefineConstants> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - <Commandlineparameters>-o:out.txt in.tt</Commandlineparameters> - <NoWarn>1591;1573</NoWarn> - <DocumentationFile>..\..\..\..\build\AddIns\MonoDevelop.TextTemplating\TextTransform.xml</DocumentationFile> - </PropertyGroup> - <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - <DebugType>pdbonly</DebugType> - <Optimize>true</Optimize> - <OutputPath>..\..\..\..\build\AddIns\MonoDevelop.TextTemplating</OutputPath> - <ErrorReport>prompt</ErrorReport> - <WarningLevel>4</WarningLevel> - <DebugSymbols>true</DebugSymbols> - <NoWarn>1591;1573</NoWarn> - <DocumentationFile>..\..\..\..\build\AddIns\MonoDevelop.TextTemplating\TextTransform.xml</DocumentationFile> - <Commandlineparameters>-o:out.txt in.tt</Commandlineparameters> - </PropertyGroup> - <ItemGroup> - <Reference Include="System" /> - <Reference Include="System.Core" /> - </ItemGroup> - <ItemGroup> - <Compile Include="TextTransform.cs" /> - <Compile Include="AssemblyInfo.cs" /> - <Compile Include="Options.cs" /> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\Mono.TextTemplating\Mono.TextTemplating.csproj"> - <Project>{A2364D6A-00EF-417C-80A6-815726C70032}</Project> - <Name>Mono.TextTemplating</Name> - <Private>False</Private> - </ProjectReference> - </ItemGroup> - <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> -</Project> |