src/Tools/VSCode/src/server.scala
author wenzelm
Wed Dec 28 17:54:55 2016 +0100 (2016-12-28)
changeset 64687 04806ad1e43a
parent 64684 fe2c9c215b36
child 64690 599873de8b01
permissions -rw-r--r--
clarified protocol errors;
     1 /*  Title:      Tools/VSCode/src/server.scala
     2     Author:     Makarius
     3 
     4 Server for VS Code Language Server Protocol 2.0, see also
     5 https://github.com/Microsoft/language-server-protocol
     6 https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md
     7 */
     8 
     9 package isabelle.vscode
    10 
    11 
    12 import isabelle._
    13 
    14 import java.io.{PrintStream, OutputStream}
    15 
    16 import scala.annotation.tailrec
    17 
    18 
    19 object Server
    20 {
    21   /* Isabelle tool wrapper */
    22 
    23   private val default_text_length = "UTF-16"
    24   private lazy val default_logic = Isabelle_System.getenv("ISABELLE_LOGIC")
    25 
    26   val isabelle_tool = Isabelle_Tool("vscode_server", "VSCode Language Server for PIDE", args =>
    27   {
    28     try {
    29       var log_file: Option[Path] = None
    30       var text_length = Text.Length.encoding(default_text_length)
    31       var dirs: List[Path] = Nil
    32       var logic = default_logic
    33       var modes: List[String] = Nil
    34       var options = Options.init()
    35 
    36       def text_length_choice: String =
    37         commas(Text.Length.encodings.map(
    38           { case (a, _) => if (a == default_text_length) a + " (default)" else a }))
    39 
    40       val getopts = Getopts("""
    41 Usage: isabelle vscode_server [OPTIONS]
    42 
    43   Options are:
    44     -L FILE      enable logging on FILE
    45     -T LENGTH    text length encoding: """ + text_length_choice + """
    46     -d DIR       include session directory
    47     -l NAME      logic session name (default ISABELLE_LOGIC=""" + quote(logic) + """)
    48     -m MODE      add print mode for output
    49     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
    50 
    51   Run the VSCode Language Server protocol (JSON RPC) over stdin/stdout.
    52 """,
    53         "L:" -> (arg => log_file = Some(Path.explode(arg))),
    54         "T:" -> (arg => Text.Length.encoding(arg)),
    55         "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
    56         "l:" -> (arg => logic = arg),
    57         "m:" -> (arg => modes = arg :: modes),
    58         "o:" -> (arg => options = options + arg))
    59 
    60       val more_args = getopts(args)
    61       if (more_args.nonEmpty) getopts.usage()
    62 
    63       if (!Build.build(options = options, build_heap = true, no_build = true,
    64             dirs = dirs, sessions = List(logic)).ok)
    65         error("Missing logic image " + quote(logic))
    66 
    67       val channel = new Channel(System.in, System.out, log_file)
    68       val server = new Server(channel, options, text_length, logic, dirs, modes)
    69 
    70       // prevent spurious garbage on the main protocol channel
    71       val orig_out = System.out
    72       try {
    73         System.setOut(new PrintStream(new OutputStream { def write(n: Int) {} }))
    74         server.start()
    75       }
    76       finally { System.setOut(orig_out) }
    77     }
    78     catch {
    79       case exn: Throwable =>
    80         val channel = new Channel(System.in, System.out, None)
    81         channel.error_message(Exn.message(exn))
    82         throw(exn)
    83     }
    84   })
    85 
    86 
    87   /* server state */
    88 
    89   sealed case class State(
    90     session: Option[Session] = None,
    91     models: Map[String, Document_Model] = Map.empty,
    92     pending_output: Set[Document.Node.Name] = Set.empty)
    93 }
    94 
    95 class Server(
    96   channel: Channel,
    97   options: Options,
    98   text_length: Text.Length = Text.Length.encoding(Server.default_text_length),
    99   session_name: String = Server.default_logic,
   100   session_dirs: List[Path] = Nil,
   101   modes: List[String] = Nil)
   102 {
   103   /* server state */
   104 
   105   private val state = Synchronized(Server.State())
   106 
   107   def session: Session = state.value.session getOrElse error("Session inactive")
   108   def resources: VSCode_Resources = session.resources.asInstanceOf[VSCode_Resources]
   109 
   110   def rendering_offset(node_pos: Line.Node_Position): Option[(VSCode_Rendering, Text.Offset)] =
   111     for {
   112       model <- state.value.models.get(node_pos.name)
   113       rendering = model.rendering(options)
   114       offset <- model.doc.offset(node_pos.pos)
   115     } yield (rendering, offset)
   116 
   117 
   118   /* input from client */
   119 
   120   private val delay_input =
   121     Standard_Thread.delay_last(options.seconds("vscode_input_delay")) {
   122       state.change(st =>
   123         {
   124           val changed = (for { entry <- st.models.iterator if entry._2.changed } yield entry).toList
   125           val edits = for { (_, model) <- changed; edit <- model.node_edits(resources) } yield edit
   126           session.update(Document.Blobs.empty, edits)
   127           st.copy(
   128             models = (st.models /: changed)({ case (ms, (uri, m)) => ms + (uri -> m.unchanged) }))
   129         })
   130     }
   131 
   132   def update_document(uri: String, text: String)
   133   {
   134     state.change(st =>
   135       {
   136         val node_name = resources.node_name(uri)
   137         val model = Document_Model(session, Line.Document(text, text_length), node_name)
   138         st.copy(models = st.models + (uri -> model))
   139       })
   140     delay_input.invoke()
   141   }
   142 
   143 
   144   /* output to client */
   145 
   146   private val commands_changed =
   147     Session.Consumer[Session.Commands_Changed](getClass.getName) {
   148       case changed =>
   149         state.change(st => st.copy(pending_output = st.pending_output ++ changed.nodes))
   150         delay_output.invoke()
   151     }
   152 
   153   private val delay_output =
   154     Standard_Thread.delay_last(options.seconds("vscode_output_delay")) {
   155       state.change(st =>
   156         {
   157           val changed_iterator =
   158             for {
   159               node_name <- st.pending_output.iterator
   160               uri = node_name.node
   161               model <- st.models.get(uri)
   162               rendering = model.rendering(options)
   163               (diagnostics, model1) <- model.publish_diagnostics(rendering)
   164             } yield {
   165               channel.diagnostics(uri, rendering.diagnostics_output(diagnostics))
   166               (uri, model1)
   167             }
   168           st.copy(
   169             models = (st.models /: changed_iterator) { case (ms, (uri, m)) => ms + (uri -> m) },
   170             pending_output = Set.empty)
   171         })
   172     }
   173 
   174 
   175   /* init and exit */
   176 
   177   def init(id: Protocol.Id)
   178   {
   179     def reply(err: String)
   180     {
   181       channel.write(Protocol.Initialize.reply(id, err))
   182       if (err == "")
   183         channel.writeln("Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")")
   184       else channel.error_message(err)
   185     }
   186 
   187     val try_session =
   188       try {
   189         val content = Build.session_content(options, false, session_dirs, session_name)
   190         val resources =
   191           new VSCode_Resources(content.loaded_theories, content.known_theories, content.syntax)
   192 
   193         Some(new Session(resources) {
   194           override def output_delay = options.seconds("editor_output_delay")
   195           override def prune_delay = options.seconds("editor_prune_delay")
   196           override def syslog_limit = options.int("editor_syslog_limit")
   197           override def reparse_limit = options.int("editor_reparse_limit")
   198         })
   199       }
   200       catch { case ERROR(msg) => reply(msg); None }
   201 
   202     for (session <- try_session) {
   203       var session_phase: Session.Consumer[Session.Phase] = null
   204       session_phase =
   205         Session.Consumer(getClass.getName) {
   206           case Session.Ready =>
   207             session.phase_changed -= session_phase
   208             session.update_options(options)
   209             reply("")
   210           case Session.Failed =>
   211             session.phase_changed -= session_phase
   212             reply("Prover startup failed")
   213           case _ =>
   214         }
   215       session.phase_changed += session_phase
   216 
   217       session.commands_changed += commands_changed
   218 
   219       session.start(receiver =>
   220         Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
   221           modes = modes, receiver = receiver))
   222 
   223       state.change(_.copy(session = Some(session)))
   224     }
   225   }
   226 
   227   def shutdown(id: Protocol.Id)
   228   {
   229     def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
   230 
   231     state.change(st =>
   232       st.session match {
   233         case None => reply("Prover inactive"); st
   234         case Some(session) =>
   235           var session_phase: Session.Consumer[Session.Phase] = null
   236           session_phase =
   237             Session.Consumer(getClass.getName) {
   238               case Session.Inactive =>
   239                 session.phase_changed -= session_phase
   240                 reply("")
   241               case _ =>
   242             }
   243           session.phase_changed += session_phase
   244           session.commands_changed -= commands_changed
   245           session.stop()
   246           delay_input.revoke()
   247           delay_output.revoke()
   248           st.copy(session = None)
   249       })
   250   }
   251 
   252   def exit() {
   253     channel.log("\n")
   254     sys.exit(if (state.value.session.isDefined) 1 else 0)
   255   }
   256 
   257 
   258   /* hover */
   259 
   260   def hover(id: Protocol.Id, node_pos: Line.Node_Position)
   261   {
   262     val result =
   263       for {
   264         (rendering, offset) <- rendering_offset(node_pos)
   265         info <- rendering.tooltip(Text.Range(offset, offset + 1))
   266       } yield {
   267         val doc = rendering.model.doc
   268         val range = doc.range(info.range)
   269         val s = Pretty.string_of(info.info, margin = rendering.tooltip_margin)
   270         (range, List("```\n" + s + "\n```"))  // FIXME proper content format
   271       }
   272     channel.write(Protocol.Hover.reply(id, result))
   273   }
   274 
   275 
   276   /* goto definition */
   277 
   278   def goto_definition(id: Protocol.Id, node_pos: Line.Node_Position)
   279   {
   280     val result =
   281       (for ((rendering, offset) <- rendering_offset(node_pos))
   282         yield rendering.hyperlinks(Text.Range(offset, offset + 1))) getOrElse Nil
   283     channel.write(Protocol.GotoDefinition.reply(id, result))
   284   }
   285 
   286 
   287   /* main loop */
   288 
   289   def start()
   290   {
   291     channel.log("Server started " + Date.now())
   292 
   293     def handle(json: JSON.T)
   294     {
   295       try {
   296         json match {
   297           case Protocol.Initialize(id) => init(id)
   298           case Protocol.Shutdown(id) => shutdown(id)
   299           case Protocol.Exit(()) => exit()
   300           case Protocol.DidOpenTextDocument(uri, lang, version, text) =>
   301             update_document(uri, text)
   302           case Protocol.DidChangeTextDocument(uri, version, List(Protocol.TextDocumentContent(text))) =>
   303             update_document(uri, text)
   304           case Protocol.DidCloseTextDocument(uri) => channel.log("CLOSE " + uri)
   305           case Protocol.DidSaveTextDocument(uri) => channel.log("SAVE " + uri)
   306           case Protocol.Hover(id, node_pos) => hover(id, node_pos)
   307           case Protocol.GotoDefinition(id, node_pos) => goto_definition(id, node_pos)
   308           case _ => channel.log("### IGNORED")
   309         }
   310       }
   311       catch { case exn: Throwable => channel.log_error_message(Exn.message(exn)) }
   312     }
   313 
   314     @tailrec def loop()
   315     {
   316       channel.read() match {
   317         case Some(json) =>
   318           json match {
   319             case bulk: List[_] => bulk.foreach(handle(_))
   320             case _ => handle(json)
   321           }
   322           loop()
   323         case None => channel.log("### TERMINATE")
   324       }
   325     }
   326     loop()
   327   }
   328 }