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