Skip to content

Instantly share code, notes, and snippets.

@EgorBo
Last active August 15, 2018 00:01
Show Gist options
  • Save EgorBo/41d91a4d0b6ccb90096dd7cc0857dfa0 to your computer and use it in GitHub Desktop.
Save EgorBo/41d91a4d0b6ccb90096dd7cc0857dfa0 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
public static class Program
{
public static void Main()
{
Visit();
Console.ReadKey();
}
private static async void Visit()
{
//string loc = @"C:\prj\coreclr-egor\src\System.Private.CoreLib";
string loc = @"C:\prj\corefx-egor\src";
foreach (string path in Directory.EnumerateFiles(loc, "*.cs", SearchOption.AllDirectories))
{
if (path.Contains("tests"))
continue;
string text = File.ReadAllText(path);
using (var workspace = new AdhocWorkspace())
{
Project proj = workspace.AddProject("UnboxingVisitor", LanguageNames.CSharp).WithMetadataReferences(new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) });
Document doc = proj.AddDocument(Path.GetFileName(path), SourceText.From(text));
Compilation compilation = await doc.Project.GetCompilationAsync();
SyntaxNode root = await doc.GetSyntaxRootAsync();
var visitor = new UnboxingVisitor { _model = compilation.GetSemanticModel(root.SyntaxTree) };
SyntaxNode node = visitor.Visit(root);
}
}
Console.WriteLine("End.");
}
}
internal sealed class UnboxingVisitor : CSharpSyntaxRewriter
{
internal SemanticModel _model;
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
{
var typeToCast = node.Type as IdentifierNameSyntax;
var whatToCast = node.Expression as IdentifierNameSyntax;
if (typeToCast != null && whatToCast != null)
{
string toType = GetTypeName(typeToCast, _model, out bool isToValueType);
string fromType = GetTypeName(whatToCast, _model, out bool isFromValueType);
if (fromType == "Object" && isToValueType)
{
var location = node.GetLocation();
var logStr = $"{location.SourceTree.FilePath}:{location.GetLineSpan().StartLinePosition.Line} {node.Parent.Parent.ToFullString()}";
Console.WriteLine(logStr);
//File.AppendAllText(@"C:\Users\bogat\source\log4.txt", logStr + Environment.NewLine);
}
}
return base.VisitCastExpression(node);
}
public static string GetTypeName(ExpressionSyntax es, SemanticModel model, out bool isValueType)
{
isValueType = false;
try
{
var symbolInfo = model.GetSymbolInfo(es);
var symbol = symbolInfo.Symbol as ITypeSymbol;
isValueType = symbol?.IsValueType == true;
var aa = symbolInfo.Symbol as IParameterSymbol;
var type = aa?.Type?.Name ?? symbol?.Name;
return type;
}
catch (Exception exc)
{
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment