首页 > 解决方案 > 如何使用 OmniSharp LanguageServer 推送 LSP 诊断?

问题描述

我正在使用 OmniSharp 的C# LSP 服务器为 VS Code 插件实现一个简单的解析/语言服务。我已经设法让基础知识启动并运行,但我无法弄清楚如何将诊断消息推送到 VS Code(就像在这个打字稿示例中一样)。

有没有人有任何有用的示例代码/提示?

谢谢!

标签: c#omnisharplanguage-server-protocol

解决方案


与@david-driscoll 交谈后,我发现我需要在构造函数中存储对ILanguageServerFacade 的引用,并在TextDocument 上使用PublishDiagnostics 扩展方法。IE:

public class TextDocumentSyncHandler : ITextDocumentSyncHandler
{
   private readonly ILanguageServerFacade _facade;

   public TextDocumentSyncHandler(ILanguageServerFacade facade)
   {
      _facade = facade;
   }

   public Task<Unit> Handle(DidChangeTextDocumentParams request, CancellationToken cancellationToken) 
   {
      // Parse your stuff here

      // Diagnostics are sent a document at a time, this example is for demonstration purposes only
      var diagnostics = ImmutableArray<Diagnostic>.Empty.ToBuilder();

      diagnostics.Add(new Diagnostic()
      {
         Code = "ErrorCode_001",
         Severity = DiagnosticSeverity.Error,
         Message = "Something bad happened",
         Range = new Range(0, 0, 0, 0),
         Source = "XXX",
         Tags = new Container<DiagnosticTag>(new DiagnosticTag[] { DiagnosticTag.Unnecessary })
      });

      _facade.TextDocument.PublishDiagnostics(new PublishDiagnosticsParams() 
      {
         Diagnostics = new Container<Diagnostic>(diagnostics.ToArray()),
         Uri = request.TextDocument.Uri,
         Version = request.TextDocument.Version
      });

      return Unit.Task;
   }
}

对于实际代码,您可能需要一个集中的诊断对象数组,但这显示了如何完成它的基础知识。

谢谢大卫!


推荐阅读