dotnet/roslyn

Document encoding gets lost on Project.AddDocument

Aperta

#24.045 aperta il 4 gen 2018

 (13 commenti) (1 reazione) (0 assegnatari)C# (4257 fork)batch import
Area-AnalyzersBughelp wanted

Metriche repository

Star
 (20.414 stelle)
Metriche merge PR
 (Merge medio 6g 17h) (256 PR mergiate in 30 g)

Descrizione

Version Used: 2.6.1 Steps to Reproduce: When entirely generating the syntax nodes in-memory, the SyntaxGenerator does not allow specifying an encoding. The workaround is to re-create the syntax tree by using CSharpSyntaxTree.Create with a valid encoding. Problem 1: how bad is this perf hit?

But even after having a valid encoding in the SyntaxTree, the AddDocument does not keep the information (see the last assert in the code below). Again, the workaround is to re-apply the encoding after the compilation has been created, but it looks definitely a weird behavor.

  • Am I missing something?
  • Is there a better way to enforce the encoding for handcrafted in-memory syntax trees?
// Encoding is needed to avoid CS8055: Cannot emit debug information for a source text without encoding
private void TestEncoding1()
{
    var workspace = new AdhocWorkspace();
    var generator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp);
    var project = workspace.CurrentSolution.AddProject("test", "test", LanguageNames.CSharp);

    var root = GetCode(generator);
    // code generated on the fly does not have encoding
    Debug.Assert(root.SyntaxTree.Encoding == null);

    var encoded = CSharpSyntaxTree.Create(root as CSharpSyntaxNode,
        null, string.Empty, Encoding.UTF8).GetRoot();
    // encoding is now part of the syntax tree
    Debug.Assert(encoded.SyntaxTree.Encoding != null);

    var document = project.AddDocument("test", encoded);
    var documentTree = document.GetSyntaxTreeAsync().Result;
    // why does this assert fails?
    Debug.Assert(documentTree.Encoding != null);
}

private SyntaxNode GetCode(SyntaxGenerator generator)
{
    return generator.NamespaceDeclaration("Foo",
        generator.ClassDeclaration("FooClass", null,
            Accessibility.Public, DeclarationModifiers.Partial,
            null, null, null));
}

Expected Behavior:

  1. I expect there a way to specify the default encoding in the SyntaxGenerator
  2. I expect that AddDocument keep the encoding stored in the specified syntax tree
  3. I want to avoid any possible perf hit that would come from generating the text source code and parsed back in a new syntax tree.

Actual Behavior: The encoding is missing (see asserts in the code)

Guida contributor