Example #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;
        }
        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 ());
            return refactoringContext;
        }
Example #3
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); 
		}
 private OmniSharpRefactoringContext GetRefactoringContext(Request req)
 {
     var q = _bufferParser.ParsedContent(req.Buffer, req.FileName);
     var resolver = new CSharpAstResolver(q.Compilation, q.SyntaxTree, q.UnresolvedFile);
     var doc = new StringBuilderDocument(req.Buffer);
     var location = new TextLocation(req.Line, req.Column);
     var refactoringContext = new OmniSharpRefactoringContext(doc, location, resolver);
     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;
 }
Example #6
0
        //public static CSharpFormattingOptions tModLoaderFormat = FormattingOptionsFactory.CreateAllman();

        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;
        }
Example #7
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();
 }
		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);
		}
		/*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;
		}
 /*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 CSharpFormatter (policy, options);
     visitor.FormattingMode = mode;
     var syntaxTree = new CSharpParser ().Parse (document, "test.cs");
     var changes = visitor.AnalyzeFormatting(document, syntaxTree);
     changes.ApplyChanges();
     return document;
 }
Example #11
0
 public CodeFormatResponse Format(CodeFormatRequest request)
 {
     var document = new StringBuilderDocument(request.Buffer);
     var options = new TextEditorOptions();
     options.EolMarker = Environment.NewLine;
     options.WrapLineLength = 80;
     options.TabsToSpaces = request.ExpandTab;
     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);
 }
Example #12
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;
 }
Example #13
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;
 }
Example #14
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.");
        }
        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
            };
        }
Example #16
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);
                }
            }
        }
Example #17
0
			public SimpleAnchor(StringBuilderDocument document, int offset)
			{
				this.document = document;
				this.offset = offset;
			}
		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
			};
		}
Example #19
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;
            }
        }
Example #20
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();
            }
        }
 public SimpleAnchor(StringBuilderDocument document, int offset)
 {
     this.document = document;
     this.offset   = offset;
 }
		public static TestRefactoringContext Create (List<string> contents, int mainIndex, bool expectErrors = false, CSharpParser parser = null)
		{
			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);
				if (parser == null)
					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.ErrorsAndWarnings) {
						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,
					version = parser.CompilerSettings.LanguageVersion,
					defaultNamespace = "Test"
				};

				contexts.Add(context);
			}

			return contexts [mainIndex];
		}