src/Tools/VSCode/src/server.scala
author wenzelm
Mon Jan 02 11:42:15 2017 +0100 (2017-01-02)
changeset 64748 155bf8632104
parent 64747 54afac94f52b
child 64755 ceb81f4928ea
permissions -rw-r--r--
clarified multiple tooltips;
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@64710
    14
import java.io.{PrintStream, OutputStream, File => JFile}
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@64733
    35
      var system_mode = false
wenzelm@64605
    36
wenzelm@64644
    37
      def text_length_choice: String =
wenzelm@64682
    38
        commas(Text.Length.encodings.map(
wenzelm@64644
    39
          { case (a, _) => if (a == default_text_length) a + " (default)" else a }))
wenzelm@64618
    40
wenzelm@64644
    41
      val getopts = Getopts("""
wenzelm@64605
    42
Usage: isabelle vscode_server [OPTIONS]
wenzelm@64605
    43
wenzelm@64605
    44
  Options are:
wenzelm@64605
    45
    -L FILE      enable logging on FILE
wenzelm@64618
    46
    -T LENGTH    text length encoding: """ + text_length_choice + """
wenzelm@64605
    47
    -d DIR       include session directory
wenzelm@64737
    48
    -l NAME      logic session name (default ISABELLE_LOGIC=""" + quote(default_logic) + """)
wenzelm@64605
    49
    -m MODE      add print mode for output
wenzelm@64605
    50
    -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
wenzelm@64733
    51
    -s           system build mode for session image
wenzelm@64605
    52
wenzelm@64605
    53
  Run the VSCode Language Server protocol (JSON RPC) over stdin/stdout.
wenzelm@64605
    54
""",
wenzelm@64644
    55
        "L:" -> (arg => log_file = Some(Path.explode(arg))),
wenzelm@64682
    56
        "T:" -> (arg => Text.Length.encoding(arg)),
wenzelm@64644
    57
        "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
wenzelm@64644
    58
        "l:" -> (arg => logic = arg),
wenzelm@64644
    59
        "m:" -> (arg => modes = arg :: modes),
wenzelm@64733
    60
        "o:" -> (arg => options = options + arg),
wenzelm@64733
    61
        "s" -> (_ => system_mode = true))
wenzelm@64605
    62
wenzelm@64644
    63
      val more_args = getopts(args)
wenzelm@64644
    64
      if (more_args.nonEmpty) getopts.usage()
wenzelm@64644
    65
wenzelm@64717
    66
      val log = Logger.make(log_file)
wenzelm@64717
    67
      val channel = new Channel(System.in, System.out, log)
wenzelm@64733
    68
      val server = new Server(channel, options, text_length, logic, dirs, modes, system_mode, log)
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@64717
    80
        val channel = new Channel(System.in, System.out, No_Logger)
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
class Server(
wenzelm@64605
    88
  channel: Channel,
wenzelm@64605
    89
  options: Options,
wenzelm@64682
    90
  text_length: Text.Length = Text.Length.encoding(Server.default_text_length),
wenzelm@64605
    91
  session_name: String = Server.default_logic,
wenzelm@64605
    92
  session_dirs: List[Path] = Nil,
wenzelm@64717
    93
  modes: List[String] = Nil,
wenzelm@64733
    94
  system_mode: Boolean = false,
wenzelm@64717
    95
  log: Logger = No_Logger)
wenzelm@64605
    96
{
wenzelm@64725
    97
  /* prover session */
wenzelm@64605
    98
wenzelm@64703
    99
  private val session_ = Synchronized(None: Option[Session])
wenzelm@64703
   100
  def session: Session = session_.value getOrElse error("Server inactive")
wenzelm@64623
   101
  def resources: VSCode_Resources = session.resources.asInstanceOf[VSCode_Resources]
wenzelm@64605
   102
wenzelm@64651
   103
  def rendering_offset(node_pos: Line.Node_Position): Option[(VSCode_Rendering, Text.Offset)] =
wenzelm@64649
   104
    for {
wenzelm@64703
   105
      model <- resources.get_model(node_pos.name)
wenzelm@64704
   106
      rendering = model.rendering()
wenzelm@64683
   107
      offset <- model.doc.offset(node_pos.pos)
wenzelm@64649
   108
    } yield (rendering, offset)
wenzelm@64649
   109
wenzelm@64605
   110
wenzelm@64725
   111
  /* input from client or file-system */
wenzelm@64725
   112
wenzelm@64725
   113
  private val delay_input =
wenzelm@64725
   114
    Standard_Thread.delay_last(options.seconds("vscode_input_delay"))
wenzelm@64725
   115
    { resources.flush_input(session) }
wenzelm@64725
   116
wenzelm@64727
   117
  private val delay_load =
wenzelm@64727
   118
    Standard_Thread.delay_last(options.seconds("vscode_load_delay"))
wenzelm@64727
   119
    { if (resources.resolve_dependencies(session)) delay_input.invoke() }
wenzelm@64727
   120
wenzelm@64727
   121
  private val watcher =
wenzelm@64727
   122
    File_Watcher(sync_documents(_), options.seconds("vscode_load_delay"))
wenzelm@64725
   123
wenzelm@64725
   124
  private def sync_documents(changed: Set[JFile]): Unit =
wenzelm@64725
   125
    if (resources.sync_models(changed)) delay_input.invoke()
wenzelm@64679
   126
wenzelm@64703
   127
  private def update_document(uri: String, text: String)
wenzelm@64679
   128
  {
wenzelm@64709
   129
    resources.update_model(session, uri, text)
wenzelm@64679
   130
    delay_input.invoke()
wenzelm@64679
   131
  }
wenzelm@64679
   132
wenzelm@64710
   133
  private def close_document(uri: String)
wenzelm@64710
   134
  {
wenzelm@64710
   135
    resources.close_model(uri) match {
wenzelm@64710
   136
      case Some(model) =>
wenzelm@64710
   137
        model.register(watcher)
wenzelm@64725
   138
        sync_documents(Set(model.file))
wenzelm@64710
   139
      case None =>
wenzelm@64710
   140
    }
wenzelm@64710
   141
  }
wenzelm@64710
   142
wenzelm@64679
   143
wenzelm@64679
   144
  /* output to client */
wenzelm@64679
   145
wenzelm@64691
   146
  private val delay_output: Standard_Thread.Delay =
wenzelm@64703
   147
    Standard_Thread.delay_last(options.seconds("vscode_output_delay"))
wenzelm@64703
   148
    {
wenzelm@64691
   149
      if (session.current_state().stable_tip_version.isEmpty) delay_output.invoke()
wenzelm@64703
   150
      else resources.flush_output(channel)
wenzelm@64679
   151
    }
wenzelm@64679
   152
wenzelm@64725
   153
  private val prover_output =
wenzelm@64725
   154
    Session.Consumer[Session.Commands_Changed](getClass.getName) {
wenzelm@64725
   155
      case changed if changed.nodes.nonEmpty =>
wenzelm@64725
   156
        resources.update_output(changed.nodes.toList.map(_.node))
wenzelm@64725
   157
        delay_output.invoke()
wenzelm@64725
   158
      case _ =>
wenzelm@64725
   159
    }
wenzelm@64710
   160
wenzelm@64725
   161
  private val syslog =
wenzelm@64692
   162
    Session.Consumer[Prover.Message](getClass.getName) {
wenzelm@64692
   163
      case output: Prover.Output if output.is_syslog =>
wenzelm@64692
   164
        channel.log_writeln(XML.content(output.message))
wenzelm@64692
   165
      case _ =>
wenzelm@64692
   166
    }
wenzelm@64692
   167
wenzelm@64692
   168
wenzelm@64605
   169
  /* init and exit */
wenzelm@64605
   170
wenzelm@64641
   171
  def init(id: Protocol.Id)
wenzelm@64605
   172
  {
wenzelm@64641
   173
    def reply(err: String)
wenzelm@64641
   174
    {
wenzelm@64641
   175
      channel.write(Protocol.Initialize.reply(id, err))
wenzelm@64642
   176
      if (err == "")
wenzelm@64642
   177
        channel.writeln("Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")")
wenzelm@64642
   178
      else channel.error_message(err)
wenzelm@64641
   179
    }
wenzelm@64641
   180
wenzelm@64643
   181
    val try_session =
wenzelm@64643
   182
      try {
wenzelm@64733
   183
        if (!Build.build(options = options, build_heap = true, no_build = true,
wenzelm@64733
   184
              system_mode = system_mode, dirs = session_dirs, sessions = List(session_name)).ok)
wenzelm@64733
   185
        {
wenzelm@64733
   186
          val start_msg = "Build started for Isabelle/" + session_name + " ..."
wenzelm@64733
   187
          val fail_msg = "Session build failed -- prover process remains inactive!"
wenzelm@64733
   188
wenzelm@64733
   189
          val progress = channel.make_progress(verbose = true)
wenzelm@64733
   190
          progress.echo(start_msg); channel.writeln(start_msg)
wenzelm@64733
   191
wenzelm@64733
   192
          if (!Build.build(options = options, progress = progress, build_heap = true,
wenzelm@64733
   193
              system_mode = system_mode, dirs = session_dirs, sessions = List(session_name)).ok)
wenzelm@64733
   194
          {
wenzelm@64733
   195
            progress.echo(fail_msg); error(fail_msg)
wenzelm@64733
   196
          }
wenzelm@64733
   197
        }
wenzelm@64733
   198
wenzelm@64643
   199
        val content = Build.session_content(options, false, session_dirs, session_name)
wenzelm@64643
   200
        val resources =
wenzelm@64720
   201
          new VSCode_Resources(options, text_length, content.loaded_theories,
wenzelm@64727
   202
              content.known_theories, content.syntax, log) {
wenzelm@64727
   203
            override def commit(change: Session.Change): Unit =
wenzelm@64727
   204
              if (change.deps_changed) delay_load.invoke()
wenzelm@64727
   205
          }
wenzelm@64605
   206
wenzelm@64643
   207
        Some(new Session(resources) {
wenzelm@64643
   208
          override def output_delay = options.seconds("editor_output_delay")
wenzelm@64643
   209
          override def prune_delay = options.seconds("editor_prune_delay")
wenzelm@64643
   210
          override def syslog_limit = options.int("editor_syslog_limit")
wenzelm@64643
   211
          override def reparse_limit = options.int("editor_reparse_limit")
wenzelm@64643
   212
        })
wenzelm@64605
   213
      }
wenzelm@64643
   214
      catch { case ERROR(msg) => reply(msg); None }
wenzelm@64605
   215
wenzelm@64643
   216
    for (session <- try_session) {
wenzelm@64643
   217
      var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64643
   218
      session_phase =
wenzelm@64643
   219
        Session.Consumer(getClass.getName) {
wenzelm@64643
   220
          case Session.Ready =>
wenzelm@64643
   221
            session.phase_changed -= session_phase
wenzelm@64643
   222
            session.update_options(options)
wenzelm@64643
   223
            reply("")
wenzelm@64643
   224
          case Session.Failed =>
wenzelm@64643
   225
            session.phase_changed -= session_phase
wenzelm@64643
   226
            reply("Prover startup failed")
wenzelm@64643
   227
          case _ =>
wenzelm@64643
   228
        }
wenzelm@64643
   229
      session.phase_changed += session_phase
wenzelm@64605
   230
wenzelm@64725
   231
      session.commands_changed += prover_output
wenzelm@64725
   232
      session.all_messages += syslog
wenzelm@64679
   233
wenzelm@64643
   234
      session.start(receiver =>
wenzelm@64643
   235
        Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
wenzelm@64643
   236
          modes = modes, receiver = receiver))
wenzelm@64605
   237
wenzelm@64703
   238
      session_.change(_ => Some(session))
wenzelm@64643
   239
    }
wenzelm@64605
   240
  }
wenzelm@64605
   241
wenzelm@64641
   242
  def shutdown(id: Protocol.Id)
wenzelm@64605
   243
  {
wenzelm@64641
   244
    def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
wenzelm@64641
   245
wenzelm@64703
   246
    session_.change({
wenzelm@64703
   247
      case Some(session) =>
wenzelm@64703
   248
        var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64703
   249
        session_phase =
wenzelm@64703
   250
          Session.Consumer(getClass.getName) {
wenzelm@64703
   251
            case Session.Inactive =>
wenzelm@64703
   252
              session.phase_changed -= session_phase
wenzelm@64725
   253
              session.commands_changed -= prover_output
wenzelm@64725
   254
              session.all_messages -= syslog
wenzelm@64703
   255
              reply("")
wenzelm@64703
   256
            case _ =>
wenzelm@64703
   257
          }
wenzelm@64703
   258
        session.phase_changed += session_phase
wenzelm@64703
   259
        session.stop()
wenzelm@64703
   260
        delay_input.revoke()
wenzelm@64703
   261
        delay_output.revoke()
wenzelm@64710
   262
        watcher.shutdown()
wenzelm@64703
   263
        None
wenzelm@64703
   264
      case None =>
wenzelm@64703
   265
        reply("Prover inactive")
wenzelm@64703
   266
        None
wenzelm@64703
   267
    })
wenzelm@64605
   268
  }
wenzelm@64605
   269
wenzelm@64646
   270
  def exit() {
wenzelm@64717
   271
    log("\n")
wenzelm@64703
   272
    sys.exit(if (session_.value.isDefined) 1 else 0)
wenzelm@64646
   273
  }
wenzelm@64605
   274
wenzelm@64605
   275
wenzelm@64622
   276
  /* hover */
wenzelm@64605
   277
wenzelm@64651
   278
  def hover(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64641
   279
  {
wenzelm@64641
   280
    val result =
wenzelm@64641
   281
      for {
wenzelm@64651
   282
        (rendering, offset) <- rendering_offset(node_pos)
wenzelm@64748
   283
        info <- rendering.tooltips(Text.Range(offset, offset + 1))
wenzelm@64641
   284
      } yield {
wenzelm@64649
   285
        val doc = rendering.model.doc
wenzelm@64683
   286
        val range = doc.range(info.range)
wenzelm@64748
   287
        val contents =
wenzelm@64748
   288
          info.info.map(tree => Pretty.string_of(List(tree), margin = rendering.tooltip_margin))
wenzelm@64748
   289
        (range, contents)
wenzelm@64641
   290
      }
wenzelm@64641
   291
    channel.write(Protocol.Hover.reply(id, result))
wenzelm@64641
   292
  }
wenzelm@64605
   293
wenzelm@64605
   294
wenzelm@64648
   295
  /* goto definition */
wenzelm@64648
   296
wenzelm@64651
   297
  def goto_definition(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64648
   298
  {
wenzelm@64648
   299
    val result =
wenzelm@64651
   300
      (for ((rendering, offset) <- rendering_offset(node_pos))
wenzelm@64649
   301
        yield rendering.hyperlinks(Text.Range(offset, offset + 1))) getOrElse Nil
wenzelm@64648
   302
    channel.write(Protocol.GotoDefinition.reply(id, result))
wenzelm@64648
   303
  }
wenzelm@64648
   304
wenzelm@64648
   305
wenzelm@64605
   306
  /* main loop */
wenzelm@64605
   307
wenzelm@64605
   308
  def start()
wenzelm@64605
   309
  {
wenzelm@64717
   310
    log("Server started " + Date.now())
wenzelm@64605
   311
wenzelm@64605
   312
    def handle(json: JSON.T)
wenzelm@64605
   313
    {
wenzelm@64605
   314
      try {
wenzelm@64605
   315
        json match {
wenzelm@64641
   316
          case Protocol.Initialize(id) => init(id)
wenzelm@64641
   317
          case Protocol.Shutdown(id) => shutdown(id)
wenzelm@64645
   318
          case Protocol.Exit(()) => exit()
wenzelm@64605
   319
          case Protocol.DidOpenTextDocument(uri, lang, version, text) =>
wenzelm@64605
   320
            update_document(uri, text)
wenzelm@64605
   321
          case Protocol.DidChangeTextDocument(uri, version, List(Protocol.TextDocumentContent(text))) =>
wenzelm@64605
   322
            update_document(uri, text)
wenzelm@64710
   323
          case Protocol.DidCloseTextDocument(uri) =>
wenzelm@64710
   324
            close_document(uri)
wenzelm@64651
   325
          case Protocol.Hover(id, node_pos) => hover(id, node_pos)
wenzelm@64651
   326
          case Protocol.GotoDefinition(id, node_pos) => goto_definition(id, node_pos)
wenzelm@64717
   327
          case _ => log("### IGNORED")
wenzelm@64605
   328
        }
wenzelm@64605
   329
      }
wenzelm@64687
   330
      catch { case exn: Throwable => channel.log_error_message(Exn.message(exn)) }
wenzelm@64605
   331
    }
wenzelm@64605
   332
wenzelm@64605
   333
    @tailrec def loop()
wenzelm@64605
   334
    {
wenzelm@64605
   335
      channel.read() match {
wenzelm@64605
   336
        case Some(json) =>
wenzelm@64605
   337
          json match {
wenzelm@64605
   338
            case bulk: List[_] => bulk.foreach(handle(_))
wenzelm@64605
   339
            case _ => handle(json)
wenzelm@64605
   340
          }
wenzelm@64605
   341
          loop()
wenzelm@64717
   342
        case None => log("### TERMINATE")
wenzelm@64605
   343
      }
wenzelm@64605
   344
    }
wenzelm@64605
   345
    loop()
wenzelm@64605
   346
  }
wenzelm@64605
   347
}