src/Tools/VSCode/src/server.scala
author wenzelm
Fri Dec 30 20:36:13 2016 +0100 (2016-12-30)
changeset 64710 72ca4e5f976e
parent 64709 5e6566ab78bf
child 64717 d2b50eb3d9ab
permissions -rw-r--r--
manage changes of external files;
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@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@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
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@64605
    93
  modes: List[String] = Nil)
wenzelm@64605
    94
{
wenzelm@64703
    95
  /* server session */
wenzelm@64605
    96
wenzelm@64703
    97
  private val session_ = Synchronized(None: Option[Session])
wenzelm@64703
    98
  def session: Session = session_.value getOrElse error("Server inactive")
wenzelm@64623
    99
  def resources: VSCode_Resources = session.resources.asInstanceOf[VSCode_Resources]
wenzelm@64605
   100
wenzelm@64651
   101
  def rendering_offset(node_pos: Line.Node_Position): Option[(VSCode_Rendering, Text.Offset)] =
wenzelm@64649
   102
    for {
wenzelm@64703
   103
      model <- resources.get_model(node_pos.name)
wenzelm@64704
   104
      rendering = model.rendering()
wenzelm@64683
   105
      offset <- model.doc.offset(node_pos.pos)
wenzelm@64649
   106
    } yield (rendering, offset)
wenzelm@64649
   107
wenzelm@64605
   108
wenzelm@64710
   109
  /* document content */
wenzelm@64679
   110
wenzelm@64703
   111
  private def update_document(uri: String, text: String)
wenzelm@64679
   112
  {
wenzelm@64709
   113
    resources.update_model(session, uri, text)
wenzelm@64679
   114
    delay_input.invoke()
wenzelm@64679
   115
  }
wenzelm@64679
   116
wenzelm@64710
   117
  private def close_document(uri: String)
wenzelm@64710
   118
  {
wenzelm@64710
   119
    resources.close_model(uri) match {
wenzelm@64710
   120
      case Some(model) =>
wenzelm@64710
   121
        model.register(watcher)
wenzelm@64710
   122
        sync_external(Set(model.file))
wenzelm@64710
   123
      case None =>
wenzelm@64710
   124
    }
wenzelm@64710
   125
  }
wenzelm@64710
   126
wenzelm@64710
   127
  private def sync_external(changed: Set[JFile]): Unit =
wenzelm@64710
   128
    if (resources.sync_external(changed)) delay_input.invoke()
wenzelm@64710
   129
wenzelm@64710
   130
  private val watcher = File_Watcher(sync_external(_))
wenzelm@64710
   131
wenzelm@64710
   132
wenzelm@64710
   133
  /* input from client */
wenzelm@64710
   134
wenzelm@64710
   135
  private val delay_input =
wenzelm@64710
   136
    Standard_Thread.delay_last(options.seconds("vscode_input_delay"))
wenzelm@64710
   137
    { resources.flush_input(session) }
wenzelm@64710
   138
wenzelm@64679
   139
wenzelm@64679
   140
  /* output to client */
wenzelm@64679
   141
wenzelm@64679
   142
  private val commands_changed =
wenzelm@64679
   143
    Session.Consumer[Session.Commands_Changed](getClass.getName) {
wenzelm@64703
   144
      case changed if changed.nodes.nonEmpty =>
wenzelm@64708
   145
        resources.update_output(changed.nodes.toList.map(_.node))
wenzelm@64679
   146
        delay_output.invoke()
wenzelm@64703
   147
      case _ =>
wenzelm@64679
   148
    }
wenzelm@64679
   149
wenzelm@64691
   150
  private val delay_output: Standard_Thread.Delay =
wenzelm@64703
   151
    Standard_Thread.delay_last(options.seconds("vscode_output_delay"))
wenzelm@64703
   152
    {
wenzelm@64691
   153
      if (session.current_state().stable_tip_version.isEmpty) delay_output.invoke()
wenzelm@64703
   154
      else resources.flush_output(channel)
wenzelm@64679
   155
    }
wenzelm@64679
   156
wenzelm@64679
   157
wenzelm@64710
   158
  /* file watcher */
wenzelm@64710
   159
wenzelm@64710
   160
wenzelm@64692
   161
  /* syslog */
wenzelm@64692
   162
wenzelm@64692
   163
  private val all_messages =
wenzelm@64692
   164
    Session.Consumer[Prover.Message](getClass.getName) {
wenzelm@64692
   165
      case output: Prover.Output if output.is_syslog =>
wenzelm@64692
   166
        channel.log_writeln(XML.content(output.message))
wenzelm@64692
   167
      case _ =>
wenzelm@64692
   168
    }
wenzelm@64692
   169
wenzelm@64692
   170
wenzelm@64605
   171
  /* init and exit */
wenzelm@64605
   172
wenzelm@64641
   173
  def init(id: Protocol.Id)
wenzelm@64605
   174
  {
wenzelm@64641
   175
    def reply(err: String)
wenzelm@64641
   176
    {
wenzelm@64641
   177
      channel.write(Protocol.Initialize.reply(id, err))
wenzelm@64642
   178
      if (err == "")
wenzelm@64642
   179
        channel.writeln("Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")")
wenzelm@64642
   180
      else channel.error_message(err)
wenzelm@64641
   181
    }
wenzelm@64641
   182
wenzelm@64643
   183
    val try_session =
wenzelm@64643
   184
      try {
wenzelm@64643
   185
        val content = Build.session_content(options, false, session_dirs, session_name)
wenzelm@64643
   186
        val resources =
wenzelm@64703
   187
          new VSCode_Resources(
wenzelm@64706
   188
            options, text_length, content.loaded_theories, content.known_theories, content.syntax)
wenzelm@64605
   189
wenzelm@64643
   190
        Some(new Session(resources) {
wenzelm@64643
   191
          override def output_delay = options.seconds("editor_output_delay")
wenzelm@64643
   192
          override def prune_delay = options.seconds("editor_prune_delay")
wenzelm@64643
   193
          override def syslog_limit = options.int("editor_syslog_limit")
wenzelm@64643
   194
          override def reparse_limit = options.int("editor_reparse_limit")
wenzelm@64643
   195
        })
wenzelm@64605
   196
      }
wenzelm@64643
   197
      catch { case ERROR(msg) => reply(msg); None }
wenzelm@64605
   198
wenzelm@64643
   199
    for (session <- try_session) {
wenzelm@64643
   200
      var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64643
   201
      session_phase =
wenzelm@64643
   202
        Session.Consumer(getClass.getName) {
wenzelm@64643
   203
          case Session.Ready =>
wenzelm@64643
   204
            session.phase_changed -= session_phase
wenzelm@64643
   205
            session.update_options(options)
wenzelm@64643
   206
            reply("")
wenzelm@64643
   207
          case Session.Failed =>
wenzelm@64643
   208
            session.phase_changed -= session_phase
wenzelm@64643
   209
            reply("Prover startup failed")
wenzelm@64643
   210
          case _ =>
wenzelm@64643
   211
        }
wenzelm@64643
   212
      session.phase_changed += session_phase
wenzelm@64605
   213
wenzelm@64679
   214
      session.commands_changed += commands_changed
wenzelm@64692
   215
      session.all_messages += all_messages
wenzelm@64679
   216
wenzelm@64643
   217
      session.start(receiver =>
wenzelm@64643
   218
        Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
wenzelm@64643
   219
          modes = modes, receiver = receiver))
wenzelm@64605
   220
wenzelm@64703
   221
      session_.change(_ => Some(session))
wenzelm@64643
   222
    }
wenzelm@64605
   223
  }
wenzelm@64605
   224
wenzelm@64641
   225
  def shutdown(id: Protocol.Id)
wenzelm@64605
   226
  {
wenzelm@64641
   227
    def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
wenzelm@64641
   228
wenzelm@64703
   229
    session_.change({
wenzelm@64703
   230
      case Some(session) =>
wenzelm@64703
   231
        var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64703
   232
        session_phase =
wenzelm@64703
   233
          Session.Consumer(getClass.getName) {
wenzelm@64703
   234
            case Session.Inactive =>
wenzelm@64703
   235
              session.phase_changed -= session_phase
wenzelm@64703
   236
              session.commands_changed -= commands_changed
wenzelm@64703
   237
              session.all_messages -= all_messages
wenzelm@64703
   238
              reply("")
wenzelm@64703
   239
            case _ =>
wenzelm@64703
   240
          }
wenzelm@64703
   241
        session.phase_changed += session_phase
wenzelm@64703
   242
        session.stop()
wenzelm@64703
   243
        delay_input.revoke()
wenzelm@64703
   244
        delay_output.revoke()
wenzelm@64710
   245
        watcher.shutdown()
wenzelm@64703
   246
        None
wenzelm@64703
   247
      case None =>
wenzelm@64703
   248
        reply("Prover inactive")
wenzelm@64703
   249
        None
wenzelm@64703
   250
    })
wenzelm@64605
   251
  }
wenzelm@64605
   252
wenzelm@64646
   253
  def exit() {
wenzelm@64646
   254
    channel.log("\n")
wenzelm@64703
   255
    sys.exit(if (session_.value.isDefined) 1 else 0)
wenzelm@64646
   256
  }
wenzelm@64605
   257
wenzelm@64605
   258
wenzelm@64622
   259
  /* hover */
wenzelm@64605
   260
wenzelm@64651
   261
  def hover(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64641
   262
  {
wenzelm@64641
   263
    val result =
wenzelm@64641
   264
      for {
wenzelm@64651
   265
        (rendering, offset) <- rendering_offset(node_pos)
wenzelm@64641
   266
        info <- rendering.tooltip(Text.Range(offset, offset + 1))
wenzelm@64641
   267
      } yield {
wenzelm@64649
   268
        val doc = rendering.model.doc
wenzelm@64683
   269
        val range = doc.range(info.range)
wenzelm@64641
   270
        val s = Pretty.string_of(info.info, margin = rendering.tooltip_margin)
wenzelm@64679
   271
        (range, List("```\n" + s + "\n```"))  // FIXME proper content format
wenzelm@64641
   272
      }
wenzelm@64641
   273
    channel.write(Protocol.Hover.reply(id, result))
wenzelm@64641
   274
  }
wenzelm@64605
   275
wenzelm@64605
   276
wenzelm@64648
   277
  /* goto definition */
wenzelm@64648
   278
wenzelm@64651
   279
  def goto_definition(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64648
   280
  {
wenzelm@64648
   281
    val result =
wenzelm@64651
   282
      (for ((rendering, offset) <- rendering_offset(node_pos))
wenzelm@64649
   283
        yield rendering.hyperlinks(Text.Range(offset, offset + 1))) getOrElse Nil
wenzelm@64648
   284
    channel.write(Protocol.GotoDefinition.reply(id, result))
wenzelm@64648
   285
  }
wenzelm@64648
   286
wenzelm@64648
   287
wenzelm@64605
   288
  /* main loop */
wenzelm@64605
   289
wenzelm@64605
   290
  def start()
wenzelm@64605
   291
  {
wenzelm@64646
   292
    channel.log("Server started " + Date.now())
wenzelm@64605
   293
wenzelm@64605
   294
    def handle(json: JSON.T)
wenzelm@64605
   295
    {
wenzelm@64605
   296
      try {
wenzelm@64605
   297
        json match {
wenzelm@64641
   298
          case Protocol.Initialize(id) => init(id)
wenzelm@64641
   299
          case Protocol.Shutdown(id) => shutdown(id)
wenzelm@64645
   300
          case Protocol.Exit(()) => exit()
wenzelm@64605
   301
          case Protocol.DidOpenTextDocument(uri, lang, version, text) =>
wenzelm@64605
   302
            update_document(uri, text)
wenzelm@64605
   303
          case Protocol.DidChangeTextDocument(uri, version, List(Protocol.TextDocumentContent(text))) =>
wenzelm@64605
   304
            update_document(uri, text)
wenzelm@64710
   305
          case Protocol.DidCloseTextDocument(uri) =>
wenzelm@64710
   306
            close_document(uri)
wenzelm@64605
   307
          case Protocol.DidSaveTextDocument(uri) => channel.log("SAVE " + 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@64605
   310
          case _ => channel.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@64605
   325
        case None => channel.log("### TERMINATE")
wenzelm@64605
   326
      }
wenzelm@64605
   327
    }
wenzelm@64605
   328
    loop()
wenzelm@64605
   329
  }
wenzelm@64605
   330
}