1 /* Title: Tools/VSCode/src/server.scala
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
9 package isabelle.vscode
14 import java.io.{PrintStream, OutputStream}
16 import scala.annotation.tailrec
21 /* Isabelle tool wrapper */
23 private val default_text_length = "UTF-16"
24 private lazy val default_logic = Isabelle_System.getenv("ISABELLE_LOGIC")
26 val isabelle_tool = Isabelle_Tool("vscode_server", "VSCode Language Server for PIDE", args =>
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()
35 def text_length_choice: String =
36 commas(Length.encodings.map(
37 { case (a, _) => if (a == default_text_length) a + " (default)" else a }))
39 val getopts = Getopts("""
40 Usage: isabelle vscode_server [OPTIONS]
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)
50 Run the VSCode Language Server protocol (JSON RPC) over stdin/stdout.
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))
59 val more_args = getopts(args)
60 if (more_args.nonEmpty) getopts.usage()
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))
66 val channel = new Channel(System.in, System.out, log_file)
67 val server = new Server(channel, options, text_length, logic, dirs, modes)
69 // prevent spurious garbage on the main protocol channel
70 val orig_out = System.out
72 System.setOut(new PrintStream(new OutputStream { def write(n: Int) {} }))
75 finally { System.setOut(orig_out) }
81 sealed case class State(
82 session: Option[Session] = None,
83 models: Map[String, Document_Model] = Map.empty)
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)
96 private val state = Synchronized(Server.State())
98 def session: Session = state.value.session getOrElse error("Session inactive")
99 def resources: VSCode_Resources = session.resources.asInstanceOf[VSCode_Resources]
104 def init(id: Protocol.Id)
106 def reply(err: String)
108 channel.write(Protocol.Initialize.reply(id, err))
110 channel.writeln("Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")")
111 else channel.error_message(err)
114 // FIXME handle error
115 val content = Build.session_content(options, false, session_dirs, session_name)
117 new VSCode_Resources(content.loaded_theories, content.known_theories, content.syntax)
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")
127 var session_phase: Session.Consumer[Session.Phase] = null
129 Session.Consumer(getClass.getName) {
130 case Session.Ready =>
131 session.phase_changed -= session_phase
132 session.update_options(options)
134 case Session.Failed =>
135 session.phase_changed -= session_phase
136 reply("Prover startup failed")
139 session.phase_changed += session_phase
141 session.start(receiver =>
142 Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
143 modes = modes, receiver = receiver))
145 state.change(_.copy(session = Some(session)))
148 def shutdown(id: Protocol.Id)
150 def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
154 case None => reply("Prover inactive"); st
155 case Some(session) =>
156 var session_phase: Session.Consumer[Session.Phase] = null
158 Session.Consumer(getClass.getName) {
159 case Session.Inactive =>
160 session.phase_changed -= session_phase
164 session.phase_changed += session_phase
166 st.copy(session = None)
170 def exit() { sys.exit(if (state.value.session.isDefined) 1 else 0) }
173 /* document management */
175 private val delay_flush =
176 Standard_Thread.delay_last(options.seconds("editor_input_delay")) {
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
183 (models /: changed)({ case (m, (uri, model)) => m + (uri -> model.unchanged) })
185 session.update(Document.Blobs.empty, edits)
186 st.copy(models = models1)
190 def update_document(uri: String, text: String)
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))
204 def hover(id: Protocol.Id, uri: String, pos: Line.Position)
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))
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
218 channel.write(Protocol.Hover.reply(id, result))
226 channel.log("\nServer started " + Date.now())
228 def handle(json: JSON.T)
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")
245 catch { case exn: Throwable => channel.log("*** ERROR: " + Exn.message(exn)) }
250 channel.read() match {
253 case bulk: List[_] => bulk.foreach(handle(_))
254 case _ => handle(json)
257 case None => channel.log("### TERMINATE")