Skip to content

Instantly share code, notes, and snippets.

@svick
Last active May 21, 2017 22:29
Show Gist options
  • Select an option

  • Save svick/e52d523457b7a27fe6fd6b19a0842c36 to your computer and use it in GitHub Desktop.

Select an option

Save svick/e52d523457b7a27fe6fd6b19a0842c36 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
class Program
{
static void Main()
{
string text = @"
using System;
using System.Collections.Generic;
Console.WriteLine(""I only need to use System"");";
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(text, new CSharpParseOptions(kind: SourceCodeKind.Script));
var coreDir = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location);
var mscorlib = MetadataReference.CreateFromFile(Path.Combine(coreDir, "mscorlib.dll"));
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var compilation = CSharpCompilation.Create("MyAssembly")
.AddSyntaxTrees(syntaxTree)
.AddReferences(mscorlib)
.WithOptions(options);
var tree = compilation.SyntaxTrees.Single();
var root = tree.GetRoot();
var unusedImportNodes = compilation.GetDiagnostics()
.Where(d => d.Id == "CS8019")
.Where(d => d.Location?.SourceTree == tree)
.Select(d => root.FindNode(d.Location.SourceSpan))
.ToList();
var newRoot = root.RemoveNodes(unusedImportNodes, SyntaxRemoveOptions.KeepNoTrivia);
var newCompilation0 = compilation.ReplaceSyntaxTree(tree, SyntaxFactory.SyntaxTree(newRoot));
var newCompilation1 = compilation.ReplaceSyntaxTree(tree, SyntaxFactory.SyntaxTree(newRoot, tree.Options));
var newCompilation2 = compilation.ReplaceSyntaxTree(tree, tree.WithRootAndOptions(newRoot, tree.Options));
var newCompilation3 = compilation.ReplaceSyntaxTree(tree, tree.WithChangedText(SourceText.From(newRoot.ToFullString())));
WriteKind(newCompilation0); // Regular
WriteKind(newCompilation1); // Script
WriteKind(newCompilation2); // Script
WriteKind(newCompilation3); // Script
void WriteKind(Compilation c) => Console.WriteLine(c.SyntaxTrees.Single().Options.Kind);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment