src/Tools/VSCode/src/server.scala
author wenzelm
Wed Dec 28 19:45:09 2016 +0100 (2016-12-28)
changeset 64690 599873de8b01
parent 64687 04806ad1e43a
child 64691 db2b21a52f20
permissions -rw-r--r--
more uniform pending_input / pending_output;
explicit Document_Model.uri;
tuned;
     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 =
   162     Standard_Thread.delay_last(options.seconds("vscode_output_delay")) {
   163       state.change(st =>
   164         {
   165           val changed_iterator =
   166             for {
   167               node_name <- st.pending_output.iterator
   168               model <- st.models.get(node_name.node)
   169               rendering = model.rendering(options)
   170               (diagnostics, model1) <- model.publish_diagnostics(rendering)
   171             } yield {
   172               channel.diagnostics(model1.uri, rendering.diagnostics_output(diagnostics))
   173               model1
   174             }
   175           st.copy(
   176             models = (st.models /: changed_iterator) { case (ms, m) => ms + (m.uri -> m) },
   177             pending_output = Set.empty)
   178         })
   179     }
   180 
   181 
   182   /* init and exit */
   183 
   184   def init(id: Protocol.Id)
   185   {
   186     def reply(err: String)
   187     {
   188       channel.write(Protocol.Initialize.reply(id, err))
   189       if (err == "")
   190         channel.writeln("Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")")
   191       else channel.error_message(err)
   192     }
   193 
   194     val try_session =
   195       try {
   196         val content = Build.session_content(options, false, session_dirs, session_name)
   197         val resources =
   198           new VSCode_Resources(content.loaded_theories, content.known_theories, content.syntax)
   199 
   200         Some(new Session(resources) {
   201           override def output_delay = options.seconds("editor_output_delay")
   202           override def prune_delay = options.seconds("editor_prune_delay")
   203           override def syslog_limit = options.int("editor_syslog_limit")
   204           override def reparse_limit = options.int("editor_reparse_limit")
   205         })
   206       }
   207       catch { case ERROR(msg) => reply(msg); None }
   208 
   209     for (session <- try_session) {
   210       var session_phase: Session.Consumer[Session.Phase] = null
   211       session_phase =
   212         Session.Consumer(getClass.getName) {
   213           case Session.Ready =>
   214             session.phase_changed -= session_phase
   215             session.update_options(options)
   216             reply("")
   217           case Session.Failed =>
   218             session.phase_changed -= session_phase
   219             reply("Prover startup failed")
   220           case _ =>
   221         }
   222       session.phase_changed += session_phase
   223 
   224       session.commands_changed += commands_changed
   225 
   226       session.start(receiver =>
   227         Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
   228           modes = modes, receiver = receiver))
   229 
   230       state.change(_.copy(session = Some(session)))
   231     }
   232   }
   233 
   234   def shutdown(id: Protocol.Id)
   235   {
   236     def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
   237 
   238     state.change(st =>
   239       st.session match {
   240         case None => reply("Prover inactive"); st
   241         case Some(session) =>
   242           var session_phase: Session.Consumer[Session.Phase] = null
   243           session_phase =
   244             Session.Consumer(getClass.getName) {
   245               case Session.Inactive =>
   246                 session.phase_changed -= session_phase
   247                 reply("")
   248               case _ =>
   249             }
   250           session.phase_changed += session_phase
   251           session.commands_changed -= commands_changed
   252           session.stop()
   253           delay_input.revoke()
   254           delay_output.revoke()
   255           st.copy(session = None)
   256       })
   257   }
   258 
   259   def exit() {
   260     channel.log("\n")
   261     sys.exit(if (state.value.session.isDefined) 1 else 0)
   262   }
   263 
   264 
   265   /* hover */
   266 
   267   def hover(id: Protocol.Id, node_pos: Line.Node_Position)
   268   {
   269     val result =
   270       for {
   271         (rendering, offset) <- rendering_offset(node_pos)
   272         info <- rendering.tooltip(Text.Range(offset, offset + 1))
   273       } yield {
   274         val doc = rendering.model.doc
   275         val range = doc.range(info.range)
   276         val s = Pretty.string_of(info.info, margin = rendering.tooltip_margin)
   277         (range, List("```\n" + s + "\n```"))  // FIXME proper content format
   278       }
   279     channel.write(Protocol.Hover.reply(id, result))
   280   }
   281 
   282 
   283   /* goto definition */
   284 
   285   def goto_definition(id: Protocol.Id, node_pos: Line.Node_Position)
   286   {
   287     val result =
   288       (for ((rendering, offset) <- rendering_offset(node_pos))
   289         yield rendering.hyperlinks(Text.Range(offset, offset + 1))) getOrElse Nil
   290     channel.write(Protocol.GotoDefinition.reply(id, result))
   291   }
   292 
   293 
   294   /* main loop */
   295 
   296   def start()
   297   {
   298     channel.log("Server started " + Date.now())
   299 
   300     def handle(json: JSON.T)
   301     {
   302       try {
   303         json match {
   304           case Protocol.Initialize(id) => init(id)
   305           case Protocol.Shutdown(id) => shutdown(id)
   306           case Protocol.Exit(()) => exit()
   307           case Protocol.DidOpenTextDocument(uri, lang, version, text) =>
   308             update_document(uri, text)
   309           case Protocol.DidChangeTextDocument(uri, version, List(Protocol.TextDocumentContent(text))) =>
   310             update_document(uri, text)
   311           case Protocol.DidCloseTextDocument(uri) => channel.log("CLOSE " + uri)
   312           case Protocol.DidSaveTextDocument(uri) => channel.log("SAVE " + uri)
   313           case Protocol.Hover(id, node_pos) => hover(id, node_pos)
   314           case Protocol.GotoDefinition(id, node_pos) => goto_definition(id, node_pos)
   315           case _ => channel.log("### IGNORED")
   316         }
   317       }
   318       catch { case exn: Throwable => channel.log_error_message(Exn.message(exn)) }
   319     }
   320 
   321     @tailrec def loop()
   322     {
   323       channel.read() match {
   324         case Some(json) =>
   325           json match {
   326             case bulk: List[_] => bulk.foreach(handle(_))
   327             case _ => handle(json)
   328           }
   329           loop()
   330         case None => channel.log("### TERMINATE")
   331       }
   332     }
   333     loop()
   334   }
   335 }