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