src/Tools/VSCode/src/server.scala
author wenzelm
Wed Dec 28 19:45:09 2016 +0100 (2016-12-28)
changeset 64690 599873de8b01
parent 64687 04806ad1e43a
child 64691 db2b21a52f20
permissions -rw-r--r--
more uniform pending_input / pending_output;
explicit Document_Model.uri;
tuned;
wenzelm@64605
     1
/*  Title:      Tools/VSCode/src/server.scala
wenzelm@64605
     2
    Author:     Makarius
wenzelm@64605
     3
wenzelm@64605
     4
Server for VS Code Language Server Protocol 2.0, see also
wenzelm@64605
     5
https://github.com/Microsoft/language-server-protocol
wenzelm@64605
     6
https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md
wenzelm@64605
     7
*/
wenzelm@64605
     8
wenzelm@64605
     9
package isabelle.vscode
wenzelm@64605
    10
wenzelm@64605
    11
wenzelm@64605
    12
import isabelle._
wenzelm@64605
    13
wenzelm@64605
    14
import java.io.{PrintStream, OutputStream}
wenzelm@64605
    15
wenzelm@64605
    16
import scala.annotation.tailrec
wenzelm@64605
    17
wenzelm@64605
    18
wenzelm@64605
    19
object Server
wenzelm@64605
    20
{
wenzelm@64605
    21
  /* Isabelle tool wrapper */
wenzelm@64605
    22
wenzelm@64618
    23
  private val default_text_length = "UTF-16"
wenzelm@64605
    24
  private lazy val default_logic = Isabelle_System.getenv("ISABELLE_LOGIC")
wenzelm@64605
    25
wenzelm@64605
    26
  val isabelle_tool = Isabelle_Tool("vscode_server", "VSCode Language Server for PIDE", args =>
wenzelm@64605
    27
  {
wenzelm@64644
    28
    try {
wenzelm@64644
    29
      var log_file: Option[Path] = None
wenzelm@64682
    30
      var text_length = Text.Length.encoding(default_text_length)
wenzelm@64644
    31
      var dirs: List[Path] = Nil
wenzelm@64644
    32
      var logic = default_logic
wenzelm@64644
    33
      var modes: List[String] = Nil
wenzelm@64644
    34
      var options = Options.init()
wenzelm@64605
    35
wenzelm@64644
    36
      def text_length_choice: String =
wenzelm@64682
    37
        commas(Text.Length.encodings.map(
wenzelm@64644
    38
          { case (a, _) => if (a == default_text_length) a + " (default)" else a }))
wenzelm@64618
    39
wenzelm@64644
    40
      val getopts = Getopts("""
wenzelm@64605
    41
Usage: isabelle vscode_server [OPTIONS]
wenzelm@64605
    42
wenzelm@64605
    43
  Options are:
wenzelm@64605
    44
    -L FILE      enable logging on FILE
wenzelm@64618
    45
    -T LENGTH    text length encoding: """ + text_length_choice + """
wenzelm@64605
    46
    -d DIR       include session directory
wenzelm@64605
    47
    -l NAME      logic session name (default ISABELLE_LOGIC=""" + quote(logic) + """)
wenzelm@64605
    48
    -m MODE      add print mode for output
wenzelm@64605
    49
    -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
wenzelm@64605
    50
wenzelm@64605
    51
  Run the VSCode Language Server protocol (JSON RPC) over stdin/stdout.
wenzelm@64605
    52
""",
wenzelm@64644
    53
        "L:" -> (arg => log_file = Some(Path.explode(arg))),
wenzelm@64682
    54
        "T:" -> (arg => Text.Length.encoding(arg)),
wenzelm@64644
    55
        "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
wenzelm@64644
    56
        "l:" -> (arg => logic = arg),
wenzelm@64644
    57
        "m:" -> (arg => modes = arg :: modes),
wenzelm@64644
    58
        "o:" -> (arg => options = options + arg))
wenzelm@64605
    59
wenzelm@64644
    60
      val more_args = getopts(args)
wenzelm@64644
    61
      if (more_args.nonEmpty) getopts.usage()
wenzelm@64644
    62
wenzelm@64644
    63
      if (!Build.build(options = options, build_heap = true, no_build = true,
wenzelm@64644
    64
            dirs = dirs, sessions = List(logic)).ok)
wenzelm@64644
    65
        error("Missing logic image " + quote(logic))
wenzelm@64605
    66
wenzelm@64644
    67
      val channel = new Channel(System.in, System.out, log_file)
wenzelm@64644
    68
      val server = new Server(channel, options, text_length, logic, dirs, modes)
wenzelm@64605
    69
wenzelm@64644
    70
      // prevent spurious garbage on the main protocol channel
wenzelm@64644
    71
      val orig_out = System.out
wenzelm@64644
    72
      try {
wenzelm@64644
    73
        System.setOut(new PrintStream(new OutputStream { def write(n: Int) {} }))
wenzelm@64644
    74
        server.start()
wenzelm@64644
    75
      }
wenzelm@64644
    76
      finally { System.setOut(orig_out) }
wenzelm@64605
    77
    }
wenzelm@64644
    78
    catch {
wenzelm@64644
    79
      case exn: Throwable =>
wenzelm@64644
    80
        val channel = new Channel(System.in, System.out, None)
wenzelm@64644
    81
        channel.error_message(Exn.message(exn))
wenzelm@64644
    82
        throw(exn)
wenzelm@64644
    83
    }
wenzelm@64605
    84
  })
wenzelm@64605
    85
wenzelm@64605
    86
wenzelm@64605
    87
  /* server state */
wenzelm@64605
    88
wenzelm@64605
    89
  sealed case class State(
wenzelm@64605
    90
    session: Option[Session] = None,
wenzelm@64679
    91
    models: Map[String, Document_Model] = Map.empty,
wenzelm@64690
    92
    pending_input: Set[Document.Node.Name] = Set.empty,
wenzelm@64679
    93
    pending_output: Set[Document.Node.Name] = Set.empty)
wenzelm@64605
    94
}
wenzelm@64605
    95
wenzelm@64605
    96
class Server(
wenzelm@64605
    97
  channel: Channel,
wenzelm@64605
    98
  options: Options,
wenzelm@64682
    99
  text_length: Text.Length = Text.Length.encoding(Server.default_text_length),
wenzelm@64605
   100
  session_name: String = Server.default_logic,
wenzelm@64605
   101
  session_dirs: List[Path] = Nil,
wenzelm@64605
   102
  modes: List[String] = Nil)
wenzelm@64605
   103
{
wenzelm@64605
   104
  /* server state */
wenzelm@64605
   105
wenzelm@64605
   106
  private val state = Synchronized(Server.State())
wenzelm@64605
   107
wenzelm@64605
   108
  def session: Session = state.value.session getOrElse error("Session inactive")
wenzelm@64623
   109
  def resources: VSCode_Resources = session.resources.asInstanceOf[VSCode_Resources]
wenzelm@64605
   110
wenzelm@64651
   111
  def rendering_offset(node_pos: Line.Node_Position): Option[(VSCode_Rendering, Text.Offset)] =
wenzelm@64649
   112
    for {
wenzelm@64651
   113
      model <- state.value.models.get(node_pos.name)
wenzelm@64679
   114
      rendering = model.rendering(options)
wenzelm@64683
   115
      offset <- model.doc.offset(node_pos.pos)
wenzelm@64649
   116
    } yield (rendering, offset)
wenzelm@64649
   117
wenzelm@64605
   118
wenzelm@64679
   119
  /* input from client */
wenzelm@64679
   120
wenzelm@64679
   121
  private val delay_input =
wenzelm@64684
   122
    Standard_Thread.delay_last(options.seconds("vscode_input_delay")) {
wenzelm@64679
   123
      state.change(st =>
wenzelm@64679
   124
        {
wenzelm@64690
   125
          val changed =
wenzelm@64690
   126
            (for {
wenzelm@64690
   127
              node_name <- st.pending_input.iterator
wenzelm@64690
   128
              model <- st.models.get(node_name.node)
wenzelm@64690
   129
              if model.changed } yield model).toList
wenzelm@64690
   130
          session.update(Document.Blobs.empty,
wenzelm@64690
   131
            for { model <- changed; edit <- model.node_edits(resources) } yield edit)
wenzelm@64679
   132
          st.copy(
wenzelm@64690
   133
            models = (st.models /: changed) { case (ms, m) => ms + (m.uri -> m.unchanged) },
wenzelm@64690
   134
            pending_input = Set.empty)
wenzelm@64679
   135
        })
wenzelm@64679
   136
    }
wenzelm@64679
   137
wenzelm@64679
   138
  def update_document(uri: String, text: String)
wenzelm@64679
   139
  {
wenzelm@64679
   140
    state.change(st =>
wenzelm@64679
   141
      {
wenzelm@64679
   142
        val node_name = resources.node_name(uri)
wenzelm@64683
   143
        val model = Document_Model(session, Line.Document(text, text_length), node_name)
wenzelm@64690
   144
        st.copy(
wenzelm@64690
   145
          models = st.models + (uri -> model),
wenzelm@64690
   146
          pending_input = st.pending_input + node_name)
wenzelm@64679
   147
      })
wenzelm@64679
   148
    delay_input.invoke()
wenzelm@64679
   149
  }
wenzelm@64679
   150
wenzelm@64679
   151
wenzelm@64679
   152
  /* output to client */
wenzelm@64679
   153
wenzelm@64679
   154
  private val commands_changed =
wenzelm@64679
   155
    Session.Consumer[Session.Commands_Changed](getClass.getName) {
wenzelm@64679
   156
      case changed =>
wenzelm@64679
   157
        state.change(st => st.copy(pending_output = st.pending_output ++ changed.nodes))
wenzelm@64679
   158
        delay_output.invoke()
wenzelm@64679
   159
    }
wenzelm@64679
   160
wenzelm@64679
   161
  private val delay_output =
wenzelm@64684
   162
    Standard_Thread.delay_last(options.seconds("vscode_output_delay")) {
wenzelm@64679
   163
      state.change(st =>
wenzelm@64679
   164
        {
wenzelm@64679
   165
          val changed_iterator =
wenzelm@64679
   166
            for {
wenzelm@64679
   167
              node_name <- st.pending_output.iterator
wenzelm@64690
   168
              model <- st.models.get(node_name.node)
wenzelm@64679
   169
              rendering = model.rendering(options)
wenzelm@64679
   170
              (diagnostics, model1) <- model.publish_diagnostics(rendering)
wenzelm@64679
   171
            } yield {
wenzelm@64690
   172
              channel.diagnostics(model1.uri, rendering.diagnostics_output(diagnostics))
wenzelm@64690
   173
              model1
wenzelm@64679
   174
            }
wenzelm@64679
   175
          st.copy(
wenzelm@64690
   176
            models = (st.models /: changed_iterator) { case (ms, m) => ms + (m.uri -> m) },
wenzelm@64679
   177
            pending_output = Set.empty)
wenzelm@64679
   178
        })
wenzelm@64679
   179
    }
wenzelm@64679
   180
wenzelm@64679
   181
wenzelm@64605
   182
  /* init and exit */
wenzelm@64605
   183
wenzelm@64641
   184
  def init(id: Protocol.Id)
wenzelm@64605
   185
  {
wenzelm@64641
   186
    def reply(err: String)
wenzelm@64641
   187
    {
wenzelm@64641
   188
      channel.write(Protocol.Initialize.reply(id, err))
wenzelm@64642
   189
      if (err == "")
wenzelm@64642
   190
        channel.writeln("Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")")
wenzelm@64642
   191
      else channel.error_message(err)
wenzelm@64641
   192
    }
wenzelm@64641
   193
wenzelm@64643
   194
    val try_session =
wenzelm@64643
   195
      try {
wenzelm@64643
   196
        val content = Build.session_content(options, false, session_dirs, session_name)
wenzelm@64643
   197
        val resources =
wenzelm@64643
   198
          new VSCode_Resources(content.loaded_theories, content.known_theories, content.syntax)
wenzelm@64605
   199
wenzelm@64643
   200
        Some(new Session(resources) {
wenzelm@64643
   201
          override def output_delay = options.seconds("editor_output_delay")
wenzelm@64643
   202
          override def prune_delay = options.seconds("editor_prune_delay")
wenzelm@64643
   203
          override def syslog_limit = options.int("editor_syslog_limit")
wenzelm@64643
   204
          override def reparse_limit = options.int("editor_reparse_limit")
wenzelm@64643
   205
        })
wenzelm@64605
   206
      }
wenzelm@64643
   207
      catch { case ERROR(msg) => reply(msg); None }
wenzelm@64605
   208
wenzelm@64643
   209
    for (session <- try_session) {
wenzelm@64643
   210
      var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64643
   211
      session_phase =
wenzelm@64643
   212
        Session.Consumer(getClass.getName) {
wenzelm@64643
   213
          case Session.Ready =>
wenzelm@64643
   214
            session.phase_changed -= session_phase
wenzelm@64643
   215
            session.update_options(options)
wenzelm@64643
   216
            reply("")
wenzelm@64643
   217
          case Session.Failed =>
wenzelm@64643
   218
            session.phase_changed -= session_phase
wenzelm@64643
   219
            reply("Prover startup failed")
wenzelm@64643
   220
          case _ =>
wenzelm@64643
   221
        }
wenzelm@64643
   222
      session.phase_changed += session_phase
wenzelm@64605
   223
wenzelm@64679
   224
      session.commands_changed += commands_changed
wenzelm@64679
   225
wenzelm@64643
   226
      session.start(receiver =>
wenzelm@64643
   227
        Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
wenzelm@64643
   228
          modes = modes, receiver = receiver))
wenzelm@64605
   229
wenzelm@64643
   230
      state.change(_.copy(session = Some(session)))
wenzelm@64643
   231
    }
wenzelm@64605
   232
  }
wenzelm@64605
   233
wenzelm@64641
   234
  def shutdown(id: Protocol.Id)
wenzelm@64605
   235
  {
wenzelm@64641
   236
    def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
wenzelm@64641
   237
wenzelm@64605
   238
    state.change(st =>
wenzelm@64605
   239
      st.session match {
wenzelm@64605
   240
        case None => reply("Prover inactive"); st
wenzelm@64605
   241
        case Some(session) =>
wenzelm@64605
   242
          var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64605
   243
          session_phase =
wenzelm@64605
   244
            Session.Consumer(getClass.getName) {
wenzelm@64605
   245
              case Session.Inactive =>
wenzelm@64605
   246
                session.phase_changed -= session_phase
wenzelm@64605
   247
                reply("")
wenzelm@64605
   248
              case _ =>
wenzelm@64605
   249
            }
wenzelm@64605
   250
          session.phase_changed += session_phase
wenzelm@64679
   251
          session.commands_changed -= commands_changed
wenzelm@64605
   252
          session.stop()
wenzelm@64679
   253
          delay_input.revoke()
wenzelm@64679
   254
          delay_output.revoke()
wenzelm@64605
   255
          st.copy(session = None)
wenzelm@64605
   256
      })
wenzelm@64605
   257
  }
wenzelm@64605
   258
wenzelm@64646
   259
  def exit() {
wenzelm@64646
   260
    channel.log("\n")
wenzelm@64646
   261
    sys.exit(if (state.value.session.isDefined) 1 else 0)
wenzelm@64646
   262
  }
wenzelm@64605
   263
wenzelm@64605
   264
wenzelm@64622
   265
  /* hover */
wenzelm@64605
   266
wenzelm@64651
   267
  def hover(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64641
   268
  {
wenzelm@64641
   269
    val result =
wenzelm@64641
   270
      for {
wenzelm@64651
   271
        (rendering, offset) <- rendering_offset(node_pos)
wenzelm@64641
   272
        info <- rendering.tooltip(Text.Range(offset, offset + 1))
wenzelm@64641
   273
      } yield {
wenzelm@64649
   274
        val doc = rendering.model.doc
wenzelm@64683
   275
        val range = doc.range(info.range)
wenzelm@64641
   276
        val s = Pretty.string_of(info.info, margin = rendering.tooltip_margin)
wenzelm@64679
   277
        (range, List("```\n" + s + "\n```"))  // FIXME proper content format
wenzelm@64641
   278
      }
wenzelm@64641
   279
    channel.write(Protocol.Hover.reply(id, result))
wenzelm@64641
   280
  }
wenzelm@64605
   281
wenzelm@64605
   282
wenzelm@64648
   283
  /* goto definition */
wenzelm@64648
   284
wenzelm@64651
   285
  def goto_definition(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64648
   286
  {
wenzelm@64648
   287
    val result =
wenzelm@64651
   288
      (for ((rendering, offset) <- rendering_offset(node_pos))
wenzelm@64649
   289
        yield rendering.hyperlinks(Text.Range(offset, offset + 1))) getOrElse Nil
wenzelm@64648
   290
    channel.write(Protocol.GotoDefinition.reply(id, result))
wenzelm@64648
   291
  }
wenzelm@64648
   292
wenzelm@64648
   293
wenzelm@64605
   294
  /* main loop */
wenzelm@64605
   295
wenzelm@64605
   296
  def start()
wenzelm@64605
   297
  {
wenzelm@64646
   298
    channel.log("Server started " + Date.now())
wenzelm@64605
   299
wenzelm@64605
   300
    def handle(json: JSON.T)
wenzelm@64605
   301
    {
wenzelm@64605
   302
      try {
wenzelm@64605
   303
        json match {
wenzelm@64641
   304
          case Protocol.Initialize(id) => init(id)
wenzelm@64641
   305
          case Protocol.Shutdown(id) => shutdown(id)
wenzelm@64645
   306
          case Protocol.Exit(()) => exit()
wenzelm@64605
   307
          case Protocol.DidOpenTextDocument(uri, lang, version, text) =>
wenzelm@64605
   308
            update_document(uri, text)
wenzelm@64605
   309
          case Protocol.DidChangeTextDocument(uri, version, List(Protocol.TextDocumentContent(text))) =>
wenzelm@64605
   310
            update_document(uri, text)
wenzelm@64605
   311
          case Protocol.DidCloseTextDocument(uri) => channel.log("CLOSE " + uri)
wenzelm@64605
   312
          case Protocol.DidSaveTextDocument(uri) => channel.log("SAVE " + uri)
wenzelm@64651
   313
          case Protocol.Hover(id, node_pos) => hover(id, node_pos)
wenzelm@64651
   314
          case Protocol.GotoDefinition(id, node_pos) => goto_definition(id, node_pos)
wenzelm@64605
   315
          case _ => channel.log("### IGNORED")
wenzelm@64605
   316
        }
wenzelm@64605
   317
      }
wenzelm@64687
   318
      catch { case exn: Throwable => channel.log_error_message(Exn.message(exn)) }
wenzelm@64605
   319
    }
wenzelm@64605
   320
wenzelm@64605
   321
    @tailrec def loop()
wenzelm@64605
   322
    {
wenzelm@64605
   323
      channel.read() match {
wenzelm@64605
   324
        case Some(json) =>
wenzelm@64605
   325
          json match {
wenzelm@64605
   326
            case bulk: List[_] => bulk.foreach(handle(_))
wenzelm@64605
   327
            case _ => handle(json)
wenzelm@64605
   328
          }
wenzelm@64605
   329
          loop()
wenzelm@64605
   330
        case None => channel.log("### TERMINATE")
wenzelm@64605
   331
      }
wenzelm@64605
   332
    }
wenzelm@64605
   333
    loop()
wenzelm@64605
   334
  }
wenzelm@64605
   335
}