Пример #1
0
        public static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: CheeseCake FileName OptionFileName");
                return;
            }

            var sourceFileName = args [0];
            var optionFileName = args [1];

            var policy   = LoadFormattingProfile(optionFileName);
            var options  = LoadTextEditorProfile(optionFileName);
            var settings = new CompilerSettings();

            settings.ConditionalSymbols.Add("UNITY_EDITOR");
            settings.ConditionalSymbols.Add("UNITY_IOS");
            settings.ConditionalSymbols.Add("UNITY_ANDROID");
            var formatter = new CSharpFormatter(policy, options);

            var text     = File.ReadAllText(sourceFileName);
            var document = new StringBuilderDocument(text);

            var syntaxTree = SyntaxTree.Parse(document, document.FileName, settings);
            var changes    = formatter.AnalyzeFormatting(document, syntaxTree);

            changes.ApplyChanges();

            File.WriteAllText(sourceFileName, document.Text, Encoding.UTF8);
        }
Пример #2
0
        public static OmniSharpRefactoringContext GetContext(BufferParser bufferParser, Request request)
        {
            var q        = bufferParser.ParsedContent(request.Buffer, request.FileName);
            var resolver = new CSharpAstResolver(q.Compilation, q.SyntaxTree, q.UnresolvedFile);
            var doc      = new StringBuilderDocument(request.Buffer);
            var location = new TextLocation(request.Line, request.Column);
            OmniSharpRefactoringContext refactoringContext;

            if (request is CodeActionRequest)
            {
                var car = request as CodeActionRequest;
                if (car.SelectionStartColumn.HasValue)
                {
                    var startLocation
                        = new TextLocation(car.SelectionStartLine.Value, car.SelectionStartColumn.Value);
                    var endLocation
                        = new TextLocation(car.SelectionEndLine.Value, car.SelectionEndColumn.Value);

                    refactoringContext = new OmniSharpRefactoringContext(doc, resolver, location, startLocation, endLocation);
                }
                else
                {
                    refactoringContext = new OmniSharpRefactoringContext(doc, resolver, location);
                }
            }
            else
            {
                refactoringContext = new OmniSharpRefactoringContext(doc, resolver, location);
            }
            refactoringContext.Services.AddService(typeof(NamingConventionService), new DefaultNameService());
            refactoringContext.Services.AddService(typeof(CodeGenerationService), new DefaultCodeGenerationService());
            return(refactoringContext);
        }
        public static OmniSharpRefactoringContext GetContext(BufferParser bufferParser, Request request)
        {
            var q                  = bufferParser.ParsedContent(request.Buffer, request.FileName);
            var resolver           = new CSharpAstResolver(q.Compilation, q.SyntaxTree, q.UnresolvedFile);
            var doc                = new StringBuilderDocument(request.Buffer);
            var location           = new TextLocation(request.Line, request.Column);
            var refactoringContext = new OmniSharpRefactoringContext(doc, resolver, location);

            return(refactoringContext);
        }
Пример #4
0
        public void Parse(IProject project, string fileName, string source)
        {
            this.FileName = fileName;
            this.Content  = new StringTextSource(source);
            this.Document = new StringBuilderDocument(this.Content);
            this.Project  = project;
            CSharpParser p = project.CreateParser();

            this.SyntaxTree = p.Parse(Content.CreateReader(), fileName);
            this.ParsedFile = this.SyntaxTree.ToTypeSystem();
        }
        public static TestRefactoringContext Create(string content)
        {
            int idx = content.IndexOf("$");

            if (idx >= 0)
            {
                content = content.Substring(0, idx) + content.Substring(idx + 1);
            }
            int idx1 = content.IndexOf("<-");
            int idx2 = content.IndexOf("->");

            int selectionStart = 0;
            int selectionEnd   = 0;

            if (0 <= idx1 && idx1 < idx2)
            {
                content        = content.Substring(0, idx2) + content.Substring(idx2 + 2);
                content        = content.Substring(0, idx1) + content.Substring(idx1 + 2);
                selectionStart = idx1;
                selectionEnd   = idx2 - 2;
                idx            = selectionEnd;
            }

            var doc    = new StringBuilderDocument(content);
            var parser = new CSharpParser();
            var unit   = parser.Parse(content, "program.cs");

            if (parser.HasErrors)
            {
                parser.ErrorPrinter.Errors.ForEach(e => Console.WriteLine(e.Message));
            }
            Assert.IsFalse(parser.HasErrors, "File contains parsing errors.");
            unit.Freeze();
            var parsedFile = unit.ToTypeSystem();

            IProjectContent pc = new CSharpProjectContent();

            pc = pc.UpdateProjectContent(null, parsedFile);
            pc = pc.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });

            var          compilation = pc.CreateCompilation();
            var          resolver    = new CSharpAstResolver(compilation, unit, parsedFile);
            TextLocation location    = TextLocation.Empty;

            if (idx >= 0)
            {
                location = doc.GetLocation(idx);
            }
            return(new TestRefactoringContext(doc, location, resolver)
            {
                selectionStart = selectionStart,
                selectionEnd = selectionEnd
            });
        }
Пример #6
0
        protected static FormattingChanges GetChanges(CSharpFormattingOptions policy, string input, out StringBuilderDocument document, FormattingMode mode = FormattingMode.Intrusive, TextEditorOptions options = null)
        {
            options = GetActualOptions(options);
            input   = NormalizeNewlines(input);

            document = new StringBuilderDocument(input);
            var visitor = new CSharpFormatter(policy, options);

            visitor.FormattingMode = mode;
            var syntaxTree = new CSharpParser().Parse(document, "test.cs");

            return(visitor.AnalyzeFormatting(document, syntaxTree));
        }
Пример #7
0
        private void Parse(IProject project, string fileName, string source)
        {
            Console.WriteLine("Loading " + fileName);
            this.FileName = fileName;
            this.Content  = new StringTextSource(source);
            this.Document = new StringBuilderDocument(this.Content);
            this.Project  = project;
            CSharpParser p = project.CreateParser();

            this.SyntaxTree = p.Parse(Content.CreateReader(), fileName);
            this.ParsedFile = this.SyntaxTree.ToTypeSystem();
            if (this.Project.ProjectContent != null)
            {
                this.Project.ProjectContent.AddOrUpdateFiles(this.ParsedFile);
            }
        }
        /*public static string ApplyChanges (string text, List<TextReplaceAction> changes)
         * {
         *      changes.Sort ((x, y) => y.Offset.CompareTo (x.Offset));
         *      StringBuilder b = new StringBuilder(text);
         *      foreach (var change in changes) {
         *              //Console.WriteLine ("---- apply:" + change);
         * //				Console.WriteLine (adapter.Text);
         *              if (change.Offset > b.Length)
         *                      continue;
         *              b.Remove(change.Offset, change.RemovedChars);
         *              b.Insert(change.Offset, change.InsertedText);
         *      }
         * //			Console.WriteLine ("---result:");
         * //			Console.WriteLine (adapter.Text);
         *      return b.ToString();
         * }*/

        protected static IDocument GetResult(CSharpFormattingOptions policy, string input, FormattingMode mode = FormattingMode.OnTheFly)
        {
            input = NormalizeNewlines(input);
            var document = new StringBuilderDocument(input);
            var options  = new TextEditorOptions();

            options.EolMarker = "\n";
            var visitor = new AstFormattingVisitor(policy, document, options);

            visitor.FormattingMode = mode;
            var compilationUnit = new CSharpParser().Parse(document, "test.cs");

            compilationUnit.AcceptVisitor(visitor);
            visitor.ApplyChanges();
            return(document);
        }
Пример #9
0
        public static string FormatCode(string text, CSharpFormattingOptions options, CancellationToken ct)
        {
            var formatter = new CSharpFormatter(options)
            {
                FormattingMode = FormattingMode.Intrusive
            };

            text = text.Replace("\r\n\r\n", "\r\n");

            var doc        = new StringBuilderDocument(text);
            var syntaxTree = SyntaxTree.Parse(doc, doc.FileName, null, ct);

            formatter.AnalyzeFormatting(doc, syntaxTree, ct).ApplyChanges();

            return(doc.Text);
        }
Пример #10
0
        /*public static string ApplyChanges (string text, List<TextReplaceAction> changes)
         * {
         *      changes.Sort ((x, y) => y.Offset.CompareTo (x.Offset));
         *      StringBuilder b = new StringBuilder(text);
         *      foreach (var change in changes) {
         *              //Console.WriteLine ("---- apply:" + change);
         * //				Console.WriteLine (adapter.Text);
         *              if (change.Offset > b.Length)
         *                      continue;
         *              b.Remove(change.Offset, change.RemovedChars);
         *              b.Insert(change.Offset, change.InsertedText);
         *      }
         * //			Console.WriteLine ("---result:");
         * //			Console.WriteLine (adapter.Text);
         *      return b.ToString();
         * }*/

        protected static IDocument GetResult(CSharpFormattingOptions policy, string input, FormattingMode mode = FormattingMode.Intrusive)
        {
            input = NormalizeNewlines(input);
            var document = new StringBuilderDocument(input);
            var options  = new TextEditorOptions();

            options.EolMarker      = "\n";
            options.WrapLineLength = 80;
            var visitor = new AstFormattingVisitor(policy, document, options);

            visitor.FormattingMode = mode;
            var syntaxTree = new CSharpParser().Parse(document, "test.cs");

            syntaxTree.AcceptVisitor(visitor);
            visitor.ApplyChanges();
            return(document);
        }
Пример #11
0
        public CodeFormatResponse Format(Request request)
        {
            var document = new StringBuilderDocument(request.Buffer);
            var options  = new TextEditorOptions();

            options.EolMarker      = Environment.NewLine;
            options.WrapLineLength = 80;
            var policy  = FormattingOptionsFactory.CreateAllman();
            var visitor = new AstFormattingVisitor(policy, document, options);

            visitor.FormattingMode = FormattingMode.Intrusive;
            var syntaxTree = new CSharpParser().Parse(document, request.FileName);

            syntaxTree.AcceptVisitor(visitor);
            visitor.ApplyChanges();
            return(new CodeFormatResponse(document.Text));
        }
        public void initializeExpr(Solution solution, int choice, string checkAccessMethodName)
        {
            foreach (var file in solution.AllFiles)
            {
                if (file.IndexOfWebMthdDecl.Count == 0 &&
                    file.IndexOfIfElStmt.Count == 0 &&
                    file.IndexOfTryCatchStmt.Count == 0 &&
                    file.IndexOfClassDecl.Count == 0 &&
                    file.IndexOfUsingDecl.Count == 0)
                {
                    continue;
                }

                file.syntaxTree.Freeze();

                // 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))
                {
                    switch (choice)
                    {
                    case 1:     //AddUsingAPIDecl(file, script);
                        RemoveAccessControlCheckAccess(file, script, checkAccessMethodName);
                        WriteValidationMethodStructure(file, script);
                        WriteIfElseStructureInWebmethodTry(file, script);

                        break;

                    case 2: WriteValidationMethodBody(file, script);
                        WriteAccessControlStmtInTryCatch(file, script, checkAccessMethodName);
                        InsertParametersIfElseInWebmethodTry(file, script);
                        DummyTextForTryCallValidation(file, script);
                        AddPageNameGlobalinClass(file, script);
                        CheckTryCatchInWebMethodBody(file, script);
                        break;
                    }
                }
                //File.WriteAllText(Path.ChangeExtension(file.fileName, ".output.cs"), document.Text);
                File.WriteAllText(file.fileName, document.Text);
            }
            Console.WriteLine("Done. Press Any Key to Exit..............");
        }
Пример #13
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);
        }
Пример #14
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);
        }
Пример #15
0
        /*public static string ApplyChanges (string text, List<TextReplaceAction> changes)
         * {
         *      changes.Sort ((x, y) => y.Offset.CompareTo (x.Offset));
         *      StringBuilder b = new StringBuilder(text);
         *      foreach (var change in changes) {
         *              //Console.WriteLine ("---- apply:" + change);
         * //				Console.WriteLine (adapter.Text);
         *              if (change.Offset > b.Length)
         *                      continue;
         *              b.Remove(change.Offset, change.RemovedChars);
         *              b.Insert(change.Offset, change.InsertedText);
         *      }
         * //			Console.WriteLine ("---result:");
         * //			Console.WriteLine (adapter.Text);
         *      return b.ToString();
         * }*/

        protected static IDocument GetResult(CSharpFormattingOptions policy, string input, FormattingMode mode = FormattingMode.Intrusive, TextEditorOptions options = null)
        {
            if (options == null)
            {
                options                = new TextEditorOptions();
                options.EolMarker      = "\n";
                options.WrapLineLength = 80;
            }


            input = NormalizeNewlines(input);
            var document = new StringBuilderDocument(input);
            var visitor  = new CSharpFormatter(policy, options);

            visitor.FormattingMode = mode;
            var syntaxTree = new CSharpParser().Parse(document, "test.cs");
            var changes    = visitor.AnalyzeFormatting(document, syntaxTree);

            changes.ApplyChanges();
            return(document);
        }
Пример #16
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);
        }
Пример #17
0
        static void Test(string input, string expectedOutput)
        {
            input          = input.Replace("\r\n", "\n");
            expectedOutput = expectedOutput.Replace("\r\n", "\n");
            int caretPositon = input.IndexOf('$');

            if (caretPositon > 0)
            {
                input = input.Substring(0, caretPositon) + input.Substring(caretPositon + 1);
            }

            var document1 = new StringBuilderDocument(input);

            int expectedCaretPosition = expectedOutput.IndexOf('$');

            if (expectedCaretPosition > 0)
            {
                expectedOutput = expectedOutput.Substring(0, expectedCaretPosition) + expectedOutput.Substring(expectedCaretPosition + 1);
            }

            var fixer = new ConstructFixer(FormattingOptionsFactory.CreateMono(), new TextEditorOptions {
                EolMarker = "\n"
            });
            int newCaretPosition;

            Assert.IsTrue(fixer.TryFix(document1, caretPositon, out newCaretPosition));
            var isEqual = expectedOutput == document1.Text.Replace("\r\n", "\n");

            if (!isEqual)
            {
                System.Console.WriteLine("expected:");
                System.Console.WriteLine(expectedOutput);
                System.Console.WriteLine("was:");
                System.Console.WriteLine(document1.Text);
            }
            Assert.IsTrue(isEqual);
            Assert.AreEqual(expectedCaretPosition, newCaretPosition);
        }
Пример #18
0
        private void Parse(IProject project, string fileName, string source)
        {
            Console.WriteLine("Loading " + fileName);
            this.FileName = fileName;
            this.Content  = new StringTextSource(source);
            this.Document = new StringBuilderDocument(this.Content);
            this.Project  = project;
            CSharpParser p = project.CreateParser();

            this.SyntaxTree = p.Parse(Content.CreateReader(), fileName);
            if (p.HasErrors)
            {
                Console.WriteLine("Error parsing " + fileName + ":");
                foreach (var error in p.Errors)
                {
                    Console.WriteLine("  " + error.Region + " " + error.Message);
                }
            }
            this.ParsedFile = this.SyntaxTree.ToTypeSystem();
            if (this.Project.ProjectContent != null)
            {
                this.Project.ProjectContent.AddOrUpdateFiles(this.ParsedFile);
            }
        }
Пример #19
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;
             *          }
             *
             */



            List <string> list = new List <string>();

            Solution solution = new Solution("C:\\Martin\\GitHub\\HotFixForUnity\\AddMethodTool\\AddMethod.sln");

            //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");
//                      }
//                  }
                    using (var script = new DocumentScript(document, formattingOptions, options))
                    {
                        CSharpParser parser = new CSharpParser();
                        //SyntaxTree syntaxTree = parser.Parse(code, srcFilePath);
                        SyntaxTree syntaxTree = file.SyntaxTree;
                        foreach (var classDec in syntaxTree.Descendants.OfType <TypeDeclaration>())
                        {
                            if (classDec.ClassType == ClassType.Class || classDec.ClassType == ClassType.Struct)
                            {
                                var className = classDec.Name;
                                foreach (var method in classDec.Children.OfType <MethodDeclaration>())
                                {
                                    var returnType = method.ReturnType.ToString();
                                    if (returnType.Contains("IEnumerator") || returnType.Contains("IEnumerable"))  // 暂不支持yield!
                                    {
                                        continue;
                                    }

                                    Console.WriteLine("className:" + className + "   method:" + method.Name);
                                    AstNodeCollection <ParameterDeclaration> paramlist = method.Parameters;


                                    string strParaType = string.Format("{0},{1}", className, method.Name);
                                    string numberType  = ",{0}";
                                    string numberPara  = ", typeof(object)";//兼容性思路,无论是静态还是非静态都传入object
                                    string strPara     = ", null";
                                    if ((method.Modifiers & Modifiers.Static) != Modifiers.Static)
                                    {
                                        strPara = ", this";
                                    }
                                    int number = 1;
                                    foreach (ParameterDeclaration param in paramlist)
                                    {
                                        Console.WriteLine("param    " + param.Name);
                                        strPara    += string.Format(", {0}", param.Name);
                                        numberType += string.Format(",{0}{1}{2}", "{", number, "}");
                                        numberPara += string.Format(", typeof({0})", param.Type);
                                        number++;
                                    }



                                    int offset = script.GetCurrentOffset(method.Body.LBraceToken.StartLocation);
                                    script.InsertText(offset + 1, "\n" +
                                                      "\n" +
                                                      string.Format("if (FixUtil.Instance.NeedFix(\"{0}.{1}\"))\n", className, method.Name) +
                                                      "{\n" +
                                                      string.Format("    string strParameter = string.Format(\"{0}{1}\"{2});\n", strParaType, numberType, numberPara) +
                                                      string.Format("    FixUtil.Instance.Fix(strParameter{0});\n", strPara) +
                                                      "    return;\n" +
                                                      "}\n");

//                script.InsertText(offset + 1, "\n" +
//                                              "\n" +
//                                string.Format("if (FixUtil.Instance.NeedFix("+className+"."+method.Name+"))\n" +
//                                              "{\n" +
//                                string.Format("    FixUtil.Instance.Fix(\"{0}.{1}\"{2});\n", className, method.Name, str) +
//                                              "    return;\n" +
//                                              "}\n");
                                }
                            }
                        }
                    }
                    File.WriteAllText(Path.ChangeExtension(file.FileName, ".output.cs"), document.Text);
                }


                string text = Console.ReadLine();
            }
        }
Пример #20
0
        private string GetMethodContentsFor(SyntaxTree syntaxTree, StringBuilderDocument document, string methodName, out bool wasFound)
        {
            ICSharpCode.NRefactory.CSharp.NamespaceDeclaration namespaceDecl = null;
            TypeDeclaration   classDecl      = null;
            MethodDeclaration methodDecl     = null;
            BlockStatement    blockStatement = null;
            string            toReturn       = null;

            ICSharpCode.NRefactory.TextLocation?start = null;
            ICSharpCode.NRefactory.TextLocation?end   = null;


            foreach (var child in syntaxTree.Children)
            {
                if (child is ICSharpCode.NRefactory.CSharp.NamespaceDeclaration)
                {
                    namespaceDecl = child as NamespaceDeclaration;
                    break;
                }
            }

            if (namespaceDecl != null)
            {
                foreach (var child in namespaceDecl.Children)
                {
                    if (child is TypeDeclaration)
                    {
                        classDecl = child as TypeDeclaration;
                        break;
                    }
                }
            }
            if (classDecl != null)
            {
                foreach (var child in classDecl.Children)
                {
                    if (child is MethodDeclaration && (child as MethodDeclaration).Name == "On" + methodName)
                    {
                        methodDecl = child as MethodDeclaration;
                        break;
                    }
                }
            }

            if (methodDecl != null)
            {
                foreach (var child in methodDecl.Children)
                {
                    if (child is BlockStatement)
                    {
                        blockStatement = child as BlockStatement;
                        break;
                    }
                }
            }

            if (blockStatement != null)
            {
                foreach (var child in blockStatement.Children)
                {
                    if ((child is CSharpTokenNode) == false)
                    {
                        if (start == null)
                        {
                            start = child.StartLocation;
                        }
                        end = child.EndLocation;
                    }
                }
            }

            if (start.HasValue)
            {
                int offset = document.GetOffset(start.Value);
                int length = document.GetOffset(end.Value) - offset;
                wasFound = true;
                return(document.GetText(offset, length));
            }
            else if (blockStatement != null)
            {
                // we found a pure empty method
                wasFound = true;
                return("");
            }
            else
            {
                wasFound = false;
                return(null);
            }
        }
Пример #21
0
        public void UpdateDisplayToCurrentObject()
        {
            string fullFileName = "<Unable to get file name>";

            try
            {
                EventResponseSave eventResponseSave = EditorLogic.CurrentEventResponseSave;
                IElement          element           = EditorLogic.CurrentElement;

                fullFileName = eventResponseSave.GetSharedCodeFullFileName();

                string contents = FileManager.FromFileText(fullFileName);

                CSharpParser parser     = new CSharpParser();
                SyntaxTree   syntaxTree = parser.Parse(contents);
                mIsCodeValid = syntaxTree.Errors.Count == 0;

                if (mIsCodeValid)
                {
                    ParsedMethod parsedMethod = eventResponseSave.GetParsedMethodFromAssociatedFile();

                    string textToAssign = null;
                    if (parsedMethod == null)
                    {
                        textToAssign = eventResponseSave.GetEventContents();
                    }
                    else
                    {
                        StringBuilderDocument document = new StringBuilderDocument(contents);

                        bool wasFound;

                        textToAssign = GetMethodContentsFor(syntaxTree, document, eventResponseSave.EventName, out wasFound);
                        if (wasFound)
                        {
                            textToAssign = textToAssign.Replace("\n", "\r\n");
                        }
                        else
                        {
                            mIsCodeValid = false;
                            textToAssign = "Could not find the method, or encountered a parse error.";
                        }
                    }

                    textToAssign = RemoveWhiteSpaceForCodeWindow(textToAssign);
                    this.syntaxBoxControl1.Document.Text = textToAssign;
                    mLastSavedText = this.syntaxBoxControl1.Document.Text;
                }
                else
                {
                    this.syntaxBoxControl1.Document.Text = "This code file is not a complete code file:\n" +
                                                           fullFileName +
                                                           "\nGlue is unable to parse it.  Please correct the problems in Visual Studio";
                }
            }
            catch (Exception e)
            {
                mIsCodeValid = false;
                this.syntaxBoxControl1.Document.Text = "Error parsing file:\n" +
                                                       fullFileName +
                                                       "\nMore details:\n\n" + e.ToString();
            }
        }
Пример #22
0
        public static TestRefactoringContext Create(string content, bool expectErrors = false)
        {
            int idx = content.IndexOf("$");

            if (idx >= 0)
            {
                content = content.Substring(0, idx) + content.Substring(idx + 1);
            }
            int idx1 = content.IndexOf("<-");
            int idx2 = content.IndexOf("->");

            int selectionStart = 0;
            int selectionEnd   = 0;

            if (0 <= idx1 && idx1 < idx2)
            {
                content        = content.Substring(0, idx2) + content.Substring(idx2 + 2);
                content        = content.Substring(0, idx1) + content.Substring(idx1 + 2);
                selectionStart = idx1;
                selectionEnd   = idx2 - 2;
                idx            = selectionEnd;
            }

            var doc    = new StringBuilderDocument(content);
            var parser = new CSharpParser();
            var unit   = parser.Parse(content, "program.cs");

            if (!expectErrors)
            {
                if (parser.HasErrors)
                {
                    Console.WriteLine(content);
                    Console.WriteLine("----");
                }
                foreach (var error in parser.Errors)
                {
                    Console.WriteLine(error.Message);
                }
                Assert.IsFalse(parser.HasErrors, "The file contains unexpected parsing errors.");
            }
            else
            {
                Assert.IsTrue(parser.HasErrors, "Expected parsing errors, but the file doesn't contain any.");
            }

            unit.Freeze();
            var unresolvedFile = unit.ToTypeSystem();

            IProjectContent pc = new CSharpProjectContent();

            pc = pc.AddOrUpdateFiles(unresolvedFile);
            pc = pc.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });

            var          compilation = pc.CreateCompilation();
            var          resolver    = new CSharpAstResolver(compilation, unit, unresolvedFile);
            TextLocation location    = TextLocation.Empty;

            if (idx >= 0)
            {
                location = doc.GetLocation(idx);
            }
            return(new TestRefactoringContext(doc, location, resolver)
            {
                selectionStart = selectionStart,
                selectionEnd = selectionEnd
            });
        }
Пример #23
0
        public static TestRefactoringContext Create(List <string> contents, int mainIndex, bool expectErrors = false)
        {
            List <int>                  indexes         = new List <int>();
            List <int>                  selectionStarts = new List <int>();
            List <int>                  selectionEnds   = new List <int>();
            List <IDocument>            documents       = new List <IDocument>();
            List <CSharpUnresolvedFile> unresolvedFiles = new List <CSharpUnresolvedFile>();
            List <SyntaxTree>           units           = new List <SyntaxTree>();

            for (int i = 0; i < contents.Count; i++)
            {
                string content = contents[i];
                int    idx     = content.IndexOf("$");
                if (idx >= 0)
                {
                    content = content.Substring(0, idx) + content.Substring(idx + 1);
                }
                int idx1           = content.IndexOf("<-");
                int idx2           = content.IndexOf("->");
                int selectionStart = 0;
                int selectionEnd   = 0;
                if (0 <= idx1 && idx1 < idx2)
                {
                    content        = content.Substring(0, idx2) + content.Substring(idx2 + 2);
                    content        = content.Substring(0, idx1) + content.Substring(idx1 + 2);
                    selectionStart = idx1;
                    selectionEnd   = idx2 - 2;
                    idx            = selectionEnd;
                }
                indexes.Add(idx);
                selectionStarts.Add(selectionStart);
                selectionEnds.Add(selectionEnd);
                var doc    = new StringBuilderDocument(content);
                var parser = new CSharpParser();
                var unit   = parser.Parse(content, "program_" + i + ".cs");
                if (!expectErrors)
                {
                    if (parser.HasErrors)
                    {
                        Console.WriteLine(content);
                        Console.WriteLine("----");
                    }
                    foreach (var error in parser.Errors)
                    {
                        Console.WriteLine(error.Message);
                    }
                    Assert.IsFalse(parser.HasErrors, "The file " + i + " contains unexpected parsing errors.");
                }
                else
                {
                    Assert.IsTrue(parser.HasErrors, "Expected parsing errors, but the file " + i + "doesn't contain any.");
                }
                unit.Freeze();
                CSharpUnresolvedFile unresolvedFile = unit.ToTypeSystem();
                units.Add(unit);
                documents.Add(doc);
                unresolvedFiles.Add(unresolvedFile);
            }

            IProjectContent pc = new CSharpProjectContent();

            pc = pc.AddOrUpdateFiles(unresolvedFiles);
            pc = pc.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });

            var compilation = pc.CreateCompilation();
            List <TestRefactoringContext> contexts = new List <TestRefactoringContext>();

            for (int documentIndex = 0; documentIndex < documents.Count; ++documentIndex)
            {
                var          doc      = documents [documentIndex];
                var          resolver = new CSharpAstResolver(compilation, units[documentIndex], unresolvedFiles[documentIndex]);
                TextLocation location = TextLocation.Empty;
                if (indexes[documentIndex] >= 0)
                {
                    location = doc.GetLocation(indexes[documentIndex]);
                }
                var context = new TestRefactoringContext(doc, location, resolver)
                {
                    selectionStart  = selectionStarts[documentIndex],
                    selectionEnd    = selectionEnds[documentIndex],
                    projectContexts = contexts
                };

                contexts.Add(context);
            }

            return(contexts [mainIndex]);
        }
Пример #24
0
        /// <summary>
        /// 代码注入! GOGOGO
        /// </summary>
        /// <param name="srcFilePath"></param>
        /// <param name="outputFilePath"></param>
        public void Inject(string srcFilePath, string outputFilePath)
        {
            UTF8Encoding utf8 = new UTF8Encoding(false);

            var predefineSymbolsSb = new StringBuilder();

            if (_defineSymbols != null)
            {
                foreach (var symbol in _defineSymbols)
                {
                    predefineSymbolsSb.AppendFormat("#define {0}\n", symbol);
                }
            }

            var code = File.ReadAllText(srcFilePath, Encoding.UTF8);

            code = predefineSymbolsSb.ToString() + code;  // 加入宏

            var document          = new StringBuilderDocument(code);
            var formattingOptions = FormattingOptionsFactory.CreateAllman();
            var options           = new TextEditorOptions();

            using (var script = new DocumentScript(document, formattingOptions, options))
            {
                CSharpParser parser     = new CSharpParser();
                SyntaxTree   syntaxTree = parser.Parse(code, srcFilePath);
                foreach (var classDec in syntaxTree.Descendants.OfType <TypeDeclaration>())
                {
                    if (classDec.ClassType == ClassType.Class || classDec.ClassType == ClassType.Struct)
                    {
                        var className = classDec.Name;
                        foreach (var method in classDec.Children.OfType <MethodDeclaration>())
                        {
                            var returnType = method.ReturnType.ToString();
                            if (returnType.Contains("IEnumerator") || returnType.Contains("IEnumerable"))  // 暂不支持yield!
                            {
                                continue;
                            }

                            var methodSegment = script.GetSegment(method);
                            var methodOffset  = methodSegment.Offset;  // 方法偏移

                            var paramsTypes     = method.Parameters;   //method.Children.OfType<ParameterDeclaration>();// typeName
                            var paramsTypesStrs = new List <string>(); // 参数
                            if (!method.HasModifier(Modifiers.Static))
                            {
                                paramsTypesStrs.Add("this");         // 非静态方法,加this
                            }
                            var paramsOutStrs = new List <string>(); // out 的参数
                            foreach (var paramsType in paramsTypes)
                            {
                                paramsTypesStrs.Add(paramsType.Name);
                                if (paramsType.ParameterModifier == ParameterModifier.Out)
                                {
                                    // out 的参数
                                    paramsOutStrs.Add(string.Format("{0} = default({1});", paramsType.Name, paramsType.Type));
                                }
                            }

                            if (_beforeInsert != null)
                            {
                                var insertBeforeText = _beforeInsert(className, method.Name, returnType,
                                                                     paramsTypesStrs.ToArray(), paramsOutStrs.ToArray());
                                if (!string.IsNullOrEmpty(insertBeforeText))
                                {
                                    script.InsertText(methodOffset, insertBeforeText);
                                }
                            }

                            foreach (var blockStatement in method.Descendants.OfType <BlockStatement>())
                            {
                                int insertOffset;
                                if (blockStatement.Statements.Count == 0) // 空函数
                                {
                                    var segment = script.GetSegment(blockStatement);
                                    insertOffset = segment.Offset + 1; // 越过"/"
                                }
                                else
                                {
                                    var firstChildStatement = blockStatement.Statements.First();
                                    var segment             = script.GetSegment(firstChildStatement);
                                    insertOffset = segment.Offset;
                                }
                                script.InsertText(insertOffset, _afterInsert(className, method.Name, returnType, paramsTypesStrs.ToArray(), paramsOutStrs.ToArray()));
                                break; // 仅对第一个方法包体(BlockStatement), 其它不是方法进行处理
                            }
                        }
                    }
                }
            }
            var resultText = document.Text;

            resultText = resultText.Substring(predefineSymbolsSb.Length); // 移除宏定义
            File.WriteAllText(outputFilePath, resultText, utf8);
        }