src/Tools/VSCode/src/server.scala
author wenzelm
Mon Jan 09 20:26:59 2017 +0100 (2017-01-09)
changeset 64854 f5aa712e6250
parent 64830 9bc44bef99e6
child 64856 5e9bf964510a
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       var system_mode = false
    36 
    37       def text_length_choice: String =
    38         commas(Text.Length.encodings.map(
    39           { case (a, _) => if (a == default_text_length) a + " (default)" else a }))
    40 
    41       val getopts = Getopts("""
    42 Usage: isabelle vscode_server [OPTIONS]
    43 
    44   Options are:
    45     -L FILE      enable logging on FILE
    46     -T LENGTH    text length encoding: """ + text_length_choice + """
    47     -d DIR       include session directory
    48     -l NAME      logic session name (default ISABELLE_LOGIC=""" + quote(default_logic) + """)
    49     -m MODE      add print mode for output
    50     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
    51     -s           system build mode for session image
    52 
    53   Run the VSCode Language Server protocol (JSON RPC) over stdin/stdout.
    54 """,
    55         "L:" -> (arg => log_file = Some(Path.explode(File.standard_path(arg)))),
    56         "T:" -> (arg => Text.Length.encoding(arg)),
    57         "d:" -> (arg => dirs = dirs ::: List(Path.explode(File.standard_path(arg)))),
    58         "l:" -> (arg => logic = arg),
    59         "m:" -> (arg => modes = arg :: modes),
    60         "o:" -> (arg => options = options + arg),
    61         "s" -> (_ => system_mode = true))
    62 
    63       val more_args = getopts(args)
    64       if (more_args.nonEmpty) getopts.usage()
    65 
    66       val log = Logger.make(log_file)
    67       val channel = new Channel(System.in, System.out, log)
    68       val server = new Server(channel, options, text_length, logic, dirs, modes, system_mode, log)
    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, No_Logger)
    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   system_mode: Boolean = false,
    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(new JFile(node_pos.name))
   106       rendering = model.rendering()
   107       offset <- model.content.doc.offset(node_pos.pos)
   108     } yield (rendering, offset)
   109 
   110 
   111   /* input from client or file-system */
   112 
   113   private val delay_input: Standard_Thread.Delay =
   114     Standard_Thread.delay_last(options.seconds("vscode_input_delay"), channel.Error_Logger)
   115     { resources.flush_input(session) }
   116 
   117   private val delay_load: Standard_Thread.Delay =
   118     Standard_Thread.delay_last(options.seconds("vscode_load_delay"), channel.Error_Logger) {
   119       val (invoke_input, invoke_load) = resources.resolve_dependencies(session, watcher)
   120       if (invoke_input) delay_input.invoke()
   121       if (invoke_load) delay_load.invoke
   122     }
   123 
   124   private val watcher =
   125     File_Watcher(sync_documents(_), options.seconds("vscode_load_delay"))
   126 
   127   private def sync_documents(changed: Set[JFile]): Unit =
   128     if (resources.sync_models(changed)) delay_input.invoke()
   129 
   130   private def update_document(file: JFile, text: String)
   131   {
   132     resources.update_model(session, file, text)
   133     delay_input.invoke()
   134   }
   135 
   136   private def close_document(file: JFile)
   137   {
   138     resources.close_model(file) match {
   139       case Some(model) =>
   140         watcher.register_parent(file)
   141         sync_documents(Set(file))
   142       case None =>
   143     }
   144   }
   145 
   146 
   147   /* output to client */
   148 
   149   private val delay_output: Standard_Thread.Delay =
   150     Standard_Thread.delay_last(options.seconds("vscode_output_delay"), channel.Error_Logger)
   151     {
   152       if (session.current_state().stable_tip_version.isEmpty) delay_output.invoke()
   153       else resources.flush_output(channel)
   154     }
   155 
   156   private val prover_output =
   157     Session.Consumer[Session.Commands_Changed](getClass.getName) {
   158       case changed if changed.nodes.nonEmpty =>
   159         resources.update_output(changed.nodes.toList.map(resources.node_file(_)))
   160         delay_output.invoke()
   161       case _ =>
   162     }
   163 
   164   private val syslog =
   165     Session.Consumer[Prover.Message](getClass.getName) {
   166       case output: Prover.Output if output.is_syslog =>
   167         channel.log_writeln(XML.content(output.message))
   168       case _ =>
   169     }
   170 
   171 
   172   /* init and exit */
   173 
   174   def init(id: Protocol.Id)
   175   {
   176     def reply(err: String)
   177     {
   178       channel.write(Protocol.Initialize.reply(id, err))
   179       if (err == "")
   180         channel.writeln("Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")")
   181       else channel.error_message(err)
   182     }
   183 
   184     val try_session =
   185       try {
   186         if (!Build.build(options = options, build_heap = true, no_build = true,
   187               system_mode = system_mode, dirs = session_dirs, sessions = List(session_name)).ok)
   188         {
   189           val start_msg = "Build started for Isabelle/" + session_name + " ..."
   190           val fail_msg = "Session build failed -- prover process remains inactive!"
   191 
   192           val progress = channel.make_progress(verbose = true)
   193           progress.echo(start_msg); channel.writeln(start_msg)
   194 
   195           if (!Build.build(options = options, progress = progress, build_heap = true,
   196               system_mode = system_mode, dirs = session_dirs, sessions = List(session_name)).ok)
   197           {
   198             progress.echo(fail_msg); error(fail_msg)
   199           }
   200         }
   201 
   202         val resources =
   203           new VSCode_Resources(options, text_length,
   204             Build.session_content(options, false, session_dirs, session_name), log)
   205           {
   206             override def commit(change: Session.Change): Unit =
   207               if (change.deps_changed || undefined_blobs(change.version.nodes).nonEmpty)
   208                 delay_load.invoke()
   209           }
   210 
   211         Some(new Session(resources) {
   212           override def output_delay = options.seconds("editor_output_delay")
   213           override def prune_delay = options.seconds("editor_prune_delay")
   214           override def syslog_limit = options.int("editor_syslog_limit")
   215           override def reparse_limit = options.int("editor_reparse_limit")
   216         })
   217       }
   218       catch { case ERROR(msg) => reply(msg); None }
   219 
   220     for (session <- try_session) {
   221       var session_phase: Session.Consumer[Session.Phase] = null
   222       session_phase =
   223         Session.Consumer(getClass.getName) {
   224           case Session.Ready =>
   225             session.phase_changed -= session_phase
   226             session.update_options(options)
   227             reply("")
   228           case Session.Failed =>
   229             session.phase_changed -= session_phase
   230             reply("Prover startup failed")
   231           case _ =>
   232         }
   233       session.phase_changed += session_phase
   234 
   235       session.commands_changed += prover_output
   236       session.all_messages += syslog
   237 
   238       session.start(receiver =>
   239         Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
   240           modes = modes, receiver = receiver))
   241 
   242       session_.change(_ => Some(session))
   243     }
   244   }
   245 
   246   def shutdown(id: Protocol.Id)
   247   {
   248     def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
   249 
   250     session_.change({
   251       case Some(session) =>
   252         var session_phase: Session.Consumer[Session.Phase] = null
   253         session_phase =
   254           Session.Consumer(getClass.getName) {
   255             case Session.Inactive =>
   256               session.phase_changed -= session_phase
   257               session.commands_changed -= prover_output
   258               session.all_messages -= syslog
   259               reply("")
   260             case _ =>
   261           }
   262         session.phase_changed += session_phase
   263         session.stop()
   264         delay_input.revoke()
   265         delay_output.revoke()
   266         watcher.shutdown()
   267         None
   268       case None =>
   269         reply("Prover inactive")
   270         None
   271     })
   272   }
   273 
   274   def exit() {
   275     log("\n")
   276     sys.exit(if (session_.value.isDefined) 1 else 0)
   277   }
   278 
   279 
   280   /* hover */
   281 
   282   def hover(id: Protocol.Id, node_pos: Line.Node_Position)
   283   {
   284     val result =
   285       for {
   286         (rendering, offset) <- rendering_offset(node_pos)
   287         info <- rendering.tooltips(Text.Range(offset, offset + 1))
   288       } yield {
   289         val doc = rendering.model.content.doc
   290         val range = doc.range(info.range)
   291         val contents =
   292           info.info.map(tree => Pretty.string_of(List(tree), margin = rendering.tooltip_margin))
   293         (range, contents)
   294       }
   295     channel.write(Protocol.Hover.reply(id, result))
   296   }
   297 
   298 
   299   /* goto definition */
   300 
   301   def goto_definition(id: Protocol.Id, node_pos: Line.Node_Position)
   302   {
   303     val result =
   304       (for ((rendering, offset) <- rendering_offset(node_pos))
   305         yield rendering.hyperlinks(Text.Range(offset, offset + 1))) getOrElse Nil
   306     channel.write(Protocol.GotoDefinition.reply(id, result))
   307   }
   308 
   309 
   310   /* document highlights */
   311 
   312   def document_highlights(id: Protocol.Id, node_pos: Line.Node_Position)
   313   {
   314     val result =
   315       (for ((rendering, offset) <- rendering_offset(node_pos))
   316         yield {
   317           val doc = rendering.model.content.doc
   318           rendering.caret_focus_ranges(Text.Range(offset, offset + 1), doc.text_range)
   319             .map(r => Protocol.DocumentHighlight.text(doc.range(r)))
   320         }) getOrElse Nil
   321     channel.write(Protocol.DocumentHighlights.reply(id, result))
   322   }
   323 
   324 
   325   /* main loop */
   326 
   327   def start()
   328   {
   329     log("Server started " + Date.now())
   330 
   331     def handle(json: JSON.T)
   332     {
   333       try {
   334         json match {
   335           case Protocol.Initialize(id) => init(id)
   336           case Protocol.Shutdown(id) => shutdown(id)
   337           case Protocol.Exit(()) => exit()
   338           case Protocol.DidOpenTextDocument(file, lang, version, text) =>
   339             update_document(file, text)
   340           case Protocol.DidChangeTextDocument(file, version, List(Protocol.TextDocumentContent(text))) =>
   341             update_document(file, text)
   342           case Protocol.DidCloseTextDocument(file) =>
   343             close_document(file)
   344           case Protocol.Hover(id, node_pos) => hover(id, node_pos)
   345           case Protocol.GotoDefinition(id, node_pos) => goto_definition(id, node_pos)
   346           case Protocol.DocumentHighlights(id, node_pos) => document_highlights(id, node_pos)
   347           case _ => log("### IGNORED")
   348         }
   349       }
   350       catch { case exn: Throwable => channel.log_error_message(Exn.message(exn)) }
   351     }
   352 
   353     @tailrec def loop()
   354     {
   355       channel.read() match {
   356         case Some(json) =>
   357           json match {
   358             case bulk: List[_] => bulk.foreach(handle(_))
   359             case _ => handle(json)
   360           }
   361           loop()
   362         case None => log("### TERMINATE")
   363       }
   364     }
   365     loop()
   366   }
   367 }