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