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