src/Tools/VSCode/src/server.scala
author wenzelm
Wed Dec 21 16:02:52 2016 +0100 (2016-12-21)
changeset 64642 c231206a84c8
parent 64641 7b9196394b32
child 64643 b755f6069ba2
permissions -rw-r--r--
display messages, according to regular Isabelle Output;
     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     var log_file: Option[Path] = None
    29     var text_length = Length.encoding(default_text_length)
    30     var dirs: List[Path] = Nil
    31     var logic = default_logic
    32     var modes: List[String] = Nil
    33     var options = Options.init()
    34 
    35     def text_length_choice: String =
    36       commas(Length.encodings.map(
    37         { case (a, _) => if (a == default_text_length) a + " (default)" else a }))
    38 
    39     val getopts = Getopts("""
    40 Usage: isabelle vscode_server [OPTIONS]
    41 
    42   Options are:
    43     -L FILE      enable logging on FILE
    44     -T LENGTH    text length encoding: """ + text_length_choice + """
    45     -d DIR       include session directory
    46     -l NAME      logic session name (default ISABELLE_LOGIC=""" + quote(logic) + """)
    47     -m MODE      add print mode for output
    48     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
    49 
    50   Run the VSCode Language Server protocol (JSON RPC) over stdin/stdout.
    51 """,
    52       "L:" -> (arg => log_file = Some(Path.explode(arg))),
    53       "T:" -> (arg => Length.encoding(arg)),
    54       "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
    55       "l:" -> (arg => logic = arg),
    56       "m:" -> (arg => modes = arg :: modes),
    57       "o:" -> (arg => options = options + arg))
    58 
    59     val more_args = getopts(args)
    60     if (more_args.nonEmpty) getopts.usage()
    61 
    62     if (!Build.build(options = options, build_heap = true, no_build = true,
    63           dirs = dirs, sessions = List(logic)).ok)
    64       error("Missing logic image " + quote(logic))
    65 
    66     val channel = new Channel(System.in, System.out, log_file)
    67     val server = new Server(channel, options, text_length, logic, dirs, modes)
    68 
    69     // prevent spurious garbage on the main protocol channel
    70     val orig_out = System.out
    71     try {
    72       System.setOut(new PrintStream(new OutputStream { def write(n: Int) {} }))
    73       server.start()
    74     }
    75     finally { System.setOut(orig_out) }
    76   })
    77 
    78 
    79   /* server state */
    80 
    81   sealed case class State(
    82     session: Option[Session] = None,
    83     models: Map[String, Document_Model] = Map.empty)
    84 }
    85 
    86 class Server(
    87   channel: Channel,
    88   options: Options,
    89   text_length: Length = Length.encoding(Server.default_text_length),
    90   session_name: String = Server.default_logic,
    91   session_dirs: List[Path] = Nil,
    92   modes: List[String] = Nil)
    93 {
    94   /* server state */
    95 
    96   private val state = Synchronized(Server.State())
    97 
    98   def session: Session = state.value.session getOrElse error("Session inactive")
    99   def resources: VSCode_Resources = session.resources.asInstanceOf[VSCode_Resources]
   100 
   101 
   102   /* init and exit */
   103 
   104   def init(id: Protocol.Id)
   105   {
   106     def reply(err: String)
   107     {
   108       channel.write(Protocol.Initialize.reply(id, err))
   109       if (err == "")
   110         channel.writeln("Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")")
   111       else channel.error_message(err)
   112     }
   113 
   114     // FIXME handle error
   115     val content = Build.session_content(options, false, session_dirs, session_name)
   116     val resources =
   117       new VSCode_Resources(content.loaded_theories, content.known_theories, content.syntax)
   118 
   119     val session =
   120       new Session(resources) {
   121         override def output_delay = options.seconds("editor_output_delay")
   122         override def prune_delay = options.seconds("editor_prune_delay")
   123         override def syslog_limit = options.int("editor_syslog_limit")
   124         override def reparse_limit = options.int("editor_reparse_limit")
   125       }
   126 
   127     var session_phase: Session.Consumer[Session.Phase] = null
   128     session_phase =
   129       Session.Consumer(getClass.getName) {
   130         case Session.Ready =>
   131           session.phase_changed -= session_phase
   132           session.update_options(options)
   133           reply("")
   134         case Session.Failed =>
   135           session.phase_changed -= session_phase
   136           reply("Prover startup failed")
   137         case _ =>
   138       }
   139     session.phase_changed += session_phase
   140 
   141     session.start(receiver =>
   142       Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
   143         modes = modes, receiver = receiver))
   144 
   145     state.change(_.copy(session = Some(session)))
   146   }
   147 
   148   def shutdown(id: Protocol.Id)
   149   {
   150     def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
   151 
   152     state.change(st =>
   153       st.session match {
   154         case None => reply("Prover inactive"); st
   155         case Some(session) =>
   156           var session_phase: Session.Consumer[Session.Phase] = null
   157           session_phase =
   158             Session.Consumer(getClass.getName) {
   159               case Session.Inactive =>
   160                 session.phase_changed -= session_phase
   161                 reply("")
   162               case _ =>
   163             }
   164           session.phase_changed += session_phase
   165           session.stop()
   166           st.copy(session = None)
   167       })
   168   }
   169 
   170   def exit() { sys.exit(if (state.value.session.isDefined) 1 else 0) }
   171 
   172 
   173   /* document management */
   174 
   175   private val delay_flush =
   176     Standard_Thread.delay_last(options.seconds("editor_input_delay")) {
   177       state.change(st =>
   178         {
   179           val models = st.models
   180           val changed = (for { entry <- models.iterator if entry._2.changed } yield entry).toList
   181           val edits = for { (_, model) <- changed; edit <- model.node_edits } yield edit
   182           val models1 =
   183             (models /: changed)({ case (m, (uri, model)) => m + (uri -> model.unchanged) })
   184 
   185           session.update(Document.Blobs.empty, edits)
   186           st.copy(models = models1)
   187         })
   188     }
   189 
   190   def update_document(uri: String, text: String)
   191   {
   192     state.change(st =>
   193       {
   194         val node_name = resources.node_name(uri)
   195         val model = Document_Model(session, Line.Document(text), node_name)
   196         st.copy(models = st.models + (uri -> model))
   197       })
   198     delay_flush.invoke()
   199   }
   200 
   201 
   202   /* hover */
   203 
   204   def hover(id: Protocol.Id, uri: String, pos: Line.Position)
   205   {
   206     val result =
   207       for {
   208         model <- state.value.models.get(uri)
   209         rendering = model.rendering(options)
   210         offset <- model.doc.offset(pos, text_length)
   211         info <- rendering.tooltip(Text.Range(offset, offset + 1))
   212       } yield {
   213         val start = model.doc.position(info.range.start, text_length)
   214         val stop = model.doc.position(info.range.stop, text_length)
   215         val s = Pretty.string_of(info.info, margin = rendering.tooltip_margin)
   216         (Line.Range(start, stop), List("```\n" + s + "\n```"))  // FIXME proper content format
   217       }
   218     channel.write(Protocol.Hover.reply(id, result))
   219   }
   220 
   221 
   222   /* main loop */
   223 
   224   def start()
   225   {
   226     channel.log("\nServer started " + Date.now())
   227 
   228     def handle(json: JSON.T)
   229     {
   230       try {
   231         json match {
   232           case Protocol.Initialize(id) => init(id)
   233           case Protocol.Shutdown(id) => shutdown(id)
   234           case Protocol.Exit => exit()
   235           case Protocol.DidOpenTextDocument(uri, lang, version, text) =>
   236             update_document(uri, text)
   237           case Protocol.DidChangeTextDocument(uri, version, List(Protocol.TextDocumentContent(text))) =>
   238             update_document(uri, text)
   239           case Protocol.DidCloseTextDocument(uri) => channel.log("CLOSE " + uri)
   240           case Protocol.DidSaveTextDocument(uri) => channel.log("SAVE " + uri)
   241           case Protocol.Hover(id, uri, pos) => hover(id, uri, pos)
   242           case _ => channel.log("### IGNORED")
   243         }
   244       }
   245       catch { case exn: Throwable => channel.log("*** ERROR: " + Exn.message(exn)) }
   246     }
   247 
   248     @tailrec def loop()
   249     {
   250       channel.read() match {
   251         case Some(json) =>
   252           json match {
   253             case bulk: List[_] => bulk.foreach(handle(_))
   254             case _ => handle(json)
   255           }
   256           loop()
   257         case None => channel.log("### TERMINATE")
   258       }
   259     }
   260     loop()
   261   }
   262 }