src/Tools/VSCode/src/server.scala
author wenzelm
Sat Dec 31 20:26:34 2016 +0100 (2016-12-31)
changeset 64727 13e37567a0d6
parent 64725 38305f56c769
child 64733 20174e871623
permissions -rw-r--r--
automatically resolve dependencies from document models and file-system;
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@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@64717
    67
      val log = Logger.make(log_file)
wenzelm@64717
    68
      val channel = new Channel(System.in, System.out, log)
wenzelm@64717
    69
      val server = new Server(channel, options, text_length, logic, dirs, modes, log)
wenzelm@64605
    70
wenzelm@64644
    71
      // prevent spurious garbage on the main protocol channel
wenzelm@64644
    72
      val orig_out = System.out
wenzelm@64644
    73
      try {
wenzelm@64644
    74
        System.setOut(new PrintStream(new OutputStream { def write(n: Int) {} }))
wenzelm@64644
    75
        server.start()
wenzelm@64644
    76
      }
wenzelm@64644
    77
      finally { System.setOut(orig_out) }
wenzelm@64605
    78
    }
wenzelm@64644
    79
    catch {
wenzelm@64644
    80
      case exn: Throwable =>
wenzelm@64717
    81
        val channel = new Channel(System.in, System.out, No_Logger)
wenzelm@64644
    82
        channel.error_message(Exn.message(exn))
wenzelm@64644
    83
        throw(exn)
wenzelm@64644
    84
    }
wenzelm@64605
    85
  })
wenzelm@64605
    86
}
wenzelm@64605
    87
wenzelm@64605
    88
class Server(
wenzelm@64605
    89
  channel: Channel,
wenzelm@64605
    90
  options: Options,
wenzelm@64682
    91
  text_length: Text.Length = Text.Length.encoding(Server.default_text_length),
wenzelm@64605
    92
  session_name: String = Server.default_logic,
wenzelm@64605
    93
  session_dirs: List[Path] = Nil,
wenzelm@64717
    94
  modes: List[String] = Nil,
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@64643
   183
        val content = Build.session_content(options, false, session_dirs, session_name)
wenzelm@64643
   184
        val resources =
wenzelm@64720
   185
          new VSCode_Resources(options, text_length, content.loaded_theories,
wenzelm@64727
   186
              content.known_theories, content.syntax, log) {
wenzelm@64727
   187
            override def commit(change: Session.Change): Unit =
wenzelm@64727
   188
              if (change.deps_changed) delay_load.invoke()
wenzelm@64727
   189
          }
wenzelm@64605
   190
wenzelm@64643
   191
        Some(new Session(resources) {
wenzelm@64643
   192
          override def output_delay = options.seconds("editor_output_delay")
wenzelm@64643
   193
          override def prune_delay = options.seconds("editor_prune_delay")
wenzelm@64643
   194
          override def syslog_limit = options.int("editor_syslog_limit")
wenzelm@64643
   195
          override def reparse_limit = options.int("editor_reparse_limit")
wenzelm@64643
   196
        })
wenzelm@64605
   197
      }
wenzelm@64643
   198
      catch { case ERROR(msg) => reply(msg); None }
wenzelm@64605
   199
wenzelm@64643
   200
    for (session <- try_session) {
wenzelm@64643
   201
      var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64643
   202
      session_phase =
wenzelm@64643
   203
        Session.Consumer(getClass.getName) {
wenzelm@64643
   204
          case Session.Ready =>
wenzelm@64643
   205
            session.phase_changed -= session_phase
wenzelm@64643
   206
            session.update_options(options)
wenzelm@64643
   207
            reply("")
wenzelm@64643
   208
          case Session.Failed =>
wenzelm@64643
   209
            session.phase_changed -= session_phase
wenzelm@64643
   210
            reply("Prover startup failed")
wenzelm@64643
   211
          case _ =>
wenzelm@64643
   212
        }
wenzelm@64643
   213
      session.phase_changed += session_phase
wenzelm@64605
   214
wenzelm@64725
   215
      session.commands_changed += prover_output
wenzelm@64725
   216
      session.all_messages += syslog
wenzelm@64679
   217
wenzelm@64643
   218
      session.start(receiver =>
wenzelm@64643
   219
        Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
wenzelm@64643
   220
          modes = modes, receiver = receiver))
wenzelm@64605
   221
wenzelm@64703
   222
      session_.change(_ => Some(session))
wenzelm@64643
   223
    }
wenzelm@64605
   224
  }
wenzelm@64605
   225
wenzelm@64641
   226
  def shutdown(id: Protocol.Id)
wenzelm@64605
   227
  {
wenzelm@64641
   228
    def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
wenzelm@64641
   229
wenzelm@64703
   230
    session_.change({
wenzelm@64703
   231
      case Some(session) =>
wenzelm@64703
   232
        var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64703
   233
        session_phase =
wenzelm@64703
   234
          Session.Consumer(getClass.getName) {
wenzelm@64703
   235
            case Session.Inactive =>
wenzelm@64703
   236
              session.phase_changed -= session_phase
wenzelm@64725
   237
              session.commands_changed -= prover_output
wenzelm@64725
   238
              session.all_messages -= syslog
wenzelm@64703
   239
              reply("")
wenzelm@64703
   240
            case _ =>
wenzelm@64703
   241
          }
wenzelm@64703
   242
        session.phase_changed += session_phase
wenzelm@64703
   243
        session.stop()
wenzelm@64703
   244
        delay_input.revoke()
wenzelm@64703
   245
        delay_output.revoke()
wenzelm@64710
   246
        watcher.shutdown()
wenzelm@64703
   247
        None
wenzelm@64703
   248
      case None =>
wenzelm@64703
   249
        reply("Prover inactive")
wenzelm@64703
   250
        None
wenzelm@64703
   251
    })
wenzelm@64605
   252
  }
wenzelm@64605
   253
wenzelm@64646
   254
  def exit() {
wenzelm@64717
   255
    log("\n")
wenzelm@64703
   256
    sys.exit(if (session_.value.isDefined) 1 else 0)
wenzelm@64646
   257
  }
wenzelm@64605
   258
wenzelm@64605
   259
wenzelm@64622
   260
  /* hover */
wenzelm@64605
   261
wenzelm@64651
   262
  def hover(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64641
   263
  {
wenzelm@64641
   264
    val result =
wenzelm@64641
   265
      for {
wenzelm@64651
   266
        (rendering, offset) <- rendering_offset(node_pos)
wenzelm@64641
   267
        info <- rendering.tooltip(Text.Range(offset, offset + 1))
wenzelm@64641
   268
      } yield {
wenzelm@64649
   269
        val doc = rendering.model.doc
wenzelm@64683
   270
        val range = doc.range(info.range)
wenzelm@64641
   271
        val s = Pretty.string_of(info.info, margin = rendering.tooltip_margin)
wenzelm@64679
   272
        (range, List("```\n" + s + "\n```"))  // FIXME proper content format
wenzelm@64641
   273
      }
wenzelm@64641
   274
    channel.write(Protocol.Hover.reply(id, result))
wenzelm@64641
   275
  }
wenzelm@64605
   276
wenzelm@64605
   277
wenzelm@64648
   278
  /* goto definition */
wenzelm@64648
   279
wenzelm@64651
   280
  def goto_definition(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64648
   281
  {
wenzelm@64648
   282
    val result =
wenzelm@64651
   283
      (for ((rendering, offset) <- rendering_offset(node_pos))
wenzelm@64649
   284
        yield rendering.hyperlinks(Text.Range(offset, offset + 1))) getOrElse Nil
wenzelm@64648
   285
    channel.write(Protocol.GotoDefinition.reply(id, result))
wenzelm@64648
   286
  }
wenzelm@64648
   287
wenzelm@64648
   288
wenzelm@64605
   289
  /* main loop */
wenzelm@64605
   290
wenzelm@64605
   291
  def start()
wenzelm@64605
   292
  {
wenzelm@64717
   293
    log("Server started " + Date.now())
wenzelm@64605
   294
wenzelm@64605
   295
    def handle(json: JSON.T)
wenzelm@64605
   296
    {
wenzelm@64605
   297
      try {
wenzelm@64605
   298
        json match {
wenzelm@64641
   299
          case Protocol.Initialize(id) => init(id)
wenzelm@64641
   300
          case Protocol.Shutdown(id) => shutdown(id)
wenzelm@64645
   301
          case Protocol.Exit(()) => exit()
wenzelm@64605
   302
          case Protocol.DidOpenTextDocument(uri, lang, version, text) =>
wenzelm@64605
   303
            update_document(uri, text)
wenzelm@64605
   304
          case Protocol.DidChangeTextDocument(uri, version, List(Protocol.TextDocumentContent(text))) =>
wenzelm@64605
   305
            update_document(uri, text)
wenzelm@64710
   306
          case Protocol.DidCloseTextDocument(uri) =>
wenzelm@64710
   307
            close_document(uri)
wenzelm@64651
   308
          case Protocol.Hover(id, node_pos) => hover(id, node_pos)
wenzelm@64651
   309
          case Protocol.GotoDefinition(id, node_pos) => goto_definition(id, node_pos)
wenzelm@64717
   310
          case _ => log("### IGNORED")
wenzelm@64605
   311
        }
wenzelm@64605
   312
      }
wenzelm@64687
   313
      catch { case exn: Throwable => channel.log_error_message(Exn.message(exn)) }
wenzelm@64605
   314
    }
wenzelm@64605
   315
wenzelm@64605
   316
    @tailrec def loop()
wenzelm@64605
   317
    {
wenzelm@64605
   318
      channel.read() match {
wenzelm@64605
   319
        case Some(json) =>
wenzelm@64605
   320
          json match {
wenzelm@64605
   321
            case bulk: List[_] => bulk.foreach(handle(_))
wenzelm@64605
   322
            case _ => handle(json)
wenzelm@64605
   323
          }
wenzelm@64605
   324
          loop()
wenzelm@64717
   325
        case None => log("### TERMINATE")
wenzelm@64605
   326
      }
wenzelm@64605
   327
    }
wenzelm@64605
   328
    loop()
wenzelm@64605
   329
  }
wenzelm@64605
   330
}