【问题标题】:T4 reports Compiling transformation: Invalid token 'this' in class, structT4 报告编译转换:类结构中的标记“this”无效
【发布时间】:2014-04-24 23:05:41
【问题描述】:

尝试为Immutable Object Graph 运行 T4 模板会出现

错误
╔═══════╦═══╦══════════════════════════════════════════════════════════════════════════════════════════════════╦═════════════════════════════════════════════════════════╦═══╦════╦══════╗
║ Error ║ 5 ║ Compiling transformation: Invalid token 'this' in class, struct, or interface member declaration ║ c:\dev\ImmutableObjectGraph-master\2013\Demo\Message.tt ║ 1 ║  1 ║ Demo ║
║ Error ║ 6 ║ Compiling transformation: Method must have a return type                                         ║ c:\dev\ImmutableObjectGraph-master\2013\Demo\Message.tt ║ 1 ║  6 ║ Demo ║
║ Error ║ 7 ║ Compiling transformation: Type expected                                                          ║ c:\dev\ImmutableObjectGraph-master\2013\Demo\Message.tt ║ 1 ║ 12 ║ Demo ║
╚═══════╩═══╩══════════════════════════════════════════════════════════════════════════════════════════════════╩═════════════════════════════════════════════════════════╩═══╩════╩══════╝

报告的行总是第 1 行,全套 t4 模板有数百行。如何排查和解决此问题?

【问题讨论】:

  • 虽然下面的答案是正确的,但如果您使用的是 GitHub,下面的文章也可能会解释另一种解决方案 - teamdevelopmentforsitecore.com/Blog/…
  • @woodyiii,您可能会发现将正确的 eol 说明符添加到 .gitattributes 将更永久地解决您的问题。如果您的团队成员在其他平台上,手动更改它会很快变老。

标签: visual-studio-2013 t4


【解决方案1】:

您不能在 T4 模板中在 scriptlet 之后使用文字。

改变

<#@ template debug="true" language="C#" #>
<#+
// scriptlet
#>
                                              <-- empty line here

到

<#@ template debug="true" language="C#" #>
<#+
// scriptlet
#>

调试

您可以通过使用自定义模板主机调用 PreProcessTemplate 来查看 T4 引擎生成的 C#。

为此我修改了Custom Template Host sample:

using Microsoft.VisualStudio.TextTemplating;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace CustomHost
{
    class CustomCmdLineHost : ITextTemplatingEngineHost
    {
        public string TemplateFile { get; private set; }
        public string FileExtension { get; private set; }
        public Encoding FileEncoding { get; private set; }
        public CompilerErrorCollection Errors { get; private set; }

        public IList<string> StandardAssemblyReferences { get { return new[] { typeof(System.Uri).Assembly.Location }; } }
        public IList<string> StandardImports { get { return new string[] { "System" }; } }

        public CustomCmdLineHost(string file)
        {
            this.TemplateFile = file;
            this.FileEncoding = Encoding.UTF8;
            this.FileExtension = ".txt";
        }

        public bool LoadIncludeText(string requestFileName, out string content, out string location)
        {
            content = location = String.Empty;

            if (File.Exists(requestFileName))
            {
                content = File.ReadAllText(requestFileName);
                return true;
            }

            return false;
        }

        public object GetHostOption(string optionName)
        {
            object returnObject;
            switch (optionName)
            {
                case "CacheAssemblies":
                    returnObject = true;
                    break;
                default:
                    returnObject = null;
                    break;
            }
            return returnObject;
        }

        public string ResolveAssemblyReference(string assemblyReference)
        {
            return ResolvePath(assemblyReference);
        }

        public Type ResolveDirectiveProcessor(string processorName)
        {
            throw new Exception("Directive Processor not found");
        }

        public string ResolvePath(string fileName)
        {
            if (File.Exists(fileName))
            {
                return fileName;
            }

            string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), fileName);
            if (File.Exists(candidate))
            {
                return candidate;
            }

            return fileName;
        }

        public string ResolveParameterValue(string directiveId, string processorName, string parameterName)
        {
            return String.Empty;
        }

        public void SetFileExtension(string extension)
        {
            FileExtension = extension;
        }

        public void SetOutputEncoding(System.Text.Encoding encoding, bool fromOutputDirective)
        {
            FileEncoding = encoding;
        }

        public void LogErrors(CompilerErrorCollection errors)
        {
            Errors = errors;
        }

        public AppDomain ProvideTemplatingAppDomain(string content)
        {
            return AppDomain.CreateDomain("Generation App Domain");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var templateFileName = args[0];

            CustomCmdLineHost host = new CustomCmdLineHost(templateFileName);
            Engine engine = new Engine();

            string language;
            string[] refs;
            var output = engine.PreprocessTemplate(
                // input file
                File.ReadAllText(templateFileName), host,
                "testClass", "testNamespace", out language, out refs);

            string outputFileName = Path.Combine(
                Path.GetDirectoryName(templateFileName),
                templateFileName + ".generator.cs");

            File.WriteAllText(outputFileName, output, host.FileEncoding);

            foreach (CompilerError error in host.Errors)
                Console.WriteLine(error.ToString());

            Console.ReadLine();
        }
    }
}

检查从模板生成的转换器在TransformText() 方法之外显示如下行。看起来,源模板中在 scriptlet (&lt;#+ #&gt;) 之后出现的任何文字都将被放置在生成的生成器类中。

        #line 1 "C:\dev\ImmutableObjectGraph-master\2013\Demo\Fruit.tt"
this.Write("\n");

删除每个模板文件末尾的换行符解决了这个问题。

【讨论】:

  • 我猜这个信息对 99% 的读者来说是最重要的:“删除每个模板文件末尾的换行符解决了这个问题。”
  • 非常感谢,我已经扯了一个小时的头发试图理解发生了什么
  • 对我来说问题出在其他地方。 1. 从上面获取 Szymon Seliga 的示例代码 2. 粘贴到控制台应用程序 3. 安装 nuget "Microsoft.VisualStudio.TextTemplating.15.0" 4. *.tt 文件的硬编码路径(应该在 111 上) 5. 这将生成*.tt.generator.cs 6. 在 Visual Studio 7 中打开此文件。查找 this.Write("\n");是外部方法(Visual Studio 语法智能感知实际上会用红色强调它
【解决方案2】:

对我来说,文件末尾的换行符不是问题,但是使用 Unix 行尾 (\n) 而不是 Windows 行尾 (\r\n) 破坏了 T4 引擎。

当您有两个看起来相同但其中一个无法编译的文件时,调试起来非常令人沮丧!

【讨论】:

  • 在我的情况下,这个答案解决了我的问题,这篇文章详细解释了如何解决这个问题 - teamdevelopmentforsitecore.com/Blog/… 每当我们将版本控制转换为 GitHub 时,都会出现随机的 CR LF 问题还是上来,像这个。
  • 另外值得注意的是,Windows 的 Git 安装程序默认将其设置为在结帐/提交时转换换行符 (core.autocrlf=true)。因此,在服务器上构建时,行尾可能与本地不同。
【解决方案3】:

是的,这对我来说也与行尾有关,可能是由于源代码控制。

为了解决,我将模板代码复制并粘贴到 Notepad++ 中并保存为普通 txt 文件,然后复制并粘贴回来。

(由于行尾错误,记事本无法使用)

【讨论】:

    猜你喜欢
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    相关资源
    最近更新 更多