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