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