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