private DefaultRazorProximityExpressionResolver(
            FileUriProvider fileUriProvider,
            LSPDocumentManager documentManager,
            LSPProjectionProvider projectionProvider,
            CodeAnalysis.Workspace workspace)
        {
            if (fileUriProvider is null)
            {
                throw new ArgumentNullException(nameof(fileUriProvider));
            }

            if (documentManager is null)
            {
                throw new ArgumentNullException(nameof(documentManager));
            }

            if (projectionProvider is null)
            {
                throw new ArgumentNullException(nameof(projectionProvider));
            }

            _fileUriProvider    = fileUriProvider;
            _documentManager    = documentManager;
            _projectionProvider = projectionProvider;
            _workspace          = workspace;

            // 10 is a magic number where this effectively represents our ability to cache the last 10 "hit" breakpoint locations
            // corresponding proximity expressions which enables us not to go "async" in those re-hit scenarios.
            _cache = new MemoryCache <CacheKey, IReadOnlyList <string> >(sizeLimit: 10);
        }
Ejemplo n.º 2
0
        public InProcLanguageServer(Stream inputStream,
                                    Stream outputStream,
                                    LanguageServerProtocol protocol,
                                    CodeAnalysis.Workspace workspace,
                                    IDiagnosticService diagnosticService,
                                    string?clientName)
        {
            _protocol  = protocol;
            _workspace = workspace;

            var jsonMessageFormatter = new JsonMessageFormatter();

            jsonMessageFormatter.JsonSerializer.Converters.Add(new VSExtensionConverter <TextDocumentIdentifier, VSTextDocumentIdentifier>());
            jsonMessageFormatter.JsonSerializer.Converters.Add(new VSExtensionConverter <ClientCapabilities, VSClientCapabilities>());

            _jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream, jsonMessageFormatter));
            _jsonRpc.AddLocalRpcTarget(this);
            _jsonRpc.StartListening();

            _diagnosticService = diagnosticService;
            _clientName        = clientName;
            _diagnosticService.DiagnosticsUpdated += DiagnosticService_DiagnosticsUpdated;

            _clientCapabilities = new VSClientCapabilities();
        }
        private RazorProximityExpressionResolver CreateResolverWith(
            FileUriProvider uriProvider              = null,
            LSPDocumentManager documentManager       = null,
            LSPProjectionProvider projectionProvider = null)
        {
            var documentUri = DocumentUri;

            uriProvider ??= Mock.Of <FileUriProvider>(provider => provider.TryGet(HostTextbuffer, out documentUri) == true && provider.TryGet(It.IsNotIn(HostTextbuffer), out It.Ref <Uri> .IsAny) == false, MockBehavior.Strict);
            var csharpDocumentUri                = new Uri(DocumentUri.OriginalString + ".g.cs", UriKind.Absolute);
            var csharpVirtualDocumentSnapshot    = new CSharpVirtualDocumentSnapshot(csharpDocumentUri, CSharpTextBuffer.CurrentSnapshot, hostDocumentSyncVersion: 0);
            LSPDocumentSnapshot documentSnapshot = new TestLSPDocumentSnapshot(DocumentUri, 0, csharpVirtualDocumentSnapshot);

            documentManager ??= Mock.Of <LSPDocumentManager>(manager => manager.TryGetDocument(DocumentUri, out documentSnapshot) == true, MockBehavior.Strict);
            if (projectionProvider is null)
            {
                projectionProvider = new Mock <LSPProjectionProvider>(MockBehavior.Strict).Object;
                Mock.Get(projectionProvider).Setup(projectionProvider => projectionProvider.GetProjectionAsync(It.IsAny <LSPDocumentSnapshot>(), It.IsAny <Position>(), CancellationToken.None))
                .Returns(Task.FromResult <ProjectionResult>(null));
            }
            CodeAnalysis.Workspace workspace     = null;
            var workspaceAccessor                = Mock.Of <VisualStudioWorkspaceAccessor>(accessor => accessor.TryGetWorkspace(It.IsAny <ITextBuffer>(), out workspace) == false, MockBehavior.Strict);
            var razorProximityExpressionResolver = new DefaultRazorProximityExpressionResolver(
                uriProvider,
                documentManager,
                projectionProvider,
                workspaceAccessor);

            return(razorProximityExpressionResolver);
        }
Ejemplo n.º 4
0
        public InProcLanguageServer(Stream inputStream,
                                    Stream outputStream,
                                    AbstractRequestHandlerProvider requestHandlerProvider,
                                    CodeAnalysis.Workspace workspace,
                                    IDiagnosticService diagnosticService,
                                    IAsynchronousOperationListenerProvider listenerProvider,
                                    string?clientName)
        {
            _requestHandlerProvider = requestHandlerProvider;
            _workspace = workspace;

            var jsonMessageFormatter = new JsonMessageFormatter();

            jsonMessageFormatter.JsonSerializer.Converters.Add(new VSExtensionConverter <TextDocumentIdentifier, VSTextDocumentIdentifier>());
            jsonMessageFormatter.JsonSerializer.Converters.Add(new VSExtensionConverter <ClientCapabilities, VSClientCapabilities>());

            _jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream, jsonMessageFormatter));
            _jsonRpc.AddLocalRpcTarget(this);
            _jsonRpc.StartListening();

            _diagnosticService = diagnosticService;
            _listener          = listenerProvider.GetListener(FeatureAttribute.LanguageServer);
            _clientName        = clientName;
            _diagnosticService.DiagnosticsUpdated += DiagnosticService_DiagnosticsUpdated;

            _clientCapabilities = new VSClientCapabilities();
        }
        public VSHostServicesProvider([Import(typeof(VisualStudioWorkspace))] CodeAnalysis.Workspace workspace)
        {
            if (workspace is null)
            {
                throw new ArgumentNullException(nameof(workspace));
            }

            _workspace = workspace;
        }
Ejemplo n.º 6
0
        public override Task <TextAndVersion> LoadTextAndVersionAsync(CodeAnalysis.Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
        {
            if (!File.Exists(Path))
            {
                return(Task.FromResult(TextAndVersion.Create(SourceText.From(""), VersionStamp.Create())));
            }

            return(base.LoadTextAndVersionAsync(workspace, documentId, cancellationToken));
        }
Ejemplo n.º 7
0
 private CodeModelService GetCodeModelService(string path, string applicationName)
 {
     _appInfo           = new ApplicationInfo(applicationName, Path.GetDirectoryName(path), "Debug");
     _logger            = new ConsoleLogger();
     _projectContext    = GetProjectInformation(path);
     _workspace         = new RoslynWorkspace(_projectContext);
     _loader            = new TestAssemblyLoadContext(_projectContext);
     _modelTypesLocator = new ModelTypesLocator(_workspace);
     return(new CodeModelService(_projectContext, _workspace, _logger, _loader));
 }
Ejemplo n.º 8
0
        protected AbstractGraphProvider(
            IGlyphService glyphService,
            SVsServiceProvider serviceProvider,
            CodeAnalysis.Workspace workspace,
            IAsynchronousOperationListenerProvider listenerProvider)
        {
            _glyphService    = glyphService;
            _serviceProvider = serviceProvider;
            var asyncListener = listenerProvider.GetListener(FeatureAttribute.GraphProvider);

            _graphQueryManager = new GraphQueryManager(workspace, asyncListener);
        }
Ejemplo n.º 9
0
        protected AbstractGraphProvider(
            IGlyphService glyphService,
            SVsServiceProvider serviceProvider,
            CodeAnalysis.Workspace workspace,
            IEnumerable <Lazy <IAsynchronousOperationListener, FeatureMetadata> > asyncListeners)
        {
            _glyphService    = glyphService;
            _serviceProvider = serviceProvider;
            var asyncListener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.GraphProvider);

            _graphQueryManager = new GraphQueryManager(workspace, asyncListener);
        }
Ejemplo n.º 10
0
        public override void Apply(CodeAnalysis.Workspace workspace, CancellationToken cancellationToken)
        {
            Task.Run(async() =>
            {
                var executeCommandParams = new ExecuteCommandParams
                {
                    Command   = _command.CommandIdentifier,
                    Arguments = _command.Arguments
                };

                await _lspClient.RequestAsync(Methods.WorkspaceExecuteCommand.ToLSRequest(), executeCommandParams, cancellationToken).ConfigureAwait(false);
            });
        }
Ejemplo n.º 11
0
        private EntityFrameworkServices GetEfServices(string path, string applicationName, bool useSqlite)
        {
            _appInfo          = new ApplicationInfo(applicationName, Path.GetDirectoryName(path), "Debug");
            _logger           = new ConsoleLogger();
            _packageInstaller = new Mock <IPackageInstaller>();
            _serviceProvider  = new Mock <IServiceProvider>();

            _projectContext    = GetProjectInformation(path);
            _workspace         = new RoslynWorkspace(_projectContext);
            _loader            = new TestAssemblyLoadContext(_projectContext);
            _modelTypesLocator = new ModelTypesLocator(_workspace);
            var dbContextMock        = new Mock <IDbContextEditorServices>();
            var editSyntaxTreeResult = new EditSyntaxTreeResult()
            {
                Edited = true
            };

            dbContextMock.Setup(db => db.EditStartupForNewContext(It.IsAny <ModelType>(),
                                                                  It.IsAny <string>(),
                                                                  It.IsAny <string>(),
                                                                  It.IsAny <string>(),
                                                                  useSqlite))
            .Returns(editSyntaxTreeResult);

            var connectionStringsWriter = new Mock <IConnectionStringsWriter>();

            connectionStringsWriter.Setup(c => c.AddConnectionString(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>()));

            var filesLocator       = new FilesLocator();
            var compilationService = new RoslynCompilationService(_appInfo, _loader, _projectContext);
            var templatingService  = new Templating.RazorTemplating(compilationService);

            _dbContextEditorServices = new DbContextEditorServices(_projectContext, _appInfo, filesLocator, templatingService, connectionStringsWriter.Object);

            return(new EntityFrameworkServices(
                       _projectContext,
                       _appInfo,
                       _loader,
                       _modelTypesLocator,
                       _dbContextEditorServices,
                       _packageInstaller.Object,
                       _serviceProvider.Object,
                       _workspace,
                       DefaultFileSystem.Instance,
                       _logger));
        }
Ejemplo n.º 12
0
        private DefaultRazorBreakpointResolver(
            FileUriProvider fileUriProvider,
            LSPDocumentManager documentManager,
            LSPProjectionProvider projectionProvider,
            LSPDocumentMappingProvider documentMappingProvider,
            CodeAnalysis.Workspace workspace)
        {
            if (fileUriProvider is null)
            {
                throw new ArgumentNullException(nameof(fileUriProvider));
            }

            if (documentManager is null)
            {
                throw new ArgumentNullException(nameof(documentManager));
            }

            if (projectionProvider is null)
            {
                throw new ArgumentNullException(nameof(projectionProvider));
            }

            if (documentMappingProvider is null)
            {
                throw new ArgumentNullException(nameof(documentMappingProvider));
            }

            _fileUriProvider         = fileUriProvider;
            _documentManager         = documentManager;
            _projectionProvider      = projectionProvider;
            _documentMappingProvider = documentMappingProvider;
            _workspace = workspace;

            // 4 is a magic number that was determined based on the functionality of VisualStudio. Currently when you set or edit a breakpoint
            // we get called with two different locations for the same breakpoint. Because of this 2 time call our size must be at least 2,
            // we grow it to 4 just to be safe for lesser known scenarios.
            _cache = new MemoryCache <CacheKey, Range>(sizeLimit: 4);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Creates a new <see cref="HostWorkspaceServices"/> associated with the specified workspace.
 /// </summary>
 protected internal override HostWorkspaceServices CreateWorkspaceServices(CodeAnalysis.Workspace workspace)
 {
     return(new MefWorkspaceServices(this, workspace));
 }
Ejemplo n.º 14
0
 public bool TryOnBeforeGlobalSymbolRenamed(CodeAnalysis.Workspace workspace, IEnumerable <DocumentId> changedDocumentIDs, string replacementText) => false;
Ejemplo n.º 15
0
 public IIncrementalAnalyzer CreateIncrementalAnalyzer(CodeAnalysis.Workspace workspace)
 {
     return(new DesignerAttributeIncrementalAnalyzer(
                _threadingContext, _serviceProvider, _notificationService, _listenerProvider));
 }
Ejemplo n.º 16
0
 private RemoteDiagnosticListTable(CodeAnalysis.Workspace workspace, IDiagnosticService diagnosticService, ITableManagerProvider provider)
     : base(workspace, provider)
 {
     _source = new LiveTableDataSource(workspace, diagnosticService, IdentifierString);
     AddInitialTableSource(workspace.CurrentSolution, _source);
 }
 public void AddSemanticClassifications(SemanticModel semanticModel, TextSpan textSpan, CodeAnalysis.Workspace workspace, Func <SyntaxNode, ImmutableArray <ISyntaxClassifier> > getNodeClassifiers, Func <SyntaxToken, ImmutableArray <ISyntaxClassifier> > getTokenClassifiers, ArrayBuilder <ClassifiedSpan> result, CancellationToken cancellationToken)
 {
     _threadingContext.JoinableTaskFactory.Run(async() =>
     {
         var sourceText = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
         await AddRemoteClassificationsAsync(RoslynMethods.ClassificationsName, semanticModel.SyntaxTree.FilePath, sourceText, textSpan, result.Add, cancellationToken).ConfigureAwait(false);
     });
 }
 public override bool TryGetWorkspace(ITextBuffer textBuffer, out CodeAnalysis.Workspace workspace)
 {
     workspace = TestWorkspace.Create();
     return(true);
 }
 public IIncrementalAnalyzer CreateIncrementalAnalyzer(CodeAnalysis.Workspace workspace)
 {
     return(new DesignerAttributeIncrementalAnalyzer(_serviceProvider, _notificationService, _asyncListeners));
 }
Ejemplo n.º 20
0
        // Internal for testing purposes
        internal static int GetPairExtentsWorker(ITextView textView, CodeAnalysis.Workspace workspace, IBraceMatchingService braceMatcher, int iLine, int iIndex, TextSpan[] pSpan, bool extendSelection, CancellationToken cancellationToken)
        {
            pSpan[0].iStartLine  = pSpan[0].iEndLine = iLine;
            pSpan[0].iStartIndex = pSpan[0].iEndIndex = iIndex;

            var pointInViewBuffer = textView.TextSnapshot.GetLineFromLineNumber(iLine).Start + iIndex;

            var subjectBuffer = textView.GetBufferContainingCaret();

            if (subjectBuffer != null)
            {
                // PointTrackingMode and PositionAffinity chosen arbitrarily.
                var positionInSubjectBuffer = textView.BufferGraph.MapDownToBuffer(pointInViewBuffer, PointTrackingMode.Positive, subjectBuffer, PositionAffinity.Successor);
                if (!positionInSubjectBuffer.HasValue)
                {
                    positionInSubjectBuffer = textView.BufferGraph.MapDownToBuffer(pointInViewBuffer, PointTrackingMode.Positive, subjectBuffer, PositionAffinity.Predecessor);
                }

                if (positionInSubjectBuffer.HasValue)
                {
                    var position = positionInSubjectBuffer.Value;

                    var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
                    if (document != null)
                    {
                        var matchingSpan = braceMatcher.FindMatchingSpanAsync(document, position, cancellationToken).WaitAndGetResult(cancellationToken);

                        if (matchingSpan.HasValue)
                        {
                            var resultsInView = textView.GetSpanInView(matchingSpan.Value.ToSnapshotSpan(subjectBuffer.CurrentSnapshot)).ToList();
                            if (resultsInView.Count == 1)
                            {
                                var vsTextSpan = resultsInView[0].ToVsTextSpan();

                                // caret is at close parenthesis
                                if (matchingSpan.Value.Start < position)
                                {
                                    pSpan[0].iStartLine  = vsTextSpan.iStartLine;
                                    pSpan[0].iStartIndex = vsTextSpan.iStartIndex;

                                    // For text selection using goto matching brace, tweak spans to suit the VS editor's behavior.
                                    // The vs editor sets selection for GotoBraceExt (Ctrl + Shift + ]) like so :
                                    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                                    // if (fExtendSelection)
                                    // {
                                    //      textSpan.iEndIndex++;
                                    //      this.SetSelection(textSpan.iStartLine, textSpan.iStartIndex, textSpan.iEndLine, textSpan.iEndIndex);
                                    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                                    // Notice a couple of things: it arbitrarily increments EndIndex by 1 and does nothing similar for StartIndex.
                                    // So, if we're extending selection:
                                    //    case a: set EndIndex to left of closing parenthesis -- ^}
                                    //            this adjustment is for any of the four cases where caret could be. left or right of open or close parenthesis -- ^{^ ^}^
                                    //    case b: set StartIndex to left of opening parenthesis -- ^{
                                    //            this adjustment is for cases where caret was originally to the right of the open parenthesis -- {^ }

                                    // if selecting, adjust end position by using the matching opening span that we just computed.
                                    if (extendSelection)
                                    {
                                        // case a.
                                        var closingSpans   = braceMatcher.FindMatchingSpanAsync(document, matchingSpan.Value.Start, cancellationToken).WaitAndGetResult(cancellationToken);
                                        var vsClosingSpans = textView.GetSpanInView(closingSpans.Value.ToSnapshotSpan(subjectBuffer.CurrentSnapshot)).ToList().First().ToVsTextSpan();
                                        pSpan[0].iEndIndex = vsClosingSpans.iStartIndex;
                                    }
                                }
                                else if (matchingSpan.Value.End > position) // caret is at open parenthesis
                                {
                                    pSpan[0].iEndLine  = vsTextSpan.iEndLine;
                                    pSpan[0].iEndIndex = vsTextSpan.iEndIndex;

                                    // if selecting, adjust start position by using the matching closing span that we computed
                                    if (extendSelection)
                                    {
                                        // case a.
                                        pSpan[0].iEndIndex = vsTextSpan.iStartIndex;

                                        // case b.
                                        var openingSpans   = braceMatcher.FindMatchingSpanAsync(document, matchingSpan.Value.End, cancellationToken).WaitAndGetResult(cancellationToken);
                                        var vsOpeningSpans = textView.GetSpanInView(openingSpans.Value.ToSnapshotSpan(subjectBuffer.CurrentSnapshot)).ToList().First().ToVsTextSpan();
                                        pSpan[0].iStartIndex = vsOpeningSpans.iStartIndex;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(VSConstants.S_OK);
        }