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