diff --git a/CHANGELOG.md b/CHANGELOG.md index ef9a60d276..07887cc088 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - Ported build system module to new CodeWriter. [#1242](https://github.com/spatialos/gdk-for-unity/pull/1242) - Ported gameobject creation module to new CodeWriter. [#1247](https://github.com/spatialos/gdk-for-unity/pull/1247) - Ported core module to new CodeWriter. [#1247](https://github.com/spatialos/gdk-for-unity/pull/1247) [#1248](https://github.com/spatialos/gdk-for-unity/pull/1248) [#1249](https://github.com/spatialos/gdk-for-unity/pull/1249) [#1251](https://github.com/spatialos/gdk-for-unity/pull/1251) [#1252](https://github.com/spatialos/gdk-for-unity/pull/1252) [#1253](https://github.com/spatialos/gdk-for-unity/pull/1253) +- Removed all Text Template Transformation Toolkit (T4) references and dependencies. [#1254](https://github.com/spatialos/gdk-for-unity/pull/1254) ## `0.3.2` - 2019-12-23 diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/CodeGenT4.DotSettings b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/CodeGenT4.DotSettings deleted file mode 100644 index 28910ba2f9..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/CodeGenT4.DotSettings +++ /dev/null @@ -1,8 +0,0 @@ - - True - True - ..\..\..\..\..\..\ReSharper2017.DotSettings - True - 1 - True - True diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/CodeGenT4.sln b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/CodeGenT4.sln deleted file mode 100644 index 2c226d7616..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/CodeGenT4.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27428.2015 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mono.TextTemplating", "Mono.TextTemplating\Mono.TextTemplating.csproj", "{79A38ECA-045D-4C5A-A180-E3E0B37ADFB9}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Improbable.TextTemplating", "Improbable.TextTemplating\Improbable.TextTemplating.csproj", "{69CD28E2-1217-47A9-BFFE-6D82701C4839}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {79A38ECA-045D-4C5A-A180-E3E0B37ADFB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {79A38ECA-045D-4C5A-A180-E3E0B37ADFB9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {79A38ECA-045D-4C5A-A180-E3E0B37ADFB9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {79A38ECA-045D-4C5A-A180-E3E0B37ADFB9}.Release|Any CPU.Build.0 = Release|Any CPU - {69CD28E2-1217-47A9-BFFE-6D82701C4839}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {69CD28E2-1217-47A9-BFFE-6D82701C4839}.Debug|Any CPU.Build.0 = Debug|Any CPU - {69CD28E2-1217-47A9-BFFE-6D82701C4839}.Release|Any CPU.ActiveCfg = Release|Any CPU - {69CD28E2-1217-47A9-BFFE-6D82701C4839}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {C66B5E5E-7454-46DB-A4D5-3D9BCCE7CE5B} - EndGlobalSection -EndGlobal diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Improbable.TextTemplating/Improbable.TextTemplating.csproj b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Improbable.TextTemplating/Improbable.TextTemplating.csproj deleted file mode 100644 index 7866f59a7f..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Improbable.TextTemplating/Improbable.TextTemplating.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - netstandard2.0 - false - - - - - - - - - - - - - - - - - diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Improbable.TextTemplating/TransformAllTask.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Improbable.TextTemplating/TransformAllTask.cs deleted file mode 100644 index 98770911ac..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Improbable.TextTemplating/TransformAllTask.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using Mono.TextTemplating; - -namespace Improbable.TextTemplating -{ - public class TransformAllTask : Task - { - [Required] - public string[] Imports { get; set; } - - [Required] - public ITaskItem[] InputFiles { get; set; } - - [Required] - public ITaskItem ProjectDirectory { get; set; } - - [Required] - public string ClassNameSpace { get; set; } - - [Output] - public ITaskItem[] OutputFiles { get; set; } - - public override bool Execute() - { - if (InputFiles.Length < 1) - { - Log.LogError("No template files were specified in the InputFiles parameter."); - return false; - } - - string generatedPath = Path.Combine(ProjectDirectory.ItemSpec, "Generated"); - Log.LogMessage(MessageImportance.Normal, "Generated files will be output to directory: {0}", generatedPath); - - if (Directory.Exists(generatedPath)) - { - Directory.Delete(generatedPath, true); - } - - Directory.CreateDirectory(generatedPath); - - var source = new List(); - var failed = false; - foreach (ITaskItem inputFile in InputFiles) - { - var itemSpec = inputFile.ItemSpec; - var withoutExtension = Path.GetFileNameWithoutExtension(itemSpec); - var path2 = $"{withoutExtension}.cs"; - var outputFile = Path.Combine(generatedPath, path2); - var templateGenerator = new TemplateGenerator(); - templateGenerator.Imports.AddRange(Imports); - - templateGenerator.PreprocessTemplate(itemSpec, withoutExtension, ClassNameSpace, outputFile, Encoding.UTF8, - out var language, out var references); - - failed |= templateGenerator.Errors.HasErrors; - - source.Add(outputFile); - Log.LogMessage(MessageImportance.Normal, "Transformed template {0} into generator: {1}", - Path.GetFileName(itemSpec), path2); - } - - OutputFiles = source - .Select(name => new TaskItem(name)) - .ToArray(); - - Log.LogMessage(MessageImportance.Normal, "Finished transforming template files."); - return !failed; - } - } -} diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/AssemblyInfo.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/AssemblyInfo.cs deleted file mode 100644 index df20767722..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/AssemblyInfo.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -// AssemblyInfo.cs -// -// Author: -// Mikayla Hutchinson -// -// 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.Runtime.CompilerServices; - -[assembly: - InternalsVisibleTo( - "Mono.TextTemplating.Tests,PublicKey=0024000004800000940000000602000000240000525341310004000001000100490b59506a03eb5fc5524722a6526eff804b7880a968a581a0bbb73cd6ab93c7b94a14150cb4ea40f610bebf607cea5e8a93ef25d124983300f4bdfe44859430a20a4ed2ac32cfd3a6f0aa12702df819b7799cc0fcf077eea706a27252d59a8a10e5164c2cdddd6680ca76b02ca244e83c1a8cc44b2691052b93ab30bcc613ad")] diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessor.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessor.cs deleted file mode 100644 index b922451254..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessor.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -// DirectiveProcessor.cs -// -// Author: -// Mikayla Hutchinson -// -// 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; -using System.CodeDom.Compiler; -using System.Collections.Generic; - -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 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/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessorException.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessorException.cs deleted file mode 100644 index d7766dcdcd..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/DirectiveProcessorException.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -// DirectiveProcessorException.cs -// -// Author: -// Mikayla Hutchinson -// -// 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/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/EncodingHelper.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/EncodingHelper.cs deleted file mode 100644 index 64333383ad..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/EncodingHelper.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -// EncodingHelper.cs -// -// Author: -// Mikayla Hutchinson -// -// 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 -{ - [Obsolete("Not implemented")] - public static class EncodingHelper - { - public static Encoding GetEncoding(string filePath) - { - throw new NotImplementedException(); - } - } -} diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Engine.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Engine.cs deleted file mode 100644 index 37f0fc0c7d..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Engine.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -// Engine.cs -// -// Author: -// Mikayla Hutchinson -// -// 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 Mono.TextTemplating; - -namespace Microsoft.VisualStudio.TextTemplating -{ - [Obsolete("Use Mono.TextTemplating.TemplatingEngine directly")] - public class Engine : ITextTemplatingEngine - { - TemplatingEngine engine = new TemplatingEngine(); - - 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/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Interfaces.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Interfaces.cs deleted file mode 100644 index 5af8be2965..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/Interfaces.cs +++ /dev/null @@ -1,107 +0,0 @@ -// -// ITextTemplatingEngineHost.cs -// -// Author: -// Mikayla Hutchinson -// -// 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.CodeDom; -using System.CodeDom.Compiler; -using System.Collections; -using System.Collections.Generic; -using System.Runtime.Serialization; -using System.Text; - -namespace Microsoft.VisualStudio.TextTemplating -{ - public interface IRecognizeHostSpecific - { - void SetProcessingRunIsHostSpecific(bool hostSpecific); - bool RequiresProcessingRunIsHostSpecific { get; } - } - - [Obsolete("Use Mono.TextTemplating.TemplatingEngine directly")] - 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); - } - - public interface ITextTemplatingEngineHost - { - object GetHostOption(string optionName); - bool LoadIncludeText(string requestFileName, out string content, out string location); - void LogErrors(CompilerErrorCollection errors); - //FIXME: this break binary compat -#if FEATURE_APPDOMAINS - AppDomain ProvideTemplatingAppDomain (string content); -#endif - 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 StandardAssemblyReferences { get; } - IList StandardImports { get; } - string TemplateFile { get; } - } - - public interface ITextTemplatingSession : - IEquatable, IEquatable, IDictionary, - ICollection>, - IEnumerable>, - IEnumerable, ISerializable - { - Guid Id { get; } - } - - 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 arguments); - void SetProcessingRunIsHostSpecific(bool hostSpecific); - - void StartProcessingRun(CodeDomProvider languageProvider, string templateContents, - CompilerErrorCollection errors); - } -} diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ParameterDirectiveProcessor.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ParameterDirectiveProcessor.cs deleted file mode 100644 index 515bd0f36e..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ParameterDirectiveProcessor.cs +++ /dev/null @@ -1,224 +0,0 @@ -// -// ParameterDirectiveProcessor.cs -// -// Author: -// Mikayla Hutchinson -// -// 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 postStatements = new List(); - readonly List members = new List(); - - 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 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 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/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/RequiresProvidesDirectiveProcessor.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/RequiresProvidesDirectiveProcessor.cs deleted file mode 100644 index a4f327c8fd..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/RequiresProvidesDirectiveProcessor.cs +++ /dev/null @@ -1,214 +0,0 @@ -// -// RequiresProvidesDirectiveProcessor.cs -// -// Author: -// Mikayla Hutchinson -// -// 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 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 providesDictionary); - - protected abstract void InitializeRequiresDictionary(string directiveName, - IDictionary requiresDictionary); - - protected abstract string FriendlyName { get; } - - protected abstract void GeneratePostInitializationCode(string directiveName, StringBuilder codeBuffer, - CodeDomProvider languageProvider, - IDictionary requiresArguments, IDictionary providesArguments); - - protected abstract void GeneratePreInitializationCode(string directiveName, StringBuilder codeBuffer, - CodeDomProvider languageProvider, - IDictionary requiresArguments, IDictionary providesArguments); - - protected abstract void GenerateTransformCode(string directiveName, StringBuilder codeBuffer, - CodeDomProvider languageProvider, - IDictionary requiresArguments, IDictionary providesArguments); - - protected virtual void PostProcessArguments(string directiveName, IDictionary requiresArguments, - IDictionary 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> 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(k, v); - } - } - - public override void ProcessDirective(string directiveName, IDictionary arguments) - { - if (directiveName == null) - throw new ArgumentNullException("directiveName"); - if (arguments == null) - throw new ArgumentNullException("arguments"); - - var providesDictionary = new Dictionary(); - var requiresDictionary = new Dictionary(); - - 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 arguments, - IDictionary requiresArguments, IDictionary providesArguments) - { - return directiveName; - } - - protected ITextTemplatingEngineHost Host - { - get { return host; } - } - } -} diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTemplatingSession.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTemplatingSession.cs deleted file mode 100644 index 084c9b5564..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTemplatingSession.cs +++ /dev/null @@ -1,80 +0,0 @@ -// -// TextTemplatingSession.cs -// -// Author: -// Mikayla Hutchinson -// -// 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.Runtime.Serialization; - -namespace Microsoft.VisualStudio.TextTemplating -{ - [Serializable] - public sealed class TextTemplatingSession : Dictionary, 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/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTransformation.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTransformation.cs deleted file mode 100644 index 6d3b25cff7..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTransformation.cs +++ /dev/null @@ -1,233 +0,0 @@ -// -// TextTransformation.cs -// -// Author: -// Mikayla Hutchinson -// -// 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 indents; - string currentIndent = string.Empty; - CompilerErrorCollection errors; - StringBuilder builder; - bool endsWithNewline; - - public TextTransformation() - { - } - - public virtual void Initialize() - { - } - - public abstract string TransformText(); - - public virtual IDictionary 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 Indents - { - get - { - if (indents == null) - indents = new Stack(); - 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/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ToStringHelper.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ToStringHelper.cs deleted file mode 100644 index 5895db8e43..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/ToStringHelper.cs +++ /dev/null @@ -1,69 +0,0 @@ -// -// ToStringHelper.cs -// -// Author: -// Mikayla Hutchinson -// -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Reflection; - -namespace Microsoft.VisualStudio.TextTemplating -{ - public static class ToStringHelper - { - static readonly 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(nameof(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/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating.csproj b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating.csproj deleted file mode 100644 index 24a26e6fd5..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - netstandard2.0 - true - 1591;1573 - Mono.TextTemplating - Open-source implementation of the T4 templating engine. - $(DefineSymbols);FEATURE_APPDOMAINS - - - - - \ No newline at end of file diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/CompiledTemplate.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/CompiledTemplate.cs deleted file mode 100644 index 8f3135ee76..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/CompiledTemplate.cs +++ /dev/null @@ -1,170 +0,0 @@ -// -// CompiledTemplate.cs -// -// Author: -// Nathan Baulch -// -// 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.CodeDom.Compiler; -using System.Collections.Generic; -using System.Globalization; -using System.Reflection; -using Microsoft.VisualStudio.TextTemplating; - -namespace Mono.TextTemplating -{ - public sealed class CompiledTemplate : -#if FEATURE_APPDOMAINS - MarshalByRefObject, -#endif - IDisposable - { - ITextTemplatingEngineHost host; - object textTransformation; - readonly CultureInfo culture; - readonly string[] assemblyFiles; - - public CompiledTemplate(ITextTemplatingEngineHost host, CompilerResults results, string fullName, - CultureInfo culture, - string[] assemblyFiles) - { -#if FEATURE_APPDOMAINS - AppDomain.CurrentDomain.AssemblyResolve += ResolveReferencedAssemblies; -#endif - 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)); - 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 FEATURE_APPDOMAINS - if (host != null) { - host = null; - AppDomain.CurrentDomain.AssemblyResolve -= ResolveReferencedAssemblies; - } -#endif - } - } -} diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/CrossAppDomainAssemblyResolver.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/CrossAppDomainAssemblyResolver.cs deleted file mode 100644 index 2e371213d2..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/CrossAppDomainAssemblyResolver.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// CrossAppDomainAssemblyResolver.cs -// -// Author: -// Mikayla Hutchinson -// -// 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. - -#if FEATURE_APPDOMAINS -namespace Mono.TextTemplating -{ - /// - /// Provides a handler for AssemblyResolve events that looks them up in the domain that created the resolver. - /// - [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; - } - } - } -} - -#endif diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/FileUtil.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/FileUtil.cs deleted file mode 100644 index 5eb4a3a05c..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/FileUtil.cs +++ /dev/null @@ -1,151 +0,0 @@ -// -// FileUtil.cs -// -// Author: -// Mikayla Hutchinson -// -// 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/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/ParsedTemplate.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/ParsedTemplate.cs deleted file mode 100644 index 0a595c4115..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/ParsedTemplate.cs +++ /dev/null @@ -1,369 +0,0 @@ -// -// Template.cs -// -// Author: -// Mikayla Hutchinson -// -// 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 segments = new List(); - readonly List importedHelperSegments = new List(); - readonly CompilerErrorCollection errors = new CompilerErrorCollection(); - readonly string rootFileName; - - public ParsedTemplate(string rootFileName) - { - this.rootFileName = rootFileName; - } - - public List RawSegments - { - get { return segments; } - } - - public IEnumerable Directives - { - get - { - foreach (ISegment seg in segments) - { - var dir = seg as Directive; - if (dir != null) - yield return dir; - } - } - } - - public IEnumerable 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(StringComparer.OrdinalIgnoreCase); - this.StartLocation = start; - } - - public string Name { get; private set; } - public Dictionary 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 - { - 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/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/RecyclableAppDomain.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/RecyclableAppDomain.cs deleted file mode 100644 index c5740a86d4..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/RecyclableAppDomain.cs +++ /dev/null @@ -1,216 +0,0 @@ -// -// RecyclableAppDomain.cs -// -// Author: -// Mikayla Hutchinson -// -// 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. - -#if FEATURE_APPDOMAINS -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 map = new Dictionary(); - - 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; - } - } - } -} - -#endif diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/TemplateGenerator.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/TemplateGenerator.cs deleted file mode 100644 index 18c616e74d..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/TemplateGenerator.cs +++ /dev/null @@ -1,543 +0,0 @@ -// -// TemplatingHost.cs -// -// Author: -// Mikayla Hutchinson -// -// 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 System.Reflection; -using System.Text; -using Microsoft.VisualStudio.TextTemplating; - -namespace Mono.TextTemplating -{ - public class TemplateGenerator : -#if FEATURE_APPDOMAINS - MarshalByRefObject, -#endif - ITextTemplatingEngineHost - { - //re-usable - TemplatingEngine engine; - - //per-run variables - string inputFile, outputFile; - Encoding encoding; - - //host fields - readonly CompilerErrorCollection errors = new CompilerErrorCollection(); - readonly List refs = new List(); - readonly List imports = new List(); - readonly List includePaths = new List(); - readonly List referencePaths = new List(); - - //host properties for consumers to access - public CompilerErrorCollection Errors - { - get { return errors; } - } - - public List Refs - { - get { return refs; } - } - - public List Imports - { - get { return imports; } - } - - public List IncludePaths - { - get { return includePaths; } - } - - public List 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 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 parameters = new Dictionary(); - - readonly Dictionary> directiveProcessors = - new Dictionary>(); - - public void AddDirectiveProcessor(string name, string klass, string assembly) - { - directiveProcessors.Add(name, new KeyValuePair(klass, assembly)); - } - - public void AddParameter(string processorName, string directiveName, string parameterName, string value) - { - parameters.Add(new ParameterKey(processorName, directiveName, parameterName), value); - } - - /// - /// Parses a parameter and adds it. - /// - /// Whether the parameter was parsed successfully. - /// Parameter in name=value or processor!directive!name!value format. - 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 ITextTemplatingEngineHost.StandardAssemblyReferences - { - get { return refs; } - } - - IList ITextTemplatingEngineHost.StandardImports - { - get { return imports; } - } - - string ITextTemplatingEngineHost.TemplateFile - { - get { return inputFile; } - } - - #endregion - - struct ParameterKey : IEquatable - { - 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; - } - } - - /// - /// If non-null, the template's Host property will be the full type of this host. - /// - public virtual Type SpecificHostType - { - get { return null; } - } - - /// - /// Gets any additional directive processors to be included in the processing run. - /// - public virtual IEnumerable GetAdditionalDirectiveProcessors() - { - yield break; - } - } -} diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/TemplateSettings.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/TemplateSettings.cs deleted file mode 100644 index 66f01285cd..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/TemplateSettings.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -// TemplateSettings.cs -// -// Author: -// Mikayla Hutchinson -// -// 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.Text; -using Microsoft.VisualStudio.TextTemplating; - -namespace Mono.TextTemplating -{ - public class TemplateSettings - { - public TemplateSettings() - { - Imports = new HashSet(); - Assemblies = new HashSet(); - CustomDirectives = new List(); - DirectiveProcessors = new Dictionary(); - } - - 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 Imports { get; private set; } - public HashSet 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 CustomDirectives { get; private set; } - public Dictionary 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/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/TemplatingEngine.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/TemplatingEngine.cs deleted file mode 100644 index 960f1782f1..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/TemplatingEngine.cs +++ /dev/null @@ -1,1357 +0,0 @@ -// -// Engine.cs -// -// Author: -// Mikayla Hutchinson -// -// 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; -using System.CodeDom.Compiler; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using Microsoft.CSharp; -using Microsoft.VisualStudio.TextTemplating; - -namespace Mono.TextTemplating -{ - public class TemplatingEngine : -#if FEATURE_APPDOMAINS - MarshalByRefObject, -#endif -#pragma warning disable 618 - ITextTemplatingEngine -#pragma warning restore 618 - { - public string ProcessTemplate(string content, ITextTemplatingEngineHost host) - { - using (var tpl = CompileTemplate(content, host)) - { - return tpl?.Process(); - } - } - - public string PreprocessTemplate(string content, ITextTemplatingEngineHost host, string className, - string classNamespace, out string language, out string[] references) - { - if (content == null) - throw new ArgumentNullException(nameof(content)); - if (host == null) - throw new ArgumentNullException(nameof(host)); - if (className == null) - throw new ArgumentNullException(nameof(className)); - if (classNamespace == null) - throw new ArgumentNullException(nameof(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(nameof(content)); - if (host == null) - throw new ArgumentNullException(nameof(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; - -#if FEATURE_APPDOMAINS - 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; - } -#endif - - return new CompiledTemplate(host, results, templateClassFullName, settings.Culture, references.ToArray()); - } - - static CompilerResults GenerateCode(IEnumerable 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(); - - 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(); - 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' || text[i + 1] == '\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()); - } - 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(); - - 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(); - - var sessionField = PrivateField(TypeRef>(), "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()); - - 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(); - var thisRef = new CodeThisReferenceExpression(); - var stringTypeRef = TypeRef(); - 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())); - - var errorsPropRef = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Errors"); - - var compilerErrorTypeRef = TypeRef(); - 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(); - var thisRef = new CodeThisReferenceExpression(); - var zeroPrim = new CodePrimitiveExpression(0); - var stringEmptyRef = - new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(stringTypeRef), "Empty"); - var intTypeRef = TypeRef(); - var stackIntTypeRef = TypeRef>(); - - 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>()); - - 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(); - 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(), "args"); - argsParam.CustomAttributes.Add(new CodeAttributeDeclaration(TypeRef())); - - 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(), "formatProvider"); - formatProviderField.InitExpression = new CodePropertyReferenceExpression( - new CodeTypeReferenceExpression(TypeRef()), "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(), - }; - meth.Parameters.Add(new CodeParameterDeclarationExpression(TypeRef(), "objectToConvert")); - var paramRef = new CodeArgumentReferenceExpression("objectToConvert"); - - meth.Statements.Add(NullCheck(paramRef, paramRef.ParameterName)); - - var typeLocal = new CodeVariableDeclarationStatement(TypeRef(), "type", - new CodeMethodInvokeExpression(paramRef, "GetType")); - var typeLocalRef = new CodeVariableReferenceExpression(typeLocal.Name); - meth.Statements.Add(typeLocal); - - var iConvertibleTypeLocal = new CodeVariableDeclarationStatement(TypeRef(), "iConvertibleType", - new CodeTypeOfExpression(TypeRef())); - 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(), paramRef), "ToString", formatProviderFieldRef)))); - - var methInfoLocal = new CodeVariableDeclarationStatement(TypeRef(), "methInfo", - new CodeMethodInvokeExpression(typeLocalRef, "GetMethod", - new CodePrimitiveExpression("ToString"), - new CodeArrayCreateExpression(TypeRef(), 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(), - new CodeMethodInvokeExpression( - methInfoLocalRef, "Invoke", paramRef, - new CodeArrayCreateExpression(TypeRef(), - 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() - { - 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: older versions of Mono don't implement GenerateCodeFromMember - // We have a workaround via reflection. First attempt to reflect the members we need to work around it. - // If they don't exist, we should be running on a version where it's fixed. - static bool useMonoHack = InitializeMonoHack(); - static MethodInfo cgFieldGen, cgPropGen, cgMethGen; - static Action initializeCodeGenerator; - - /// - /// An implementation of CodeDomProvider.GenerateCodeFromMember that works on Mono. - /// - public static void GenerateCodeFromMembers(CodeDomProvider provider, CodeGeneratorOptions options, - StringWriter sw, IEnumerable members) - { - if (!useMonoHack) - { - foreach (CodeTypeMember member in members) - provider.GenerateCodeFromMember(member, sw, options); - return; - } - -#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 bool InitializeMonoHack() - { - if (Type.GetType("Mono.Runtime") == null) - { - return false; - } - - var cgType = typeof(CodeGenerator); - - var cgInit = cgType.GetMethod("InitOutput", BindingFlags.NonPublic | BindingFlags.Instance); - if (cgInit != null) - { - initializeCodeGenerator = new Action( - (generator, sw, options) => { cgInit.Invoke(generator, new object[] { sw, options }); }); - } - else - { - var cgOptions = cgType.GetField("options", BindingFlags.NonPublic | BindingFlags.Instance); - var cgOutput = cgType.GetField("output", BindingFlags.NonPublic | BindingFlags.Instance); - - if (cgOptions == null || cgOutput == null) - { - return false; - } - - initializeCodeGenerator = new Action( - (generator, sw, options) => - { - var output = new IndentedTextWriter(sw); - cgOptions.SetValue(generator, options); - cgOutput.SetValue(generator, output); - }); - } - - cgFieldGen = cgType.GetMethod("GenerateField", BindingFlags.NonPublic | BindingFlags.Instance); - cgPropGen = cgType.GetMethod("GenerateProperty", BindingFlags.NonPublic | BindingFlags.Instance); - cgMethGen = cgType.GetMethod("GenerateMethod", BindingFlags.NonPublic | BindingFlags.Instance); - - if (cgFieldGen == null || cgPropGen == null || cgMethGen == null) - { - return false; - } - - return true; - } - - public static string GenerateIndentedClassCode(CodeDomProvider provider, params CodeTypeMember[] members) - { - return GenerateIndentedClassCode(provider, (IEnumerable) members); - } - - public static string GenerateIndentedClassCode(CodeDomProvider provider, IEnumerable 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/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/Tokeniser.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/Tokeniser.cs deleted file mode 100644 index 0c0f3bc3a9..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/Mono.TextTemplating/Mono.TextTemplating/Tokeniser.cs +++ /dev/null @@ -1,356 +0,0 @@ -// -// Tokeniser.cs -// -// Author: -// Mikayla Hutchinson -// -// 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/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/README.md b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/README.md deleted file mode 100644 index 84b4fbf7b4..0000000000 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenT4/README.md +++ /dev/null @@ -1,2 +0,0 @@ -This project exists in folder prefixed with a '.' so that Unity ignores it at script compile time, but it can still be -distributed as part of the Unity package. diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGen/CodeGen.csproj b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGen/CodeGen.csproj index 8f9881d59d..c54ca795c3 100644 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGen/CodeGen.csproj +++ b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGen/CodeGen.csproj @@ -8,9 +8,6 @@ - - - @@ -21,5 +18,4 @@ - diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGen/dependencies/Improbable.TextTemplating/Improbable.TextTemplating.dll b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGen/dependencies/Improbable.TextTemplating/Improbable.TextTemplating.dll deleted file mode 100644 index 28b64c911f..0000000000 Binary files a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGen/dependencies/Improbable.TextTemplating/Improbable.TextTemplating.dll and /dev/null differ diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGen/dependencies/Improbable.TextTemplating/Mono.TextTemplating.dll b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGen/dependencies/Improbable.TextTemplating/Mono.TextTemplating.dll deleted file mode 100644 index 428cbdcd68..0000000000 Binary files a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGen/dependencies/Improbable.TextTemplating/Mono.TextTemplating.dll and /dev/null differ diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGen/dependencies/Improbable.TextTemplating/System.CodeDom.dll b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGen/dependencies/Improbable.TextTemplating/System.CodeDom.dll deleted file mode 100644 index 3128b6a563..0000000000 Binary files a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGen/dependencies/Improbable.TextTemplating/System.CodeDom.dll and /dev/null differ diff --git a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGenerationLib/CodeWriter/Scopes/MethodBlock.cs b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGenerationLib/CodeWriter/Scopes/MethodBlock.cs index 0d82fe0570..d627dc0f1e 100644 --- a/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGenerationLib/CodeWriter/Scopes/MethodBlock.cs +++ b/workers/unity/Packages/io.improbable.gdk.tools/.CodeGenTemplate/CodeGenerationLib/CodeWriter/Scopes/MethodBlock.cs @@ -15,6 +15,8 @@ internal MethodBlock(string declaration, Action populate, string an internal MethodBlock(string declaration, Func> populate, string annotation = "") : base( declaration) { + Annotation = annotation; + var methodBody = populate().ToList(); if (methodBody.Count > 0) { diff --git a/workers/unity/Packages/io.improbable.gdk.tools/GenerateCode.cs b/workers/unity/Packages/io.improbable.gdk.tools/GenerateCode.cs index 45786fb08b..a36473a0c5 100644 --- a/workers/unity/Packages/io.improbable.gdk.tools/GenerateCode.cs +++ b/workers/unity/Packages/io.improbable.gdk.tools/GenerateCode.cs @@ -37,7 +37,7 @@ internal static class GenerateCode /// CS error code /// Message /// - /// Example: Generated\Templates\UnityCommandManagerGenerator.tt(11,9): warning CS0219: The variable 'profilingEnd' is assigned but its value is never used [D:\gdk-for-unity\workers\unity\Packages\io.improbable.gdk.tools\.CodeGenerator\GdkCodeGenerator\GdkCodeGenerator.csproj] + /// Example: D:\gdk-for-unity\workers\unity\Packages\io.improbable.gdk.core\.codegen\Source\CoreCodegenJob.cs(128,64): error CS1002: ; expected [D:\gdk-for-unity\test-project\build\codegen\CodeGen\CodeGen.csproj] private static readonly Regex dotnetRegex = new Regex( @"(?[\w\\\.]+)\((?\d+),(?\d+)\): (?\w+) (?\w+): (?[\s\S]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); @@ -384,12 +384,10 @@ This method edits the csproj XML to link in the constituent parts of the each co Source/ SourceFile1.cs SourceFile2.cs - Templates/ - MyTemplate.tt Partials/ Improbable.Vector3f - Each of the Source, Templates, and Partials folder are optional. + Each of the Source and Partials folder are optional. */ private static void UpdateModules() { @@ -428,15 +426,6 @@ private static void UpdateModules() itemGroup.Add(ele); } - var templateDir = Path.Combine(dir, "Templates"); - if (Directory.Exists(templateDir)) - { - // Ensure that we generate and compile in any T4 templates provided by the codegen module. - var ele = new XElement("T4Files"); - ele.SetAttributeValue("Include", Path.Combine(templateDir, "**")); - itemGroup.Add(ele); - } - var partialDir = Path.Combine(dir, "Partials"); if (Directory.Exists(partialDir)) {