c# - C# CodeDom 在 csc.exe 中导致堆栈溢出 (CS1647) 的解决方法?

标签 c# compiler-construction codedom csc

我遇到了一种情况,我需要生成一个带有大字符串常量的类。超出我控制范围的代码会导致我生成的 CodeDom 树被发送到 C# 源代码,然后作为更大的程序集的一部分进行编译。

不幸的是,我遇到过这样一种情况:如果此字符串的长度在 Win2K8 x64 中超过 335440 个字符(在 Win2K3 x86 中为 926240),C# 编译器将退出并出现 fatal error :

fatal error CS1647: An expression is too long or complex to compile near 'int'

MSDN 称 CS1647 是“编译器中的堆栈溢出”(无双关语!)。仔细观察,我确定 CodeDom“很好地”将我的字符串 const 包装在 80 个字符处。这导致编译器连接超过 4193 个字符串 block ,这显然是 x64 NetFx 中 C# 编译器的堆栈深度。 CSC.exe 必须在内部递归地评估此表达式以“补充”我的单个字符串。

我最初的问题是:“有没有人知道改变代码生成器发出字符串的方式的解决方法?”我无法控制外部系统使用 C# 源作为中间体的事实我希望它是一个常量(而不是字符串的运行时连接)。

或者,我如何制定这个表达式,以便在一定数量的字符之后,我仍然能够创建一个常量,但它由多个 block 组成?

完整重现在这里:

// this string breaks CSC: 335440 is Win2K8 x64 max, 926240 is Win2K3 x86 max
string HugeString = new String('X', 926300);

CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
CodeCompileUnit code = new CodeCompileUnit();

// namespace Foo {}
CodeNamespace ns = new CodeNamespace("Foo");
code.Namespaces.Add(ns);

// public class Bar {}
CodeTypeDeclaration type = new CodeTypeDeclaration();
type.IsClass = true;
type.Name = "Bar";
type.Attributes = MemberAttributes.Public;
ns.Types.Add(type);

// public const string HugeString = "XXXX...";

CodeMemberField field = new CodeMemberField();
field.Name = "HugeString";
field.Type = new CodeTypeReference(typeof(String));
field.Attributes = MemberAttributes.Public|MemberAttributes.Const;
field.InitExpression = new CodePrimitiveExpression(HugeString);
type.Members.Add(field);

// generate class file
using (TextWriter writer = File.CreateText("FooBar.cs"))
{
    provider.GenerateCodeFromCompileUnit(code, writer, new CodeGeneratorOptions());
}

// compile class file
CompilerResults results = provider.CompileAssemblyFromFile(new CompilerParameters(), "FooBar.cs");

// output reults
foreach (string msg in results.Output)
{
    Console.WriteLine(msg);
}

// output errors
foreach (CompilerError error in results.Errors)
{
    Console.WriteLine(error);
}

最佳答案

使用 CodeSnippetExpression 和手动引用的字符串,我能够发出我希望从 Microsoft.CSharp.CSharpCodeGenerator 看到的源。

所以要回答上面的问题,请替换这一行:

field.InitExpression = new CodePrimitiveExpression(HugeString);

用这个:

field.InitExpression = new CodeSnippetExpression(QuoteSnippetStringCStyle(HugeString));

最后修改引用 Microsoft.CSharp.CSharpCodeGenerator.QuoteSnippetStringCStyle 方法的私有(private)字符串,使其在 80 个字符后不换行:

private static string QuoteSnippetStringCStyle(string value)
{
    // CS1647: An expression is too long or complex to compile near '...'
    // happens if number of line wraps is too many (335440 is max for x64, 926240 is max for x86)

    // CS1034: Compiler limit exceeded: Line cannot exceed 16777214 characters
    // theoretically every character could be escaped unicode (6 chars), plus quotes, etc.

    const int LineWrapWidth = (16777214/6) - 4;
    StringBuilder b = new StringBuilder(value.Length+5);

    b.Append("\r\n\"");
    for (int i=0; i<value.Length; i++)
    {
        switch (value[i])
        {
            case '\u2028':
            case '\u2029':
            {
                int ch = (int)value[i];
                b.Append(@"\u");
                b.Append(ch.ToString("X4", CultureInfo.InvariantCulture));
                break;
            }
            case '\\':
            {
                b.Append(@"\\");
                break;
            }
            case '\'':
            {
                b.Append(@"\'");
                break;
            }
            case '\t':
            {
                b.Append(@"\t");
                break;
            }
            case '\n':
            {
                b.Append(@"\n");
                break;
            }
            case '\r':
            {
                b.Append(@"\r");
                break;
            }
            case '"':
            {
                b.Append("\\\"");
                break;
            }
            case '\0':
            {
                b.Append(@"\0");
                break;
            }
            default:
            {
                b.Append(value[i]);
                break;
            }
        }

        if ((i > 0) && ((i % LineWrapWidth) == 0))
        {
            if ((Char.IsHighSurrogate(value[i]) && (i < (value.Length - 1))) && Char.IsLowSurrogate(value[i + 1]))
            {
                b.Append(value[++i]);
            }
            b.Append("\"+\r\n");
            b.Append('"');
        }
    }
    b.Append("\"");
    return b.ToString();
}

关于c# - C# CodeDom 在 csc.exe 中导致堆栈溢出 (CS1647) 的解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/960305/

相关文章:

c# - 使用 HttpWebRequest 和 X509 SSL 证书检查 HTTPS Web 服务是否可用

c# - 如何使用方法调用生成已编译的 lambda?

compiler-construction - Clojure 中编译器开发的习语

c# - 使用连接字符串的 DocumentDB .Net 客户端

compiler-construction - 删除左递归

c++ - 为什么在堆栈上分配了这么多空间?

c# - 如何使用 CodeDom 创建接口(interface)方法

javascript - 在运行时解释和/或接收 dotNet 代码

c# - 从现有类生成 CodeDOM

c# - 用泛型对象初始化非泛型对象