src/Tools/VSCode/src/server.scala
author wenzelm
Wed Dec 28 17:26:38 2016 +0100 (2016-12-28)
changeset 64683 c0c09b6dfbe0
parent 64682 7e119f32276a
child 64684 fe2c9c215b36
permissions -rw-r--r--
clarified signature: maintan Text.Length within Line.Document;
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@64679
    92
    pending_output: Set[Document.Node.Name] = Set.empty)
wenzelm@64605
    93
}
wenzelm@64605
    94
wenzelm@64605
    95
class Server(
wenzelm@64605
    96
  channel: Channel,
wenzelm@64605
    97
  options: Options,
wenzelm@64682
    98
  text_length: Text.Length = Text.Length.encoding(Server.default_text_length),
wenzelm@64605
    99
  session_name: String = Server.default_logic,
wenzelm@64605
   100
  session_dirs: List[Path] = Nil,
wenzelm@64605
   101
  modes: List[String] = Nil)
wenzelm@64605
   102
{
wenzelm@64605
   103
  /* server state */
wenzelm@64605
   104
wenzelm@64605
   105
  private val state = Synchronized(Server.State())
wenzelm@64605
   106
wenzelm@64605
   107
  def session: Session = state.value.session getOrElse error("Session inactive")
wenzelm@64623
   108
  def resources: VSCode_Resources = session.resources.asInstanceOf[VSCode_Resources]
wenzelm@64605
   109
wenzelm@64651
   110
  def rendering_offset(node_pos: Line.Node_Position): Option[(VSCode_Rendering, Text.Offset)] =
wenzelm@64649
   111
    for {
wenzelm@64651
   112
      model <- state.value.models.get(node_pos.name)
wenzelm@64679
   113
      rendering = model.rendering(options)
wenzelm@64683
   114
      offset <- model.doc.offset(node_pos.pos)
wenzelm@64649
   115
    } yield (rendering, offset)
wenzelm@64649
   116
wenzelm@64605
   117
wenzelm@64679
   118
  /* input from client */
wenzelm@64679
   119
wenzelm@64679
   120
  private val delay_input =
wenzelm@64679
   121
    Standard_Thread.delay_last(options.seconds("editor_input_delay")) {
wenzelm@64679
   122
      state.change(st =>
wenzelm@64679
   123
        {
wenzelm@64679
   124
          val changed = (for { entry <- st.models.iterator if entry._2.changed } yield entry).toList
wenzelm@64679
   125
          val edits = for { (_, model) <- changed; edit <- model.node_edits(resources) } yield edit
wenzelm@64679
   126
          session.update(Document.Blobs.empty, edits)
wenzelm@64679
   127
          st.copy(
wenzelm@64679
   128
            models = (st.models /: changed)({ case (ms, (uri, m)) => ms + (uri -> m.unchanged) }))
wenzelm@64679
   129
        })
wenzelm@64679
   130
    }
wenzelm@64679
   131
wenzelm@64679
   132
  def update_document(uri: String, text: String)
wenzelm@64679
   133
  {
wenzelm@64679
   134
    state.change(st =>
wenzelm@64679
   135
      {
wenzelm@64679
   136
        val node_name = resources.node_name(uri)
wenzelm@64683
   137
        val model = Document_Model(session, Line.Document(text, text_length), node_name)
wenzelm@64679
   138
        st.copy(models = st.models + (uri -> model))
wenzelm@64679
   139
      })
wenzelm@64679
   140
    delay_input.invoke()
wenzelm@64679
   141
  }
wenzelm@64679
   142
wenzelm@64679
   143
wenzelm@64679
   144
  /* output to client */
wenzelm@64679
   145
wenzelm@64679
   146
  private val commands_changed =
wenzelm@64679
   147
    Session.Consumer[Session.Commands_Changed](getClass.getName) {
wenzelm@64679
   148
      case changed =>
wenzelm@64679
   149
        state.change(st => st.copy(pending_output = st.pending_output ++ changed.nodes))
wenzelm@64679
   150
        delay_output.invoke()
wenzelm@64679
   151
    }
wenzelm@64679
   152
wenzelm@64679
   153
  private val delay_output =
wenzelm@64679
   154
    Standard_Thread.delay_last(options.seconds("editor_update_delay")) {
wenzelm@64679
   155
      state.change(st =>
wenzelm@64679
   156
        {
wenzelm@64679
   157
          val changed_iterator =
wenzelm@64679
   158
            for {
wenzelm@64679
   159
              node_name <- st.pending_output.iterator
wenzelm@64679
   160
              uri = node_name.node
wenzelm@64679
   161
              model <- st.models.get(uri)
wenzelm@64679
   162
              rendering = model.rendering(options)
wenzelm@64679
   163
              (diagnostics, model1) <- model.publish_diagnostics(rendering)
wenzelm@64679
   164
            } yield {
wenzelm@64679
   165
              channel.diagnostics(uri, rendering.diagnostics_output(diagnostics))
wenzelm@64679
   166
              (uri, model1)
wenzelm@64679
   167
            }
wenzelm@64679
   168
          st.copy(
wenzelm@64679
   169
            models = (st.models /: changed_iterator) { case (ms, (uri, m)) => ms + (uri -> m) },
wenzelm@64679
   170
            pending_output = Set.empty)
wenzelm@64679
   171
        })
wenzelm@64679
   172
    }
wenzelm@64679
   173
wenzelm@64679
   174
wenzelm@64605
   175
  /* init and exit */
wenzelm@64605
   176
wenzelm@64641
   177
  def init(id: Protocol.Id)
wenzelm@64605
   178
  {
wenzelm@64641
   179
    def reply(err: String)
wenzelm@64641
   180
    {
wenzelm@64641
   181
      channel.write(Protocol.Initialize.reply(id, err))
wenzelm@64642
   182
      if (err == "")
wenzelm@64642
   183
        channel.writeln("Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")")
wenzelm@64642
   184
      else channel.error_message(err)
wenzelm@64641
   185
    }
wenzelm@64641
   186
wenzelm@64643
   187
    val try_session =
wenzelm@64643
   188
      try {
wenzelm@64643
   189
        val content = Build.session_content(options, false, session_dirs, session_name)
wenzelm@64643
   190
        val resources =
wenzelm@64643
   191
          new VSCode_Resources(content.loaded_theories, content.known_theories, content.syntax)
wenzelm@64605
   192
wenzelm@64643
   193
        Some(new Session(resources) {
wenzelm@64643
   194
          override def output_delay = options.seconds("editor_output_delay")
wenzelm@64643
   195
          override def prune_delay = options.seconds("editor_prune_delay")
wenzelm@64643
   196
          override def syslog_limit = options.int("editor_syslog_limit")
wenzelm@64643
   197
          override def reparse_limit = options.int("editor_reparse_limit")
wenzelm@64643
   198
        })
wenzelm@64605
   199
      }
wenzelm@64643
   200
      catch { case ERROR(msg) => reply(msg); None }
wenzelm@64605
   201
wenzelm@64643
   202
    for (session <- try_session) {
wenzelm@64643
   203
      var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64643
   204
      session_phase =
wenzelm@64643
   205
        Session.Consumer(getClass.getName) {
wenzelm@64643
   206
          case Session.Ready =>
wenzelm@64643
   207
            session.phase_changed -= session_phase
wenzelm@64643
   208
            session.update_options(options)
wenzelm@64643
   209
            reply("")
wenzelm@64643
   210
          case Session.Failed =>
wenzelm@64643
   211
            session.phase_changed -= session_phase
wenzelm@64643
   212
            reply("Prover startup failed")
wenzelm@64643
   213
          case _ =>
wenzelm@64643
   214
        }
wenzelm@64643
   215
      session.phase_changed += session_phase
wenzelm@64605
   216
wenzelm@64679
   217
      session.commands_changed += commands_changed
wenzelm@64679
   218
wenzelm@64643
   219
      session.start(receiver =>
wenzelm@64643
   220
        Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
wenzelm@64643
   221
          modes = modes, receiver = receiver))
wenzelm@64605
   222
wenzelm@64643
   223
      state.change(_.copy(session = Some(session)))
wenzelm@64643
   224
    }
wenzelm@64605
   225
  }
wenzelm@64605
   226
wenzelm@64641
   227
  def shutdown(id: Protocol.Id)
wenzelm@64605
   228
  {
wenzelm@64641
   229
    def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
wenzelm@64641
   230
wenzelm@64605
   231
    state.change(st =>
wenzelm@64605
   232
      st.session match {
wenzelm@64605
   233
        case None => reply("Prover inactive"); st
wenzelm@64605
   234
        case Some(session) =>
wenzelm@64605
   235
          var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64605
   236
          session_phase =
wenzelm@64605
   237
            Session.Consumer(getClass.getName) {
wenzelm@64605
   238
              case Session.Inactive =>
wenzelm@64605
   239
                session.phase_changed -= session_phase
wenzelm@64605
   240
                reply("")
wenzelm@64605
   241
              case _ =>
wenzelm@64605
   242
            }
wenzelm@64605
   243
          session.phase_changed += session_phase
wenzelm@64679
   244
          session.commands_changed -= commands_changed
wenzelm@64605
   245
          session.stop()
wenzelm@64679
   246
          delay_input.revoke()
wenzelm@64679
   247
          delay_output.revoke()
wenzelm@64605
   248
          st.copy(session = None)
wenzelm@64605
   249
      })
wenzelm@64605
   250
  }
wenzelm@64605
   251
wenzelm@64646
   252
  def exit() {
wenzelm@64646
   253
    channel.log("\n")
wenzelm@64646
   254
    sys.exit(if (state.value.session.isDefined) 1 else 0)
wenzelm@64646
   255
  }
wenzelm@64605
   256
wenzelm@64605
   257
wenzelm@64622
   258
  /* hover */
wenzelm@64605
   259
wenzelm@64651
   260
  def hover(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64641
   261
  {
wenzelm@64641
   262
    val result =
wenzelm@64641
   263
      for {
wenzelm@64651
   264
        (rendering, offset) <- rendering_offset(node_pos)
wenzelm@64641
   265
        info <- rendering.tooltip(Text.Range(offset, offset + 1))
wenzelm@64641
   266
      } yield {
wenzelm@64649
   267
        val doc = rendering.model.doc
wenzelm@64683
   268
        val range = doc.range(info.range)
wenzelm@64641
   269
        val s = Pretty.string_of(info.info, margin = rendering.tooltip_margin)
wenzelm@64679
   270
        (range, List("```\n" + s + "\n```"))  // FIXME proper content format
wenzelm@64641
   271
      }
wenzelm@64641
   272
    channel.write(Protocol.Hover.reply(id, result))
wenzelm@64641
   273
  }
wenzelm@64605
   274
wenzelm@64605
   275
wenzelm@64648
   276
  /* goto definition */
wenzelm@64648
   277
wenzelm@64651
   278
  def goto_definition(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64648
   279
  {
wenzelm@64648
   280
    val result =
wenzelm@64651
   281
      (for ((rendering, offset) <- rendering_offset(node_pos))
wenzelm@64649
   282
        yield rendering.hyperlinks(Text.Range(offset, offset + 1))) getOrElse Nil
wenzelm@64648
   283
    channel.write(Protocol.GotoDefinition.reply(id, result))
wenzelm@64648
   284
  }
wenzelm@64648
   285
wenzelm@64648
   286
wenzelm@64605
   287
  /* main loop */
wenzelm@64605
   288
wenzelm@64605
   289
  def start()
wenzelm@64605
   290
  {
wenzelm@64646
   291
    channel.log("Server started " + Date.now())
wenzelm@64605
   292
wenzelm@64605
   293
    def handle(json: JSON.T)
wenzelm@64605
   294
    {
wenzelm@64605
   295
      try {
wenzelm@64605
   296
        json match {
wenzelm@64641
   297
          case Protocol.Initialize(id) => init(id)
wenzelm@64641
   298
          case Protocol.Shutdown(id) => shutdown(id)
wenzelm@64645
   299
          case Protocol.Exit(()) => exit()
wenzelm@64605
   300
          case Protocol.DidOpenTextDocument(uri, lang, version, text) =>
wenzelm@64605
   301
            update_document(uri, text)
wenzelm@64605
   302
          case Protocol.DidChangeTextDocument(uri, version, List(Protocol.TextDocumentContent(text))) =>
wenzelm@64605
   303
            update_document(uri, text)
wenzelm@64605
   304
          case Protocol.DidCloseTextDocument(uri) => channel.log("CLOSE " + uri)
wenzelm@64605
   305
          case Protocol.DidSaveTextDocument(uri) => channel.log("SAVE " + uri)
wenzelm@64651
   306
          case Protocol.Hover(id, node_pos) => hover(id, node_pos)
wenzelm@64651
   307
          case Protocol.GotoDefinition(id, node_pos) => goto_definition(id, node_pos)
wenzelm@64605
   308
          case _ => channel.log("### IGNORED")
wenzelm@64605
   309
        }
wenzelm@64605
   310
      }
wenzelm@64655
   311
      catch { case exn: Throwable => channel.error_message(Exn.message(exn)) }
wenzelm@64605
   312
    }
wenzelm@64605
   313
wenzelm@64605
   314
    @tailrec def loop()
wenzelm@64605
   315
    {
wenzelm@64605
   316
      channel.read() match {
wenzelm@64605
   317
        case Some(json) =>
wenzelm@64605
   318
          json match {
wenzelm@64605
   319
            case bulk: List[_] => bulk.foreach(handle(_))
wenzelm@64605
   320
            case _ => handle(json)
wenzelm@64605
   321
          }
wenzelm@64605
   322
          loop()
wenzelm@64605
   323
        case None => channel.log("### TERMINATE")
wenzelm@64605
   324
      }
wenzelm@64605
   325
    }
wenzelm@64605
   326
    loop()
wenzelm@64605
   327
  }
wenzelm@64605
   328
}