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; }
public IEnumerable<QuickFix> CodeCheck(Request request) { var errors = new List<QuickFix>(); var syntaxErrors = _syntaxErrorsHandler.FindSyntaxErrors(request) .Errors.Select( x => new QuickFix {Column = x.Column, FileName = x.FileName, Line = x.Line, Text = x.Message, LogLevel = "Error"}); errors.AddRange(syntaxErrors); if (errors.Any()) { return errors; } var semanticErrors = _semanticErrorsHandler.FindSemanticErrors(request) .Errors.Select( x => new QuickFix {Column = x.Column, FileName = x.FileName, Line = x.Line, Text = x.Message , LogLevel = "Error"}); errors.AddRange(semanticErrors); if (errors.Any()) { return errors; } var codeErrors = _codeIssuesHandler.GetCodeIssues(request).QuickFixes; errors.AddRange(codeErrors); return errors; }
public SemanticErrorsResponse FindSemanticErrors(Request request) { var clientFilename = request.FileName.ApplyPathReplacementsForClient(); var project = _solution.ProjectContainingFile(request.FileName); project.UpdateFile(request.FileName, request.Buffer); var solutionSnapshot = new DefaultSolutionSnapshot(_solution.Projects.Select(i => i.ProjectContent)); SyntaxTree syntaxTree; if(project.CompilerSettings!=null){ syntaxTree = new CSharpParser(project.CompilerSettings).Parse(request.Buffer, request.FileName); }else{ syntaxTree = new CSharpParser().Parse(request.Buffer, request.FileName); } var resolver = new CSharpAstResolver(solutionSnapshot.GetCompilation(project.ProjectContent), syntaxTree); var navigator = new SemanticErrorsNavigator(); resolver.ApplyNavigator(navigator); var errors = navigator.GetErrors() .Where(e => ShouldIncludeIssue(e.Message)) .Select(i => new Error { FileName = clientFilename, Message = i.Message, Line = i.StartLocation.Line, Column = i.EndLocation.Column, EndLine = i.EndLocation.Line, EndColumn = i.EndLocation.Column }); return new SemanticErrorsResponse { Errors = errors, }; }
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; }
public QuickFixResponse GetCodeIssues(Request req) { var actions = GetContextualCodeActions(req); return new QuickFixResponse(actions.Select(a => new QuickFix { Column = a.Start.Column, Line = a.Start.Line, FileName = req.FileName, Text = a.Description })); }
public FixUsingsResponse FixUsings(Request request) { _fileName = request.FileName; string buffer = RemoveUsings(request.Buffer); buffer = SortUsings(buffer); buffer = AddLinqForQueryIfMissing(buffer); bool ambiguousResultsFound = false; bool usingsAdded = true; while (usingsAdded) { var content = _bufferParser.ParsedContent(buffer, _fileName); var tree = content.SyntaxTree; var resolver = new CSharpAstResolver(content.Compilation, content.SyntaxTree, content.UnresolvedFile); var unresolvedNodes = GetAllUnresolvedNodes(tree, resolver).Select(nr => GetNodeToAddUsing(nr)); usingsAdded = false; request.Buffer = buffer; var outerContext = OmniSharpRefactoringContext.GetContext(_bufferParser, request); using (var script = new OmniSharpScript(outerContext, _config)) { foreach (var unresolvedNode in unresolvedNodes) { _logger.Info(unresolvedNode); var requestForNode = CreateRequest(buffer, unresolvedNode); var innerContext = OmniSharpRefactoringContext.GetContext(_bufferParser, requestForNode); var addUsingAction = new AddUsingAction(); var actions = addUsingAction.GetActions(innerContext).Where(a => a.Description.StartsWith("using")).ToArray(); if (actions.Length == 1) { var a = actions[0]; _logger.Info("Adding " + a.Description); a.Run(script); usingsAdded = true; break; } ambiguousResultsFound |= actions.Length > 1; } } buffer = outerContext.Document.Text; } IEnumerable<QuickFix> ambiguous = Enumerable.Empty<QuickFix>(); if (ambiguousResultsFound) { ambiguous = GetAmbiguousNodes(buffer, request.FileName); } return new FixUsingsResponse(buffer, ambiguous); }
private IEnumerable<CodeAction> GetContextualCodeActions(Request req) { var refactoringContext = OmniSharpRefactoringContext.GetContext(_bufferParser, req); var actions = new List<CodeAction>(); var providers = new CodeActionProviders().GetProviders(); foreach (var provider in providers) { var providerActions = provider.GetActions(refactoringContext); actions.AddRange(providerActions); } return actions; }
public SyntaxErrorsResponse FindSyntaxErrors(Request request) { var syntaxTree = new CSharpParser().Parse(request.Buffer, request.FileName); var errors = syntaxTree.Errors.Select(error => new Error { Message = error.Message.Replace("'", "''"), Column = error.Region.BeginColumn, Line = error.Region.BeginLine, FileName = request.FileName }); return new SyntaxErrorsResponse {Errors = errors}; }
GetFileRegions(Request request) { var context = new BufferContext(request, this._parser); var declarationCollector = new GetDirectivesAstVisitor(); context.ParsedContent.SyntaxTree .AcceptVisitor(declarationCollector); var regions = declarationCollector.Directives .Where(d => d.Type == PreProcessorDirectiveType.Region || d.Type == PreProcessorDirectiveType.Endregion) .Select(d => QuickFix.ForFirstLineInRegion (d.GetRegion(), context.Document)); return new QuickFixResponse(regions); }
public OverrideContext (Request request, BufferParser parser) { this.BufferParser = parser; this.CompletionContext = new BufferContext (request, this.BufferParser); this.CurrentType = this.CompletionContext.ParsedContent .UnresolvedFile.GetInnermostTypeDefinition (this.CompletionContext.TextLocation) .Resolve(this.CompletionContext.ResolveContext); this.OverrideTargets = GetOverridableMembers() .Select(m => new GetOverrideTargetsResponse (m, this.CompletionContext.ResolveContext)) .ToArray(); }
private IEnumerable<CodeIssue> GetContextualCodeActions(Request req) { var refactoringContext = OmniSharpRefactoringContext.GetContext(_bufferParser, req); var actions = new List<CodeIssue>(); var providers = new CodeIssueProviders().GetProviders(); foreach (var provider in providers) { try { var codeIssues = provider.GetIssues(refactoringContext); actions.AddRange(codeIssues.Where(ShouldIncludeIssue)); } catch (Exception) { } } return actions; }
void Initialize(Request request, BufferParser parser) { this.Request = request; this.BufferParser = parser; this.Document = new ReadOnlyDocument(request.Buffer ?? ""); this.TextLocation = new TextLocation (line: request.Line, column: request.Column); int cursorPosition = this.Document.GetOffset(this.TextLocation); //Ensure cursorPosition only equals 0 when editorText is empty, so line 1,column 1 //completion will work correctly. cursorPosition = Math.Max(cursorPosition, 1); cursorPosition = Math.Min(cursorPosition, request.Buffer.Length); this.CursorPosition = cursorPosition; this.ParsedContent = this.BufferParser.ParsedContent(request.Buffer, request.FileName); this.ResolveContext = this.ParsedContent.UnresolvedFile.GetTypeResolveContext(this.ParsedContent.Compilation, this.TextLocation); }
public GetContextResponse GetContextResponse(Request request) { string methodName = null; string typeName = null; var bufferContext = new BufferContext(request, _parser); var node = bufferContext.NodeCurrentlyUnderCursor; TypeDeclaration type = null; NamespaceDeclaration namespaceDeclaration = null; if(node != null) { var method = (MethodDeclaration) node.AncestorsAndSelf.FirstOrDefault(n => n is MethodDeclaration); if (method != null) methodName = method.Name; type = (TypeDeclaration)node.AncestorsAndSelf.FirstOrDefault(n => n is TypeDeclaration); namespaceDeclaration = (NamespaceDeclaration)node.AncestorsAndSelf.FirstOrDefault(n => n is NamespaceDeclaration); } if (type == null) { var tree = bufferContext.ParsedContent.SyntaxTree; type = (TypeDeclaration)tree.DescendantsAndSelf.FirstOrDefault(n => n is TypeDeclaration); namespaceDeclaration = (NamespaceDeclaration)tree.DescendantsAndSelf.FirstOrDefault(n => n is NamespaceDeclaration); } typeName = type.Name; if (namespaceDeclaration != null) typeName = namespaceDeclaration.FullName + "." + typeName; var project = _solution.ProjectContainingFile(request.FileName); var directory = new FileInfo(project.FileName).Directory.FullName; var assemblyName = Path.Combine(directory, "bin", "Debug", project.ProjectContent.FullAssemblyName + ".dll"); return new GetContextResponse { MethodName = methodName, TypeName = typeName, AssemblyName = "\"" + assemblyName + "\"" }; }
private IEnumerable<CodeIssue> GetContextualCodeActions(Request req) { var refactoringContext = OmniSharpRefactoringContext.GetContext(_bufferParser, req); var ignoredCodeIssues = ConfigurationLoader.Config.IgnoredCodeIssues; var actions = new List<CodeIssue>(); var providers = new CodeIssueProviders().GetProviders(); foreach (var provider in providers) { try { var codeIssues = provider.GetIssues(refactoringContext); actions.AddRange(codeIssues.Where(issue => !ignoredCodeIssues.Contains(issue.Description))); } catch (Exception) { } } return actions; }
public void Should_not_offer_already_overridden_method() { var buffer = @" public class WeirdString : String { public override string ToString() { return ""weird""; } $ }"; var location = TestHelpers.GetLineAndColumnFromDollar(buffer); var request = new Request { Buffer = buffer, FileName = "myfile.cs", Line = location.Line, Column = location.Column }; var solution = new FakeSolutionBuilder().AddFile(buffer, "myfile.cs").Build(); var parser = new BufferParser(solution); var context = new OverrideContext(request, parser); var overrides = context.OverrideTargets.Select(m => m.OverrideTargetName).ToArray(); overrides.ShouldNotContain("public virtual string ToString ();"); }
public static GetContextResponse GetContextInformation(this string editorText) { int cursorOffset = editorText.IndexOf("$", StringComparison.Ordinal); var cursorPosition = TestHelpers.GetLineAndColumnFromIndex(editorText, cursorOffset); editorText = editorText.Replace("$", ""); var solution = new FakeSolution(); var project = new FakeProject(); project.AddFile(editorText); solution.Projects.Add(project); var handler = new GetContextHandler(solution, new BufferParser(solution)); var request = new Request { Buffer = editorText, FileName = "myfile", Line = cursorPosition.Line, Column = cursorPosition.Column, }; return handler.GetContextResponse(request); }
public SemanticErrorsResponse FindSemanticErrors(Request request) { var clientFilename = request.FileName.ApplyPathReplacementsForClient(); var project = _solution.ProjectContainingFile(request.FileName); project.UpdateFile(request.FileName, request.Buffer); var solutionSnapshot = new DefaultSolutionSnapshot(_solution.Projects.Select(i => i.ProjectContent)); var syntaxTree = new CSharpParser().Parse(request.Buffer, request.FileName); var resolver = new CSharpAstResolver(solutionSnapshot.GetCompilation(project.ProjectContent), syntaxTree); var navigator = new SemanticErrorsNavigator(); resolver.ApplyNavigator(navigator); var errors = navigator.GetErrors().Select(i => new Error { FileName = clientFilename, Message = i.Message, Line = i.TextLocation.Line, Column = i.TextLocation.Column, }); return new SemanticErrorsResponse { Errors = errors, }; }
public RunCodeIssuesResponse FixCodeIssue(Request req) { var issues = GetContextualCodeActions(req).ToList(); var issue = issues.FirstOrDefault(i => i.Start.Line == req.Line); if (issue == null) return new RunCodeIssuesResponse { Text = req.Buffer }; var context = OmniSharpRefactoringContext.GetContext(_bufferParser, req); using (var script = new OmniSharpScript(context, _config)) { var action = issue.Actions.FirstOrDefault(); if (action != null) { action.Run(script); return new RunCodeIssuesResponse {Text = context.Document.Text}; } } return new RunCodeIssuesResponse {Text = req.Buffer}; }
public SyntaxErrorsResponse FindSyntaxErrors(Request request) { var parser = new CSharpParser (); var project = _solution.ProjectContainingFile(request.FileName); if (project.CompilerSettings != null) { parser.CompilerSettings = project.CompilerSettings; } var syntaxTree = parser.Parse(request.Buffer, request.FileName); var filename = request.FileName.ApplyPathReplacementsForClient(); var errors = syntaxTree.Errors.Select(error => new Error { Message = error.Message.Replace("'", "''"), Column = error.Region.BeginColumn, Line = error.Region.BeginLine, EndColumn = error.Region.EndColumn, EndLine = error.Region.EndLine, FileName = filename }); return new SyntaxErrorsResponse {Errors = errors}; }
public static FixUsingsResponse GetFixUsingsResponse(this string buffer) { var solution = new FakeSolutionBuilder().AddFile(buffer).Build(); var bufferParser = new BufferParser(solution); var handler = new FixUsingsHandler(bufferParser, new Logger(Verbosity.Quiet), new OmniSharpConfiguration()); var request = new Request(); request.Buffer = buffer; request.FileName = "myfile"; // line number should be irrelevant request.Line = int.MaxValue; var response = handler.FixUsings(request); return response; }
/// <summary> /// Inserts the given EntityDeclaration with the given /// script at the end of the type declaration under the /// cursor (e.g. class / struct). /// </summary> /// <remarks> /// Alters the given script. Returns its CurrentDocument /// property. Alters the given memberDeclaration, adding /// Modifiers.Override to its Modifiers as well as removing /// Modifiers.Virtual. /// </remarks> IDocument runOverrideTargetWorker ( Request request , OmniSharpRefactoringContext refactoringContext , ParsedResult parsedContent , EntityDeclaration memberDeclaration , OmniSharpScript script) { // Add override flag memberDeclaration.Modifiers |= Modifiers.Override; // Remove virtual flag memberDeclaration.Modifiers &= ~ Modifiers.Virtual; // The current type declaration, e.g. class, struct.. var typeDeclaration = parsedContent.SyntaxTree.GetNodeAt ( refactoringContext.Location , n => n.NodeType == NodeType.TypeDeclaration); // Even empty classes have nodes, so this works var lastNode = typeDeclaration.Children.Last(); script.InsertBefore ( node : lastNode , newNode : memberDeclaration); script.FormatText(memberDeclaration); return script.CurrentDocument; }
/// <summary> /// Returns the available overridable members in the given /// request. /// </summary> public IEnumerable<GetOverrideTargetsResponse> GetOverrideTargets (Request request) { var overrideContext = new OverrideContext(request, _parser); return overrideContext.OverrideTargets; }
private static Error[] GetErrors(string editorText) { var fileName = "test.cs"; var solution = new FakeSolution(); var project = new FakeProject(); project.AddFile(editorText, fileName); solution.Projects.Add(project); var handler = new SemanticErrorsHandler(solution); var request = new Request { Buffer = editorText, FileName = fileName, }; var semanticErrorsResponse = handler.FindSemanticErrors(request); return semanticErrorsResponse.Errors.ToArray(); }
Request CreateRequest(string buffer, AstNode node) { var request = new Request(); request.Buffer = buffer; request.Line = node.Region.BeginLine; request.Column = node.Region.BeginColumn; request.FileName = _fileName; return request; }
public GetCodeActionsResponse GetCodeActions(Request req) { var actions = GetContextualCodeActions(req); return new GetCodeActionsResponse { CodeActions = actions.Select(a => a.Description) }; }
public BufferContext (Request request, BufferParser bufferParser) { this.Initialize(request, bufferParser); }