src/Tools/VSCode/src/server.scala
author wenzelm
Tue Dec 20 22:24:16 2016 +0100 (2016-12-20)
changeset 64622 529bbb8977c7
parent 64618 c81bd30839a6
child 64623 83f012ce2567
permissions -rw-r--r--
more uniform rendering for Isabelle/jEdit and Isabelle/VSCode;
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@64605
    28
    var log_file: Option[Path] = None
wenzelm@64618
    29
    var text_length = Length.encoding(default_text_length)
wenzelm@64605
    30
    var dirs: List[Path] = Nil
wenzelm@64605
    31
    var logic = default_logic
wenzelm@64605
    32
    var modes: List[String] = Nil
wenzelm@64605
    33
    var options = Options.init()
wenzelm@64605
    34
wenzelm@64618
    35
    def text_length_choice: String =
wenzelm@64618
    36
      commas(Length.encodings.map(
wenzelm@64618
    37
        { case (a, _) => if (a == default_text_length) a + " (default)" else a }))
wenzelm@64618
    38
wenzelm@64605
    39
    val getopts = Getopts("""
wenzelm@64605
    40
Usage: isabelle vscode_server [OPTIONS]
wenzelm@64605
    41
wenzelm@64605
    42
  Options are:
wenzelm@64605
    43
    -L FILE      enable logging on FILE
wenzelm@64618
    44
    -T LENGTH    text length encoding: """ + text_length_choice + """
wenzelm@64605
    45
    -d DIR       include session directory
wenzelm@64605
    46
    -l NAME      logic session name (default ISABELLE_LOGIC=""" + quote(logic) + """)
wenzelm@64605
    47
    -m MODE      add print mode for output
wenzelm@64605
    48
    -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
wenzelm@64605
    49
wenzelm@64605
    50
  Run the VSCode Language Server protocol (JSON RPC) over stdin/stdout.
wenzelm@64605
    51
""",
wenzelm@64605
    52
      "L:" -> (arg => log_file = Some(Path.explode(arg))),
wenzelm@64618
    53
      "T:" -> (arg => Length.encoding(arg)),
wenzelm@64605
    54
      "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
wenzelm@64605
    55
      "l:" -> (arg => logic = arg),
wenzelm@64605
    56
      "m:" -> (arg => modes = arg :: modes),
wenzelm@64605
    57
      "o:" -> (arg => options = options + arg))
wenzelm@64605
    58
wenzelm@64605
    59
    val more_args = getopts(args)
wenzelm@64605
    60
    if (more_args.nonEmpty) getopts.usage()
wenzelm@64605
    61
wenzelm@64605
    62
    if (!Build.build(options = options, build_heap = true, no_build = true,
wenzelm@64605
    63
          dirs = dirs, sessions = List(logic)).ok)
wenzelm@64605
    64
      error("Missing logic image " + quote(logic))
wenzelm@64605
    65
wenzelm@64605
    66
    val channel = new Channel(System.in, System.out, log_file)
wenzelm@64618
    67
    val server = new Server(channel, options, text_length, logic, dirs, modes)
wenzelm@64605
    68
wenzelm@64605
    69
    // prevent spurious garbage on the main protocol channel
wenzelm@64605
    70
    val orig_out = System.out
wenzelm@64605
    71
    try {
wenzelm@64605
    72
      System.setOut(new PrintStream(new OutputStream { def write(n: Int) {} }))
wenzelm@64605
    73
      server.start()
wenzelm@64605
    74
    }
wenzelm@64605
    75
    finally { System.setOut(orig_out) }
wenzelm@64605
    76
  })
wenzelm@64605
    77
wenzelm@64605
    78
wenzelm@64605
    79
  /* server state */
wenzelm@64605
    80
wenzelm@64605
    81
  sealed case class State(
wenzelm@64605
    82
    session: Option[Session] = None,
wenzelm@64605
    83
    models: Map[String, Document_Model] = Map.empty)
wenzelm@64605
    84
}
wenzelm@64605
    85
wenzelm@64605
    86
class Server(
wenzelm@64605
    87
  channel: Channel,
wenzelm@64605
    88
  options: Options,
wenzelm@64618
    89
  text_length: Length = Length.encoding(Server.default_text_length),
wenzelm@64605
    90
  session_name: String = Server.default_logic,
wenzelm@64605
    91
  session_dirs: List[Path] = Nil,
wenzelm@64605
    92
  modes: List[String] = Nil)
wenzelm@64605
    93
{
wenzelm@64605
    94
  /* server state */
wenzelm@64605
    95
wenzelm@64605
    96
  private val state = Synchronized(Server.State())
wenzelm@64605
    97
wenzelm@64605
    98
  def session: Session = state.value.session getOrElse error("Session inactive")
wenzelm@64605
    99
  def resources: URI_Resources = session.resources.asInstanceOf[URI_Resources]
wenzelm@64605
   100
wenzelm@64605
   101
wenzelm@64605
   102
  /* init and exit */
wenzelm@64605
   103
wenzelm@64605
   104
  def initialize(reply: String => Unit)
wenzelm@64605
   105
  {
wenzelm@64605
   106
    val content = Build.session_content(options, false, session_dirs, session_name)
wenzelm@64605
   107
    val resources =
wenzelm@64605
   108
      new URI_Resources(content.loaded_theories, content.known_theories, content.syntax)
wenzelm@64605
   109
wenzelm@64605
   110
    val session =
wenzelm@64605
   111
      new Session(resources) {
wenzelm@64605
   112
        override def output_delay = options.seconds("editor_output_delay")
wenzelm@64605
   113
        override def prune_delay = options.seconds("editor_prune_delay")
wenzelm@64605
   114
        override def syslog_limit = options.int("editor_syslog_limit")
wenzelm@64605
   115
        override def reparse_limit = options.int("editor_reparse_limit")
wenzelm@64605
   116
      }
wenzelm@64605
   117
wenzelm@64605
   118
    var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64605
   119
    session_phase =
wenzelm@64605
   120
      Session.Consumer(getClass.getName) {
wenzelm@64605
   121
        case Session.Ready =>
wenzelm@64605
   122
          session.phase_changed -= session_phase
wenzelm@64605
   123
          session.update_options(options)
wenzelm@64605
   124
          reply("")
wenzelm@64605
   125
        case Session.Failed =>
wenzelm@64605
   126
          session.phase_changed -= session_phase
wenzelm@64605
   127
          reply("Prover startup failed")
wenzelm@64605
   128
        case _ =>
wenzelm@64605
   129
      }
wenzelm@64605
   130
    session.phase_changed += session_phase
wenzelm@64605
   131
wenzelm@64605
   132
    session.start(receiver =>
wenzelm@64605
   133
      Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
wenzelm@64605
   134
        modes = modes, receiver = receiver))
wenzelm@64605
   135
wenzelm@64605
   136
    state.change(_.copy(session = Some(session)))
wenzelm@64605
   137
  }
wenzelm@64605
   138
wenzelm@64605
   139
  def shutdown(reply: String => Unit)
wenzelm@64605
   140
  {
wenzelm@64605
   141
    state.change(st =>
wenzelm@64605
   142
      st.session match {
wenzelm@64605
   143
        case None => reply("Prover inactive"); st
wenzelm@64605
   144
        case Some(session) =>
wenzelm@64605
   145
          var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64605
   146
          session_phase =
wenzelm@64605
   147
            Session.Consumer(getClass.getName) {
wenzelm@64605
   148
              case Session.Inactive =>
wenzelm@64605
   149
                session.phase_changed -= session_phase
wenzelm@64605
   150
                reply("")
wenzelm@64605
   151
              case _ =>
wenzelm@64605
   152
            }
wenzelm@64605
   153
          session.phase_changed += session_phase
wenzelm@64605
   154
          session.stop()
wenzelm@64605
   155
          st.copy(session = None)
wenzelm@64605
   156
      })
wenzelm@64605
   157
  }
wenzelm@64605
   158
wenzelm@64605
   159
  def exit() { sys.exit(if (state.value.session.isDefined) 1 else 0) }
wenzelm@64605
   160
wenzelm@64605
   161
wenzelm@64605
   162
  /* document management */
wenzelm@64605
   163
wenzelm@64605
   164
  private val delay_flush =
wenzelm@64605
   165
    Standard_Thread.delay_last(options.seconds("editor_input_delay")) {
wenzelm@64605
   166
      state.change(st =>
wenzelm@64605
   167
        {
wenzelm@64605
   168
          val models = st.models
wenzelm@64605
   169
          val changed = (for { entry <- models.iterator if entry._2.changed } yield entry).toList
wenzelm@64605
   170
          val edits = for { (_, model) <- changed; edit <- model.node_edits } yield edit
wenzelm@64605
   171
          val models1 =
wenzelm@64605
   172
            (models /: changed)({ case (m, (uri, model)) => m + (uri -> model.unchanged) })
wenzelm@64605
   173
wenzelm@64605
   174
          session.update(Document.Blobs.empty, edits)
wenzelm@64605
   175
          st.copy(models = models1)
wenzelm@64605
   176
        })
wenzelm@64605
   177
    }
wenzelm@64605
   178
wenzelm@64605
   179
  def update_document(uri: String, text: String)
wenzelm@64605
   180
  {
wenzelm@64605
   181
    state.change(st =>
wenzelm@64605
   182
      {
wenzelm@64605
   183
        val node_name = resources.node_name(uri)
wenzelm@64605
   184
        val model = Document_Model(session, Line.Document(text), node_name)
wenzelm@64605
   185
        st.copy(models = st.models + (uri -> model))
wenzelm@64605
   186
      })
wenzelm@64605
   187
    delay_flush.invoke()
wenzelm@64605
   188
  }
wenzelm@64605
   189
wenzelm@64605
   190
wenzelm@64622
   191
  /* hover */
wenzelm@64605
   192
wenzelm@64605
   193
  def hover(uri: String, pos: Line.Position): Option[(Line.Range, List[String])] =
wenzelm@64605
   194
    for {
wenzelm@64605
   195
      model <- state.value.models.get(uri)
wenzelm@64622
   196
      rendering = model.rendering(options)
wenzelm@64618
   197
      offset <- model.doc.offset(pos, text_length)
wenzelm@64622
   198
      info <- rendering.tooltip(Text.Range(offset, offset + 1))
wenzelm@64605
   199
    } yield {
wenzelm@64618
   200
      val start = model.doc.position(info.range.start, text_length)
wenzelm@64618
   201
      val stop = model.doc.position(info.range.stop, text_length)
wenzelm@64622
   202
      val s = Pretty.string_of(info.info, margin = rendering.tooltip_margin)
wenzelm@64618
   203
      (Line.Range(start, stop), List("```\n" + s + "\n```"))
wenzelm@64605
   204
    }
wenzelm@64605
   205
wenzelm@64605
   206
wenzelm@64605
   207
  /* main loop */
wenzelm@64605
   208
wenzelm@64605
   209
  def start()
wenzelm@64605
   210
  {
wenzelm@64605
   211
    channel.log("\nServer started " + Date.now())
wenzelm@64605
   212
wenzelm@64605
   213
    def handle(json: JSON.T)
wenzelm@64605
   214
    {
wenzelm@64605
   215
      try {
wenzelm@64605
   216
        json match {
wenzelm@64605
   217
          case Protocol.Initialize(id) =>
wenzelm@64605
   218
            def initialize_reply(err: String)
wenzelm@64605
   219
            {
wenzelm@64605
   220
              channel.write(Protocol.Initialize.reply(id, err))
wenzelm@64605
   221
              if (err == "") {
wenzelm@64605
   222
                channel.write(Protocol.DisplayMessage(Protocol.MessageType.Info,
wenzelm@64605
   223
                  "Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")"))
wenzelm@64605
   224
              }
wenzelm@64605
   225
              else channel.write(Protocol.DisplayMessage(Protocol.MessageType.Error, err))
wenzelm@64605
   226
            }
wenzelm@64605
   227
            initialize(initialize_reply _)
wenzelm@64605
   228
          case Protocol.Shutdown(id) =>
wenzelm@64605
   229
            shutdown((error: String) => channel.write(Protocol.Shutdown.reply(id, error)))
wenzelm@64605
   230
          case Protocol.Exit =>
wenzelm@64605
   231
            exit()
wenzelm@64605
   232
          case Protocol.DidOpenTextDocument(uri, lang, version, text) =>
wenzelm@64605
   233
            update_document(uri, text)
wenzelm@64605
   234
          case Protocol.DidChangeTextDocument(uri, version, List(Protocol.TextDocumentContent(text))) =>
wenzelm@64605
   235
            update_document(uri, text)
wenzelm@64605
   236
          case Protocol.DidCloseTextDocument(uri) => channel.log("CLOSE " + uri)
wenzelm@64605
   237
          case Protocol.DidSaveTextDocument(uri) => channel.log("SAVE " + uri)
wenzelm@64605
   238
          case Protocol.Hover(id, uri, pos) =>
wenzelm@64605
   239
            channel.write(Protocol.Hover.reply(id, hover(uri, pos)))
wenzelm@64605
   240
          case _ => channel.log("### IGNORED")
wenzelm@64605
   241
        }
wenzelm@64605
   242
      }
wenzelm@64605
   243
      catch { case exn: Throwable => channel.log("*** ERROR: " + Exn.message(exn)) }
wenzelm@64605
   244
    }
wenzelm@64605
   245
wenzelm@64605
   246
    @tailrec def loop()
wenzelm@64605
   247
    {
wenzelm@64605
   248
      channel.read() match {
wenzelm@64605
   249
        case Some(json) =>
wenzelm@64605
   250
          json match {
wenzelm@64605
   251
            case bulk: List[_] => bulk.foreach(handle(_))
wenzelm@64605
   252
            case _ => handle(json)
wenzelm@64605
   253
          }
wenzelm@64605
   254
          loop()
wenzelm@64605
   255
        case None => channel.log("### TERMINATE")
wenzelm@64605
   256
      }
wenzelm@64605
   257
    }
wenzelm@64605
   258
    loop()
wenzelm@64605
   259
  }
wenzelm@64605
   260
}