Exemplo n.º 1
0
        public static string ReplaceStringLiteralsWithVariables(string text, IEnumerable<string> macros, Func<int, int, string, string, string> onReplace)
        {
            var setting = new CompilerSettings();
            foreach (var macro in macros) setting.ConditionalSymbols.Add(macro);

            var tree = SyntaxTree.Parse(text, string.Empty, setting);
            tree.Freeze();

            var doc = new StringBuilderDocument(text);
            using (var editor = new DocumentScript(doc, FormattingOptionsFactory.CreateAllman(), TextEditorOptions.Default)) {
                var originDoc = editor.OriginalDocument;

                foreach (var node in tree.Descendants.OfType<PrimitiveExpression>().Where(e => e.Value is string)) {
                    var line = originDoc.GetLineByNumber(node.StartLocation.Line);
                    var result = onReplace(node.StartLocation.Line, node.StartLocation.Column, originDoc.GetText(line), node.Value as string);
                    if (result != null) {
                        var names = result.Split('.');
                        Expression exp = new IdentifierExpression(names.First());
                        foreach (var name in names.Skip(1)) exp = exp.Member(name);

                        editor.Replace(node, exp);
                    }
                }
            }

            return doc.Text;
        }
Exemplo n.º 2
0
 private static string RemoveClasses(string code, IEnumerable<TypeDeclaration> classes)
 {
     var document = new StringBuilderDocument(code);
     using (
         var script = new DocumentScript(
             document,
             FormattingOptionsFactory.CreateAllman(),
             new TextEditorOptions()))
     {
         foreach (var @class in classes)
         {
             var offset = script.GetCurrentOffset(@class.GetRegion().Begin);
             script.Replace(@class, new TypeDeclaration());
             script.Replace(offset, new TypeDeclaration().GetText().Trim().Length, "");
         }
     }
     return document.Text;
 }
Exemplo n.º 3
0
        public static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                Console.WriteLine("use: RenameClass.exe <SolutionPath> <ClassNamespace> <CurrentClassName> <NewClassName>");
                return;
            }

            var solutionFile = args[0]; // "C:\\Users\\v-ezeqs\\Documents\\Visual Studio 2010\\Projects\\Application36\\Application36.sln"
            var classNamespace = args[1]; // "Application36.WebHost"
            var className = args[2]; // "SiteMaster"
            var classNewName = args[3]; // "SiteMaster2"

            if (!File.Exists(solutionFile))
            {
                Console.WriteLine("Solution not found at {0}", solutionFile);
                return;
            }

            Console.WriteLine("Loading solution...");

            // Loading Solution in Memory
            Solution solution = new Solution(solutionFile);

            Console.WriteLine("Finding references...");

            // Define which Type I'm looking for
            var typeReference = new GetClassTypeReference(classNamespace, className) as ITypeReference;

            // Try to find the Type definition in solution's projects
            foreach (var proj in solution.Projects)
            {
                var type = typeReference.Resolve(proj.Compilation);
                if (type.Kind != TypeKind.Unknown)
                {
                    SetSearchedMembers(new List<object>() { type });
                }
            }

            if (searchedMembers == null)
            {
                Console.WriteLine("Not References found. Refactoring Done.");
                return;
            }

            // Find all related members related with the Type (like Members, Methods, etc)
            ICSharpCode.NRefactory.CSharp.Resolver.FindReferences refFinder = new ICSharpCode.NRefactory.CSharp.Resolver.FindReferences();
            var scopes = searchedMembers.Select (e => refFinder.GetSearchScopes (e as IEntity));

            // Finding references to the Type on the one of the different Solution files
            refs = new List<dynamic>();
            foreach (var file in solution.AllFiles.Distinct (new CSharpFileEqualityComparer())) {
                foreach (var scope in scopes)
                {
                    refFinder.FindReferencesInFile(
                        scope,
                        file.UnresolvedTypeSystemForFile,
                        file.SyntaxTree,
                        file.Project.Compilation,
                        (astNode, result) =>
                        {
                            var newRef = GetReference(result, astNode, file);
                            if (newRef == null || refs.Any(r => r.File.FileName == newRef.File.FileName && r.Region == newRef.Region))
                                return;
                            refs.Add(newRef);
                        },
                        CancellationToken.None
                    );
                }
            }

            Console.WriteLine("Refactoring {0} places in {1} files...",
                              refs.Count(),
                              refs.Select(x => x.File.FileName).Distinct().Count());

            // Perform replace for each of the References found
            foreach (var r in refs) {
                // DocumentScript expects the the AST to stay unmodified (so that it fits
                // to the document state at the time of the DocumentScript constructor call),
                // so we call Freeze() to prevent accidental modifications (e.g. forgetting a Clone() call).
                r.File.SyntaxTree.Freeze();

                // Create a document containing the file content:
                var fileText = File.ReadAllText(r.File.FileName);
                var document = new StringBuilderDocument(fileText);
                using (var script = new DocumentScript(document, FormattingOptionsFactory.CreateAllman(), new TextEditorOptions())) {
                    // Alternative 1: clone a portion of the AST and modify it
                    //var copy = (InvocationExpression)expr.Clone();
                    //copy.Arguments.Add(stringComparisonAst.Member("Ordinal"));
                    //script.Replace(expr, copy);

                    // Alternative 2: perform direct text insertion / replace
                    int offset = script.GetCurrentOffset(r.Region.Begin);
                    var length = r.Region.End.Column - r.Region.Begin.Column;

                    script.Replace(offset, length, classNewName);
                }
                File.WriteAllText(r.File.FileName, document.Text);
            }

            Console.WriteLine("Refactoring Done.");
        }
Exemplo n.º 4
0
        public static void Main(string[] args)
        {
            if (args.Length == 0) {
                Console.WriteLine("Please specify the path to a .sln file on the command line");

                Console.Write("Press any key to continue . . . ");
                Console.ReadKey(true);
                return;
            }

            Solution solution = new Solution(args[0]);
            foreach (var file in solution.AllFiles) {
                var astResolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.UnresolvedTypeSystemForFile);
                foreach (var invocation in file.SyntaxTree.Descendants.OfType<InvocationExpression>()) {
                    // Retrieve semantics for the invocation
                    var rr = astResolver.Resolve(invocation) as InvocationResolveResult;
                    if (rr == null) {
                        // Not an invocation resolve result - e.g. could be a UnknownMemberResolveResult instead
                        continue;
                    }
                    if (rr.Member.FullName != "System.String.IndexOf") {
                        // Invocation isn't a string.IndexOf call
                        continue;
                    }
                    if (rr.Member.Parameters.First().Type.FullName != "System.String") {
                        // Ignore the overload that accepts a char, as that doesn't take a StringComparison.
                        // (looking for a char always performs the expected ordinal comparison)
                        continue;
                    }
                    if (rr.Member.Parameters.Last().Type.FullName == "System.StringComparison") {
                        // Already using the overload that specifies a StringComparison
                        continue;
                    }
                    Console.WriteLine(invocation.GetRegion() + ": " + invocation.GetText());
                    file.IndexOfInvocations.Add(invocation);
                }
            }
            Console.WriteLine("Found {0} places to refactor in {1} files.",
                              solution.AllFiles.Sum(f => f.IndexOfInvocations.Count),
                              solution.AllFiles.Count(f => f.IndexOfInvocations.Count > 0));
            Console.Write("Apply refactorings? ");
            string answer = Console.ReadLine();
            if ("yes".Equals(answer, StringComparison.OrdinalIgnoreCase) || "y".Equals(answer, StringComparison.OrdinalIgnoreCase)) {
                foreach (var file in solution.AllFiles) {
                    if (file.IndexOfInvocations.Count == 0)
                        continue;
                    // DocumentScript expects the the AST to stay unmodified (so that it fits
                    // to the document state at the time of the DocumentScript constructor call),
                    // so we call Freeze() to prevent accidental modifications (e.g. forgetting a Clone() call).
                    file.SyntaxTree.Freeze();
                    // AST resolver used to find context for System.StringComparison generation
                    var compilation = file.Project.Compilation;
                    var astResolver = new CSharpAstResolver(compilation, file.SyntaxTree, file.UnresolvedTypeSystemForFile);

                    // Create a document containing the file content:
                    var document = new StringBuilderDocument(file.OriginalText);
                    var formattingOptions = FormattingOptionsFactory.CreateAllman();
                    var options = new TextEditorOptions();
                    using (var script = new DocumentScript(document, formattingOptions, options)) {
                        foreach (InvocationExpression expr in file.IndexOfInvocations) {
                            // Generate a reference to System.StringComparison in this context:
                            var astBuilder = new TypeSystemAstBuilder(astResolver.GetResolverStateBefore(expr));
                            IType stringComparison = compilation.FindType(typeof(StringComparison));
                            AstType stringComparisonAst = astBuilder.ConvertType(stringComparison);

                            // Alternative 1: clone a portion of the AST and modify it
                            var copy = (InvocationExpression)expr.Clone();
                            copy.Arguments.Add(stringComparisonAst.Member("Ordinal"));
                            script.Replace(expr, copy);

            //							// Alternative 2: perform direct text insertion
            //							int offset = script.GetCurrentOffset(expr.RParToken.StartLocation);
            //							script.InsertText(offset, ", " + stringComparisonAst.GetText() +  ".Ordinal");
                        }
                    }
                    File.WriteAllText(Path.ChangeExtension(file.FileName, ".output.cs"), document.Text);
                }
            }
        }
Exemplo n.º 5
0
 private static string RemoveMethods(string code, IEnumerable<MethodVisitorResult> methods)
 {
     var document = new StringBuilderDocument(code);
     using (var script = new DocumentScript(
         document, 
         FormattingOptionsFactory.CreateAllman(), 
         new TextEditorOptions()))
     {
         foreach (var method in methods)
         {
             var offset = script.GetCurrentOffset(method.MethodDefinition.GetRegion().Begin);
             script.Replace(method.MethodDefinition, new MethodDeclaration());
             script.Replace(offset, new MethodDeclaration().GetText().Trim().Length, "");
         }
     }
     return document.Text;
 }