src/Tools/VSCode/src/server.scala
author wenzelm
Wed Dec 21 22:49:53 2016 +0100 (2016-12-21)
changeset 64651 ea5620f7b0d8
parent 64649 d67c3094a0c2
child 64655 ea34f36ff6a5
permissions -rw-r--r--
clarified signature;
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@64644
    30
      var text_length = 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@64644
    37
        commas(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@64644
    54
        "T:" -> (arg => 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
  /* server state */
wenzelm@64605
    88
wenzelm@64605
    89
  sealed case class State(
wenzelm@64605
    90
    session: Option[Session] = None,
wenzelm@64605
    91
    models: Map[String, Document_Model] = Map.empty)
wenzelm@64605
    92
}
wenzelm@64605
    93
wenzelm@64605
    94
class Server(
wenzelm@64605
    95
  channel: Channel,
wenzelm@64605
    96
  options: Options,
wenzelm@64618
    97
  text_length: Length = Length.encoding(Server.default_text_length),
wenzelm@64605
    98
  session_name: String = Server.default_logic,
wenzelm@64605
    99
  session_dirs: List[Path] = Nil,
wenzelm@64605
   100
  modes: List[String] = Nil)
wenzelm@64605
   101
{
wenzelm@64605
   102
  /* server state */
wenzelm@64605
   103
wenzelm@64605
   104
  private val state = Synchronized(Server.State())
wenzelm@64605
   105
wenzelm@64605
   106
  def session: Session = state.value.session getOrElse error("Session inactive")
wenzelm@64623
   107
  def resources: VSCode_Resources = session.resources.asInstanceOf[VSCode_Resources]
wenzelm@64605
   108
wenzelm@64651
   109
  def rendering_offset(node_pos: Line.Node_Position): Option[(VSCode_Rendering, Text.Offset)] =
wenzelm@64649
   110
    for {
wenzelm@64651
   111
      model <- state.value.models.get(node_pos.name)
wenzelm@64649
   112
      rendering = model.rendering(options)
wenzelm@64651
   113
      offset <- model.doc.offset(node_pos.pos, text_length)
wenzelm@64649
   114
    } yield (rendering, offset)
wenzelm@64649
   115
wenzelm@64605
   116
wenzelm@64605
   117
  /* init and exit */
wenzelm@64605
   118
wenzelm@64641
   119
  def init(id: Protocol.Id)
wenzelm@64605
   120
  {
wenzelm@64641
   121
    def reply(err: String)
wenzelm@64641
   122
    {
wenzelm@64641
   123
      channel.write(Protocol.Initialize.reply(id, err))
wenzelm@64642
   124
      if (err == "")
wenzelm@64642
   125
        channel.writeln("Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")")
wenzelm@64642
   126
      else channel.error_message(err)
wenzelm@64641
   127
    }
wenzelm@64641
   128
wenzelm@64643
   129
    val try_session =
wenzelm@64643
   130
      try {
wenzelm@64643
   131
        val content = Build.session_content(options, false, session_dirs, session_name)
wenzelm@64643
   132
        val resources =
wenzelm@64643
   133
          new VSCode_Resources(content.loaded_theories, content.known_theories, content.syntax)
wenzelm@64605
   134
wenzelm@64643
   135
        Some(new Session(resources) {
wenzelm@64643
   136
          override def output_delay = options.seconds("editor_output_delay")
wenzelm@64643
   137
          override def prune_delay = options.seconds("editor_prune_delay")
wenzelm@64643
   138
          override def syslog_limit = options.int("editor_syslog_limit")
wenzelm@64643
   139
          override def reparse_limit = options.int("editor_reparse_limit")
wenzelm@64643
   140
        })
wenzelm@64605
   141
      }
wenzelm@64643
   142
      catch { case ERROR(msg) => reply(msg); None }
wenzelm@64605
   143
wenzelm@64643
   144
    for (session <- try_session) {
wenzelm@64643
   145
      var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64643
   146
      session_phase =
wenzelm@64643
   147
        Session.Consumer(getClass.getName) {
wenzelm@64643
   148
          case Session.Ready =>
wenzelm@64643
   149
            session.phase_changed -= session_phase
wenzelm@64643
   150
            session.update_options(options)
wenzelm@64643
   151
            reply("")
wenzelm@64643
   152
          case Session.Failed =>
wenzelm@64643
   153
            session.phase_changed -= session_phase
wenzelm@64643
   154
            reply("Prover startup failed")
wenzelm@64643
   155
          case _ =>
wenzelm@64643
   156
        }
wenzelm@64643
   157
      session.phase_changed += session_phase
wenzelm@64605
   158
wenzelm@64643
   159
      session.start(receiver =>
wenzelm@64643
   160
        Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
wenzelm@64643
   161
          modes = modes, receiver = receiver))
wenzelm@64605
   162
wenzelm@64643
   163
      state.change(_.copy(session = Some(session)))
wenzelm@64643
   164
    }
wenzelm@64605
   165
  }
wenzelm@64605
   166
wenzelm@64641
   167
  def shutdown(id: Protocol.Id)
wenzelm@64605
   168
  {
wenzelm@64641
   169
    def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
wenzelm@64641
   170
wenzelm@64605
   171
    state.change(st =>
wenzelm@64605
   172
      st.session match {
wenzelm@64605
   173
        case None => reply("Prover inactive"); st
wenzelm@64605
   174
        case Some(session) =>
wenzelm@64605
   175
          var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64605
   176
          session_phase =
wenzelm@64605
   177
            Session.Consumer(getClass.getName) {
wenzelm@64605
   178
              case Session.Inactive =>
wenzelm@64605
   179
                session.phase_changed -= session_phase
wenzelm@64605
   180
                reply("")
wenzelm@64605
   181
              case _ =>
wenzelm@64605
   182
            }
wenzelm@64605
   183
          session.phase_changed += session_phase
wenzelm@64605
   184
          session.stop()
wenzelm@64605
   185
          st.copy(session = None)
wenzelm@64605
   186
      })
wenzelm@64605
   187
  }
wenzelm@64605
   188
wenzelm@64646
   189
  def exit() {
wenzelm@64646
   190
    channel.log("\n")
wenzelm@64646
   191
    sys.exit(if (state.value.session.isDefined) 1 else 0)
wenzelm@64646
   192
  }
wenzelm@64605
   193
wenzelm@64605
   194
wenzelm@64605
   195
  /* document management */
wenzelm@64605
   196
wenzelm@64605
   197
  private val delay_flush =
wenzelm@64605
   198
    Standard_Thread.delay_last(options.seconds("editor_input_delay")) {
wenzelm@64605
   199
      state.change(st =>
wenzelm@64605
   200
        {
wenzelm@64605
   201
          val models = st.models
wenzelm@64605
   202
          val changed = (for { entry <- models.iterator if entry._2.changed } yield entry).toList
wenzelm@64605
   203
          val edits = for { (_, model) <- changed; edit <- model.node_edits } yield edit
wenzelm@64605
   204
          val models1 =
wenzelm@64605
   205
            (models /: changed)({ case (m, (uri, model)) => m + (uri -> model.unchanged) })
wenzelm@64605
   206
wenzelm@64605
   207
          session.update(Document.Blobs.empty, edits)
wenzelm@64605
   208
          st.copy(models = models1)
wenzelm@64605
   209
        })
wenzelm@64605
   210
    }
wenzelm@64605
   211
wenzelm@64605
   212
  def update_document(uri: String, text: String)
wenzelm@64605
   213
  {
wenzelm@64605
   214
    state.change(st =>
wenzelm@64605
   215
      {
wenzelm@64605
   216
        val node_name = resources.node_name(uri)
wenzelm@64605
   217
        val model = Document_Model(session, Line.Document(text), node_name)
wenzelm@64605
   218
        st.copy(models = st.models + (uri -> model))
wenzelm@64605
   219
      })
wenzelm@64605
   220
    delay_flush.invoke()
wenzelm@64605
   221
  }
wenzelm@64605
   222
wenzelm@64605
   223
wenzelm@64622
   224
  /* hover */
wenzelm@64605
   225
wenzelm@64651
   226
  def hover(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64641
   227
  {
wenzelm@64641
   228
    val result =
wenzelm@64641
   229
      for {
wenzelm@64651
   230
        (rendering, offset) <- rendering_offset(node_pos)
wenzelm@64641
   231
        info <- rendering.tooltip(Text.Range(offset, offset + 1))
wenzelm@64641
   232
      } yield {
wenzelm@64649
   233
        val doc = rendering.model.doc
wenzelm@64649
   234
        val start = doc.position(info.range.start, text_length)
wenzelm@64649
   235
        val stop = doc.position(info.range.stop, text_length)
wenzelm@64641
   236
        val s = Pretty.string_of(info.info, margin = rendering.tooltip_margin)
wenzelm@64641
   237
        (Line.Range(start, stop), List("```\n" + s + "\n```"))  // FIXME proper content format
wenzelm@64641
   238
      }
wenzelm@64641
   239
    channel.write(Protocol.Hover.reply(id, result))
wenzelm@64641
   240
  }
wenzelm@64605
   241
wenzelm@64605
   242
wenzelm@64648
   243
  /* goto definition */
wenzelm@64648
   244
wenzelm@64651
   245
  def goto_definition(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64648
   246
  {
wenzelm@64648
   247
    val result =
wenzelm@64651
   248
      (for ((rendering, offset) <- rendering_offset(node_pos))
wenzelm@64649
   249
        yield rendering.hyperlinks(Text.Range(offset, offset + 1))) getOrElse Nil
wenzelm@64648
   250
    channel.write(Protocol.GotoDefinition.reply(id, result))
wenzelm@64648
   251
  }
wenzelm@64648
   252
wenzelm@64648
   253
wenzelm@64605
   254
  /* main loop */
wenzelm@64605
   255
wenzelm@64605
   256
  def start()
wenzelm@64605
   257
  {
wenzelm@64646
   258
    channel.log("Server started " + Date.now())
wenzelm@64605
   259
wenzelm@64605
   260
    def handle(json: JSON.T)
wenzelm@64605
   261
    {
wenzelm@64605
   262
      try {
wenzelm@64605
   263
        json match {
wenzelm@64641
   264
          case Protocol.Initialize(id) => init(id)
wenzelm@64641
   265
          case Protocol.Shutdown(id) => shutdown(id)
wenzelm@64645
   266
          case Protocol.Exit(()) => exit()
wenzelm@64605
   267
          case Protocol.DidOpenTextDocument(uri, lang, version, text) =>
wenzelm@64605
   268
            update_document(uri, text)
wenzelm@64605
   269
          case Protocol.DidChangeTextDocument(uri, version, List(Protocol.TextDocumentContent(text))) =>
wenzelm@64605
   270
            update_document(uri, text)
wenzelm@64605
   271
          case Protocol.DidCloseTextDocument(uri) => channel.log("CLOSE " + uri)
wenzelm@64605
   272
          case Protocol.DidSaveTextDocument(uri) => channel.log("SAVE " + uri)
wenzelm@64651
   273
          case Protocol.Hover(id, node_pos) => hover(id, node_pos)
wenzelm@64651
   274
          case Protocol.GotoDefinition(id, node_pos) => goto_definition(id, node_pos)
wenzelm@64605
   275
          case _ => channel.log("### IGNORED")
wenzelm@64605
   276
        }
wenzelm@64605
   277
      }
wenzelm@64605
   278
      catch { case exn: Throwable => channel.log("*** ERROR: " + Exn.message(exn)) }
wenzelm@64605
   279
    }
wenzelm@64605
   280
wenzelm@64605
   281
    @tailrec def loop()
wenzelm@64605
   282
    {
wenzelm@64605
   283
      channel.read() match {
wenzelm@64605
   284
        case Some(json) =>
wenzelm@64605
   285
          json match {
wenzelm@64605
   286
            case bulk: List[_] => bulk.foreach(handle(_))
wenzelm@64605
   287
            case _ => handle(json)
wenzelm@64605
   288
          }
wenzelm@64605
   289
          loop()
wenzelm@64605
   290
        case None => channel.log("### TERMINATE")
wenzelm@64605
   291
      }
wenzelm@64605
   292
    }
wenzelm@64605
   293
    loop()
wenzelm@64605
   294
  }
wenzelm@64605
   295
}