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