src/Tools/VSCode/src/server.scala
author wenzelm
Wed Dec 28 20:17:01 2016 +0100 (2016-12-28)
changeset 64692 ccf017e2f2b4
parent 64691 db2b21a52f20
child 64702 d95b9117cb5b
permissions -rw-r--r--
support for syslog messages;
clarified shutdown;
     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_input: Set[Document.Node.Name] = Set.empty,
    93     pending_output: Set[Document.Node.Name] = Set.empty)
    94 }
    95 
    96 class Server(
    97   channel: Channel,
    98   options: Options,
    99   text_length: Text.Length = Text.Length.encoding(Server.default_text_length),
   100   session_name: String = Server.default_logic,
   101   session_dirs: List[Path] = Nil,
   102   modes: List[String] = Nil)
   103 {
   104   /* server state */
   105 
   106   private val state = Synchronized(Server.State())
   107 
   108   def session: Session = state.value.session getOrElse error("Session inactive")
   109   def resources: VSCode_Resources = session.resources.asInstanceOf[VSCode_Resources]
   110 
   111   def rendering_offset(node_pos: Line.Node_Position): Option[(VSCode_Rendering, Text.Offset)] =
   112     for {
   113       model <- state.value.models.get(node_pos.name)
   114       rendering = model.rendering(options)
   115       offset <- model.doc.offset(node_pos.pos)
   116     } yield (rendering, offset)
   117 
   118 
   119   /* input from client */
   120 
   121   private val delay_input =
   122     Standard_Thread.delay_last(options.seconds("vscode_input_delay")) {
   123       state.change(st =>
   124         {
   125           val changed =
   126             (for {
   127               node_name <- st.pending_input.iterator
   128               model <- st.models.get(node_name.node)
   129               if model.changed } yield model).toList
   130           session.update(Document.Blobs.empty,
   131             for { model <- changed; edit <- model.node_edits(resources) } yield edit)
   132           st.copy(
   133             models = (st.models /: changed) { case (ms, m) => ms + (m.uri -> m.unchanged) },
   134             pending_input = Set.empty)
   135         })
   136     }
   137 
   138   def update_document(uri: String, text: String)
   139   {
   140     state.change(st =>
   141       {
   142         val node_name = resources.node_name(uri)
   143         val model = Document_Model(session, Line.Document(text, text_length), node_name)
   144         st.copy(
   145           models = st.models + (uri -> model),
   146           pending_input = st.pending_input + node_name)
   147       })
   148     delay_input.invoke()
   149   }
   150 
   151 
   152   /* output to client */
   153 
   154   private val commands_changed =
   155     Session.Consumer[Session.Commands_Changed](getClass.getName) {
   156       case changed =>
   157         state.change(st => st.copy(pending_output = st.pending_output ++ changed.nodes))
   158         delay_output.invoke()
   159     }
   160 
   161   private val delay_output: Standard_Thread.Delay =
   162     Standard_Thread.delay_last(options.seconds("vscode_output_delay")) {
   163       if (session.current_state().stable_tip_version.isEmpty) delay_output.invoke()
   164       else {
   165         state.change(st =>
   166           {
   167             val changed_iterator =
   168               for {
   169                 node_name <- st.pending_output.iterator
   170                 model <- st.models.get(node_name.node)
   171                 rendering = model.rendering(options)
   172                 (diagnostics, model1) <- model.publish_diagnostics(rendering)
   173               } yield {
   174                 channel.diagnostics(model1.uri, rendering.diagnostics_output(diagnostics))
   175                 model1
   176               }
   177             st.copy(
   178               models = (st.models /: changed_iterator) { case (ms, m) => ms + (m.uri -> m) },
   179               pending_output = Set.empty)
   180           }
   181         )
   182       }
   183     }
   184 
   185 
   186   /* syslog */
   187 
   188   private val all_messages =
   189     Session.Consumer[Prover.Message](getClass.getName) {
   190       case output: Prover.Output if output.is_syslog =>
   191         channel.log_writeln(XML.content(output.message))
   192       case _ =>
   193     }
   194 
   195 
   196   /* init and exit */
   197 
   198   def init(id: Protocol.Id)
   199   {
   200     def reply(err: String)
   201     {
   202       channel.write(Protocol.Initialize.reply(id, err))
   203       if (err == "")
   204         channel.writeln("Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")")
   205       else channel.error_message(err)
   206     }
   207 
   208     val try_session =
   209       try {
   210         val content = Build.session_content(options, false, session_dirs, session_name)
   211         val resources =
   212           new VSCode_Resources(content.loaded_theories, content.known_theories, content.syntax)
   213 
   214         Some(new Session(resources) {
   215           override def output_delay = options.seconds("editor_output_delay")
   216           override def prune_delay = options.seconds("editor_prune_delay")
   217           override def syslog_limit = options.int("editor_syslog_limit")
   218           override def reparse_limit = options.int("editor_reparse_limit")
   219         })
   220       }
   221       catch { case ERROR(msg) => reply(msg); None }
   222 
   223     for (session <- try_session) {
   224       var session_phase: Session.Consumer[Session.Phase] = null
   225       session_phase =
   226         Session.Consumer(getClass.getName) {
   227           case Session.Ready =>
   228             session.phase_changed -= session_phase
   229             session.update_options(options)
   230             reply("")
   231           case Session.Failed =>
   232             session.phase_changed -= session_phase
   233             reply("Prover startup failed")
   234           case _ =>
   235         }
   236       session.phase_changed += session_phase
   237 
   238       session.commands_changed += commands_changed
   239       session.all_messages += all_messages
   240 
   241       session.start(receiver =>
   242         Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
   243           modes = modes, receiver = receiver))
   244 
   245       state.change(_.copy(session = Some(session)))
   246     }
   247   }
   248 
   249   def shutdown(id: Protocol.Id)
   250   {
   251     def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
   252 
   253     state.change(st =>
   254       st.session match {
   255         case None => reply("Prover inactive"); st
   256         case Some(session) =>
   257           var session_phase: Session.Consumer[Session.Phase] = null
   258           session_phase =
   259             Session.Consumer(getClass.getName) {
   260               case Session.Inactive =>
   261                 session.phase_changed -= session_phase
   262                 session.commands_changed -= commands_changed
   263                 session.all_messages -= all_messages
   264                 reply("")
   265               case _ =>
   266             }
   267           session.phase_changed += session_phase
   268           session.stop()
   269           delay_input.revoke()
   270           delay_output.revoke()
   271           st.copy(session = None)
   272       })
   273   }
   274 
   275   def exit() {
   276     channel.log("\n")
   277     sys.exit(if (state.value.session.isDefined) 1 else 0)
   278   }
   279 
   280 
   281   /* hover */
   282 
   283   def hover(id: Protocol.Id, node_pos: Line.Node_Position)
   284   {
   285     val result =
   286       for {
   287         (rendering, offset) <- rendering_offset(node_pos)
   288         info <- rendering.tooltip(Text.Range(offset, offset + 1))
   289       } yield {
   290         val doc = rendering.model.doc
   291         val range = doc.range(info.range)
   292         val s = Pretty.string_of(info.info, margin = rendering.tooltip_margin)
   293         (range, List("```\n" + s + "\n```"))  // FIXME proper content format
   294       }
   295     channel.write(Protocol.Hover.reply(id, result))
   296   }
   297 
   298 
   299   /* goto definition */
   300 
   301   def goto_definition(id: Protocol.Id, node_pos: Line.Node_Position)
   302   {
   303     val result =
   304       (for ((rendering, offset) <- rendering_offset(node_pos))
   305         yield rendering.hyperlinks(Text.Range(offset, offset + 1))) getOrElse Nil
   306     channel.write(Protocol.GotoDefinition.reply(id, result))
   307   }
   308 
   309 
   310   /* main loop */
   311 
   312   def start()
   313   {
   314     channel.log("Server started " + Date.now())
   315 
   316     def handle(json: JSON.T)
   317     {
   318       try {
   319         json match {
   320           case Protocol.Initialize(id) => init(id)
   321           case Protocol.Shutdown(id) => shutdown(id)
   322           case Protocol.Exit(()) => exit()
   323           case Protocol.DidOpenTextDocument(uri, lang, version, text) =>
   324             update_document(uri, text)
   325           case Protocol.DidChangeTextDocument(uri, version, List(Protocol.TextDocumentContent(text))) =>
   326             update_document(uri, text)
   327           case Protocol.DidCloseTextDocument(uri) => channel.log("CLOSE " + uri)
   328           case Protocol.DidSaveTextDocument(uri) => channel.log("SAVE " + uri)
   329           case Protocol.Hover(id, node_pos) => hover(id, node_pos)
   330           case Protocol.GotoDefinition(id, node_pos) => goto_definition(id, node_pos)
   331           case _ => channel.log("### IGNORED")
   332         }
   333       }
   334       catch { case exn: Throwable => channel.log_error_message(Exn.message(exn)) }
   335     }
   336 
   337     @tailrec def loop()
   338     {
   339       channel.read() match {
   340         case Some(json) =>
   341           json match {
   342             case bulk: List[_] => bulk.foreach(handle(_))
   343             case _ => handle(json)
   344           }
   345           loop()
   346         case None => channel.log("### TERMINATE")
   347       }
   348     }
   349     loop()
   350   }
   351 }