src/Tools/VSCode/src/server.scala
author wenzelm
Tue Dec 20 22:32:04 2016 +0100 (2016-12-20)
changeset 64623 83f012ce2567
parent 64622 529bbb8977c7
child 64641 7b9196394b32
permissions -rw-r--r--
clarified module name;
     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 initialize(reply: String => Unit)
   105   {
   106     val content = Build.session_content(options, false, session_dirs, session_name)
   107     val resources =
   108       new VSCode_Resources(content.loaded_theories, content.known_theories, content.syntax)
   109 
   110     val session =
   111       new Session(resources) {
   112         override def output_delay = options.seconds("editor_output_delay")
   113         override def prune_delay = options.seconds("editor_prune_delay")
   114         override def syslog_limit = options.int("editor_syslog_limit")
   115         override def reparse_limit = options.int("editor_reparse_limit")
   116       }
   117 
   118     var session_phase: Session.Consumer[Session.Phase] = null
   119     session_phase =
   120       Session.Consumer(getClass.getName) {
   121         case Session.Ready =>
   122           session.phase_changed -= session_phase
   123           session.update_options(options)
   124           reply("")
   125         case Session.Failed =>
   126           session.phase_changed -= session_phase
   127           reply("Prover startup failed")
   128         case _ =>
   129       }
   130     session.phase_changed += session_phase
   131 
   132     session.start(receiver =>
   133       Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
   134         modes = modes, receiver = receiver))
   135 
   136     state.change(_.copy(session = Some(session)))
   137   }
   138 
   139   def shutdown(reply: String => Unit)
   140   {
   141     state.change(st =>
   142       st.session match {
   143         case None => reply("Prover inactive"); st
   144         case Some(session) =>
   145           var session_phase: Session.Consumer[Session.Phase] = null
   146           session_phase =
   147             Session.Consumer(getClass.getName) {
   148               case Session.Inactive =>
   149                 session.phase_changed -= session_phase
   150                 reply("")
   151               case _ =>
   152             }
   153           session.phase_changed += session_phase
   154           session.stop()
   155           st.copy(session = None)
   156       })
   157   }
   158 
   159   def exit() { sys.exit(if (state.value.session.isDefined) 1 else 0) }
   160 
   161 
   162   /* document management */
   163 
   164   private val delay_flush =
   165     Standard_Thread.delay_last(options.seconds("editor_input_delay")) {
   166       state.change(st =>
   167         {
   168           val models = st.models
   169           val changed = (for { entry <- models.iterator if entry._2.changed } yield entry).toList
   170           val edits = for { (_, model) <- changed; edit <- model.node_edits } yield edit
   171           val models1 =
   172             (models /: changed)({ case (m, (uri, model)) => m + (uri -> model.unchanged) })
   173 
   174           session.update(Document.Blobs.empty, edits)
   175           st.copy(models = models1)
   176         })
   177     }
   178 
   179   def update_document(uri: String, text: String)
   180   {
   181     state.change(st =>
   182       {
   183         val node_name = resources.node_name(uri)
   184         val model = Document_Model(session, Line.Document(text), node_name)
   185         st.copy(models = st.models + (uri -> model))
   186       })
   187     delay_flush.invoke()
   188   }
   189 
   190 
   191   /* hover */
   192 
   193   def hover(uri: String, pos: Line.Position): Option[(Line.Range, List[String])] =
   194     for {
   195       model <- state.value.models.get(uri)
   196       rendering = model.rendering(options)
   197       offset <- model.doc.offset(pos, text_length)
   198       info <- rendering.tooltip(Text.Range(offset, offset + 1))
   199     } yield {
   200       val start = model.doc.position(info.range.start, text_length)
   201       val stop = model.doc.position(info.range.stop, text_length)
   202       val s = Pretty.string_of(info.info, margin = rendering.tooltip_margin)
   203       (Line.Range(start, stop), List("```\n" + s + "\n```"))
   204     }
   205 
   206 
   207   /* main loop */
   208 
   209   def start()
   210   {
   211     channel.log("\nServer started " + Date.now())
   212 
   213     def handle(json: JSON.T)
   214     {
   215       try {
   216         json match {
   217           case Protocol.Initialize(id) =>
   218             def initialize_reply(err: String)
   219             {
   220               channel.write(Protocol.Initialize.reply(id, err))
   221               if (err == "") {
   222                 channel.write(Protocol.DisplayMessage(Protocol.MessageType.Info,
   223                   "Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")"))
   224               }
   225               else channel.write(Protocol.DisplayMessage(Protocol.MessageType.Error, err))
   226             }
   227             initialize(initialize_reply _)
   228           case Protocol.Shutdown(id) =>
   229             shutdown((error: String) => channel.write(Protocol.Shutdown.reply(id, error)))
   230           case Protocol.Exit =>
   231             exit()
   232           case Protocol.DidOpenTextDocument(uri, lang, version, text) =>
   233             update_document(uri, text)
   234           case Protocol.DidChangeTextDocument(uri, version, List(Protocol.TextDocumentContent(text))) =>
   235             update_document(uri, text)
   236           case Protocol.DidCloseTextDocument(uri) => channel.log("CLOSE " + uri)
   237           case Protocol.DidSaveTextDocument(uri) => channel.log("SAVE " + uri)
   238           case Protocol.Hover(id, uri, pos) =>
   239             channel.write(Protocol.Hover.reply(id, hover(uri, pos)))
   240           case _ => channel.log("### IGNORED")
   241         }
   242       }
   243       catch { case exn: Throwable => channel.log("*** ERROR: " + Exn.message(exn)) }
   244     }
   245 
   246     @tailrec def loop()
   247     {
   248       channel.read() match {
   249         case Some(json) =>
   250           json match {
   251             case bulk: List[_] => bulk.foreach(handle(_))
   252             case _ => handle(json)
   253           }
   254           loop()
   255         case None => channel.log("### TERMINATE")
   256       }
   257     }
   258     loop()
   259   }
   260 }