public override async void Execute(EditorRefactoringContext context)
        {
            SyntaxTree st = await context.GetSyntaxTreeAsync().ConfigureAwait(false);

            ICompilation compilation = await context.GetCompilationAsync().ConfigureAwait(false);

            CSharpFullParseInformation info = await context.GetParseInformationAsync().ConfigureAwait(false) as CSharpFullParseInformation;

            EntityDeclaration node     = (EntityDeclaration)st.GetNodeAt(context.CaretLocation, n => n is TypeDeclaration || n is DelegateDeclaration);
            IDocument         document = context.Editor.Document;

            FileName newFileName = FileName.Create(Path.Combine(Path.GetDirectoryName(context.FileName), MakeValidFileName(node.Name)));
            string   header      = CopyFileHeader(document, info);
            string   footer      = CopyFileEnd(document, info);

            AstNode newNode = node.Clone();

            foreach (var ns in node.Ancestors.OfType <NamespaceDeclaration>())
            {
                var newNS = new NamespaceDeclaration(ns.Name);
                newNS.Members.AddRange(ns.Children.Where(ch => ch is UsingDeclaration ||
                                                         ch is UsingAliasDeclaration ||
                                                         ch is ExternAliasDeclaration).Select(usingDecl => usingDecl.Clone()));
                newNS.AddMember(newNode);
                newNode = newNS;
            }

            var topLevelUsings = st.Children.Where(ch => ch is UsingDeclaration ||
                                                   ch is UsingAliasDeclaration ||
                                                   ch is ExternAliasDeclaration);
            StringBuilder       newCode = new StringBuilder(header);
            CSharpOutputVisitor visitor = new CSharpOutputVisitor(new StringWriter(newCode), FormattingOptionsFactory.CreateSharpDevelop());

            foreach (var topLevelUsing in topLevelUsings)
            {
                topLevelUsing.AcceptVisitor(visitor);
            }

            newNode.AcceptVisitor(visitor);

            newCode.AppendLine(footer);

            IViewContent viewContent = FileService.NewFile(newFileName, newCode.ToString());

            viewContent.PrimaryFile.SaveToDisk(newFileName);
            // now that the code is saved in the other file, remove it from the original document
            RemoveExtractedNode(context, node);

            IProject project = (IProject)compilation.GetProject();

            if (project != null)
            {
                FileProjectItem projectItem = new FileProjectItem(project, ItemType.Compile);
                projectItem.FileName = newFileName;
                ProjectService.AddProjectItem(project, projectItem);
                FileService.FireFileCreated(newFileName, false);
                project.Save();
                ProjectBrowserPad.RefreshViewAsync();
            }
        }
        public override void Execute(EditorRefactoringContext context)
        {
            CSharpFullParseInformation parseInformation = context.GetParseInformation() as CSharpFullParseInformation;

            if (parseInformation != null)
            {
                SyntaxTree st         = parseInformation.SyntaxTree;
                Identifier identifier = (Identifier)st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
                if (identifier == null)
                {
                    return;
                }
                TypeDeclaration interfaceTypeDeclaration = identifier.Parent as TypeDeclaration;
                if (interfaceTypeDeclaration != null)
                {
                    // Generate abstract class from interface and abstract members from interface members
                    TypeDeclaration abstractClassTypeNode = (TypeDeclaration)interfaceTypeDeclaration.Clone();
                    abstractClassTypeNode.ClassType  = ClassType.Class;
                    abstractClassTypeNode.Modifiers |= Modifiers.Abstract;
                    foreach (var entity in abstractClassTypeNode.Children.OfType <EntityDeclaration>())
                    {
                        entity.Modifiers |= Modifiers.Abstract | Modifiers.Public;
                    }

                    var refactoringContext = SDRefactoringContext.Create(context.Editor, CancellationToken.None);
                    using (Script script = refactoringContext.StartScript()) {
                        // Replace interface node with node of abstract class
                        script.Replace(interfaceTypeDeclaration, abstractClassTypeNode);
                    }
                }
            }
        }
        public override void Execute(EditorRefactoringContext context)
        {
            CSharpFullParseInformation parseInformation = context.GetParseInformation() as CSharpFullParseInformation;

            if (parseInformation != null)
            {
                SyntaxTree st         = parseInformation.SyntaxTree;
                Identifier identifier = (Identifier)st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
                if (identifier == null)
                {
                    return;
                }
                ParameterDeclaration parameterDeclaration = identifier.Parent as ParameterDeclaration;
                if (parameterDeclaration == null)
                {
                    return;
                }

                AstNode grandparent = identifier.Parent.Parent;
                if ((grandparent is MethodDeclaration) || (grandparent is ConstructorDeclaration))
                {
                    // Range check condition
                    var rangeCheck = new IfElseStatement(
                        new BinaryOperatorExpression(
                            new BinaryOperatorExpression(new IdentifierExpression(identifier.Name), BinaryOperatorType.LessThan, new IdentifierExpression("lower")),
                            BinaryOperatorType.ConditionalOr,
                            new BinaryOperatorExpression(new IdentifierExpression(identifier.Name), BinaryOperatorType.GreaterThan, new IdentifierExpression("upper"))
                            ),
                        new ThrowStatement(
                            new ObjectCreateExpression(
                                new SimpleType("ArgumentOutOfRangeException"),
                                new List <Expression>()
                    {
                        new PrimitiveExpression(identifier.Name, '"' + identifier.Name + '"'), new IdentifierExpression(identifier.Name), new BinaryOperatorExpression(new PrimitiveExpression("Value must be between "), BinaryOperatorType.Add, new BinaryOperatorExpression(new IdentifierExpression("lower"), BinaryOperatorType.Add, new BinaryOperatorExpression(new PrimitiveExpression(" and "), BinaryOperatorType.Add, new IdentifierExpression("upper"))))
                    }
                                )
                            )
                        );

                    // Add range check as first statement in method's/constructor's body
                    var refactoringContext = SDRefactoringContext.Create(context.Editor, CancellationToken.None);
                    using (Script script = refactoringContext.StartScript()) {
                        if (grandparent is MethodDeclaration)
                        {
                            var methodDeclaration = (MethodDeclaration)grandparent;
                            script.AddTo(methodDeclaration.Body, rangeCheck);
                        }
                        else if (grandparent is ConstructorDeclaration)
                        {
                            var ctorDeclaration = (ConstructorDeclaration)grandparent;
                            script.AddTo(ctorDeclaration.Body, rangeCheck);
                        }
                    }
                }
            }
        }
        public void EndHighlighting()
        {
            inHighlightingGroup = false;
            visitor.Resolver    = null;
            this.parseInfo      = null;

            // TODO use this to remove cached lines which are no longer visible
//			var visibleDocumentLines = new HashSet<IDocumentLine>(syntaxHighlighter.GetVisibleDocumentLines());
//			cachedLines.RemoveAll(c => !visibleDocumentLines.Contains(c.DocumentLine));
        }
 public void Dispose()
 {
     if (eventHandlersAreRegistered)
     {
         SD.ParserService.ParseInformationUpdated             -= ParserService_ParseInformationUpdated;
         SD.ParserService.LoadSolutionProjectsThread.Finished -= ParserService_LoadSolutionProjectsThreadEnded;
         eventHandlersAreRegistered = false;
     }
     this.visitor.Dispose();
     this.parseInfo = null;
 }
Esempio n. 6
0
        string CopyFileHeader(IDocument document, CSharpFullParseInformation info)
        {
            var lastHeadNode = info.SyntaxTree.Children
                               .TakeWhile(node => node.NodeType == NodeType.Whitespace && (!(node is Comment) || !((Comment)node).IsDocumentation))
                               .LastOrDefault();

            if (lastHeadNode == null)
            {
                return("");
            }
            return(document.GetText(0, document.GetOffset(lastHeadNode.EndLocation)));
        }
Esempio n. 7
0
        string CopyFileEnd(IDocument document, CSharpFullParseInformation info)
        {
            var firstFootNode = info.SyntaxTree.Children.Reverse()
                                .TakeWhile(node => node.NodeType == NodeType.Whitespace && (!(node is Comment) || !((Comment)node).IsDocumentation))
                                .LastOrDefault();

            if (firstFootNode == null)
            {
                return("");
            }
            int offset = document.GetOffset(firstFootNode.StartLocation);

            return(document.GetText(offset, document.TextLength - offset));
        }
        public CSharpDesignerGenerator(ICSharpDesignerLoaderContext context)
        {
            this.context          = context;
            this.primaryParseInfo = context.GetPrimaryFileParseInformation();
            this.compilation      = context.GetCompilation();

            // Find designer class
            formClass            = FormsDesignerSecondaryDisplayBinding.GetDesignableClass(primaryParseInfo.UnresolvedFile, compilation, out primaryPart);
            initializeComponents = FormsDesignerSecondaryDisplayBinding.GetInitializeComponents(formClass);
            if (initializeComponents == null)
            {
                throw new FormsDesignerLoadException("Could not find InitializeComponents");
            }
        }
Esempio n. 9
0
 private CSharpCompletionContext(ITextEditor editor, CSharpFullParseInformation parseInfo, ICompilation compilation, IProjectContent projectContent, IDocument document, TextLocation caretLocation)
 {
     Debug.Assert(editor != null);
     Debug.Assert(parseInfo != null);
     Debug.Assert(compilation != null);
     Debug.Assert(projectContent != null);
     Debug.Assert(document != null);
     this.Editor                    = editor;
     this.Document                  = document;
     this.ParseInformation          = parseInfo;
     this.Compilation               = compilation;
     this.ProjectContent            = projectContent;
     this.TypeResolveContextAtCaret = parseInfo.UnresolvedFile.GetTypeResolveContext(compilation, caretLocation);
     this.CompletionContextProvider = new DefaultCompletionContextProvider(document, parseInfo.UnresolvedFile);
 }
 /// <summary>
 /// Retrieves the declaration for the specified entity.
 /// Returns null if the entity is not defined in C# source code.
 /// </summary>
 public static EntityDeclaration GetDeclaration(this IEntity entity, out CSharpFullParseInformation parseInfo)
 {
     if (entity == null || string.IsNullOrEmpty(entity.Region.FileName))
     {
         parseInfo = null;
         return(null);
     }
     parseInfo = SD.ParserService.Parse(FileName.Create(entity.Region.FileName),
                                        parentProject: entity.ParentAssembly.GetProject())
                 as CSharpFullParseInformation;
     if (parseInfo == null)
     {
         return(null);
     }
     return(parseInfo.SyntaxTree.GetNodeAt <EntityDeclaration>(entity.Region.Begin));
 }
Esempio n. 11
0
        public override string GetDisplayName(EditorRefactoringContext context)
        {
            CSharpFullParseInformation parseInformation = context.GetParseInformation() as CSharpFullParseInformation;

            if (parseInformation != null)
            {
                SyntaxTree st         = parseInformation.SyntaxTree;
                Identifier identifier = (Identifier)st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
                if (identifier == null)
                {
                    return(DisplayName);
                }

                return(StringParser.Parse("${res:SharpDevelop.Refactoring.MoveClassToFile}",
                                          new StringTagPair("FileName", MakeValidFileName(identifier.Name))));
            }

            return(DisplayName);
        }
Esempio n. 12
0
        void FindCurrentReferences(int start, int end)
        {
            ICompilation compilation             = SD.ParserService.GetCompilationForFile(editor.FileName);
            CSharpFullParseInformation parseInfo = SD.ParserService.GetCachedParseInformation(editor.FileName) as CSharpFullParseInformation;

            if (currentSymbolReference == null || parseInfo == null)
            {
                return;
            }

            IResolveVisitorNavigator currentNavigator = InitNavigator(compilation);
            CSharpAstResolver        resolver         = parseInfo.GetResolver(compilation);

            if (currentNavigator == null || resolver == null)
            {
                return;
            }

            VisitVisibleNodes(parseInfo.SyntaxTree, currentNavigator, resolver, start, end);
        }
Esempio n. 13
0
        public override void Execute(EditorRefactoringContext context)
        {
            CSharpFullParseInformation parseInformation = context.GetParseInformation() as CSharpFullParseInformation;

            if (parseInformation != null)
            {
                SyntaxTree st         = parseInformation.SyntaxTree;
                Identifier identifier = (Identifier)st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
                if (identifier == null)
                {
                    return;
                }

                ICompilation compilation = context.GetCompilation();
                IProject     project     = compilation.GetProject();
                RenameFile(project, context.FileName, Path.Combine(Path.GetDirectoryName(context.FileName), MakeValidFileName(identifier.Name)));
                if (project != null)
                {
                    project.Save();
                }
            }
        }
Esempio n. 14
0
        async void RunAnalysis(ITextSource textSource, CSharpFullParseInformation parseInfo)
        {
            if (markerService == null)
            {
                return;
            }
            if (cancellationTokenSource != null)
            {
                cancellationTokenSource.Cancel();
            }
            cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken        = cancellationTokenSource.Token;
            List <InspectionTag> results = new List <InspectionTag>();

            try {
                await Task.Run(
                    delegate {
                    var compilation = SD.ParserService.GetCompilationForFile(parseInfo.FileName);
                    var resolver    = parseInfo.GetResolver(compilation);
                    var context     = new SDRefactoringContext(textSource, resolver, new TextLocation(0, 0), 0, 0, cancellationToken);
                    foreach (var issueProvider in issueProviders.Value)
                    {
                        if (issueProvider.CurrentSeverity == Severity.None)
                        {
                            continue;
                        }

                        foreach (var issue in issueProvider.GetIssues(context))
                        {
                            if (issue.Start.IsEmpty || issue.End.IsEmpty)
                            {
                                // Issues can occur on invalid locations when analyzing incomplete code.
                                // We'll just ignore them.
                                continue;
                            }
                            results.Add(new InspectionTag(
                                            this,
                                            issueProvider,
                                            textSource.Version,
                                            issue.Description,
                                            context.GetOffset(issue.Start),
                                            context.GetOffset(issue.End),
                                            issue.IssueMarker,
                                            issue.Actions));
                        }
                    }
                }, cancellationToken);
            } catch (TaskCanceledException) {
            } catch (OperationCanceledException) {
            } catch (Exception ex) {
                SD.Log.WarnFormatted("IssueManager crashed: {0}", ex);
                SD.AnalyticsMonitor.TrackException(ex);
            }
            if (!cancellationToken.IsCancellationRequested)
            {
                analyzedVersion = textSource.Version;
                Clear();
                foreach (var newResult in results)
                {
                    newResult.CreateMarker(editor.Document, markerService);
                }
                existingResults = results;
            }
            if (cancellationTokenSource != null && cancellationTokenSource.Token == cancellationToken)
            {
                // Dispose the cancellation token source if it's still the same one as we originally created
                cancellationTokenSource.Dispose();
                cancellationTokenSource = null;
            }
        }
        HighlightedLine DoHighlightLine(int lineNumber, IDocumentLine documentLine, CachedLine cachedLine, ITextSourceVersion newVersion)
        {
            if (parseInfo == null)
            {
                if (forceParseOnNextRefresh)
                {
                    forceParseOnNextRefresh = false;
                    parseInfo = SD.ParserService.Parse(FileName.Create(document.FileName), document) as CSharpFullParseInformation;
                }
                else
                {
                    parseInfo = SD.ParserService.GetCachedParseInformation(FileName.Create(document.FileName), newVersion) as CSharpFullParseInformation;
                }
            }
            if (parseInfo == null)
            {
                if (invalidLines != null && !invalidLines.Contains(documentLine))
                {
                    invalidLines.Add(documentLine);
                    //Debug.WriteLine("Semantic highlighting for line {0} - marking as invalid", lineNumber);
                }

                if (cachedLine != null)
                {
                    // If there's a cached version, adjust it to the latest document changes and return it.
                    // This avoids flickering when changing a line that contains semantic highlighting.
                    cachedLine.Update(newVersion);
                                        #if DEBUG
                    cachedLine.HighlightedLine.ValidateInvariants();
                                        #endif
                    return(cachedLine.HighlightedLine);
                }
                else
                {
                    return(null);
                }
            }

            if (visitor.Resolver == null)
            {
                var compilation = SD.ParserService.GetCompilationForFile(parseInfo.FileName);
                visitor.Resolver = parseInfo.GetResolver(compilation);
            }

            line            = new HighlightedLine(document, documentLine);
            this.lineNumber = lineNumber;
            visitor.UpdateLineInformation(lineNumber);

            if (Debugger.IsAttached)
            {
                parseInfo.SyntaxTree.AcceptVisitor(visitor);
                                #if DEBUG
                line.ValidateInvariants();
                                #endif
            }
            else
            {
                try {
                    parseInfo.SyntaxTree.AcceptVisitor(visitor);
                                        #if DEBUG
                    line.ValidateInvariants();
                                        #endif
                } catch (Exception ex) {
                    hasCrashed = true;
                    throw new ApplicationException("Error highlighting line " + lineNumber, ex);
                }
            }
            //Debug.WriteLine("Semantic highlighting for line {0} - added {1} sections", lineNumber, line.Sections.Count);
            if (cachedLines != null && document.Version != null)
            {
                cachedLines.Add(new CachedLine(line, document.Version));
            }
            return(line);
        }