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, File => JFile}
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 =>
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
37 def text_length_choice: String =
38 commas(Text.Length.encodings.map(
39 { case (a, _) => if (a == default_text_length) a + " (default)" else a }))
41 val getopts = Getopts("""
42 Usage: isabelle vscode_server [OPTIONS]
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
53 Run the VSCode Language Server protocol (JSON RPC) over stdin/stdout.
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))
63 val more_args = getopts(args)
64 if (more_args.nonEmpty) getopts.usage()
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)
70 // prevent spurious garbage on the main protocol channel
71 val orig_out = System.out
73 System.setOut(new PrintStream(new OutputStream { def write(n: Int) {} }))
76 finally { System.setOut(orig_out) }
79 case exn: Throwable =>
80 val channel = new Channel(System.in, System.out, No_Logger)
81 channel.error_message(Exn.message(exn))
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)
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]
103 def rendering_offset(node_pos: Line.Node_Position): Option[(VSCode_Rendering, Text.Offset)] =
105 model <- resources.get_model(node_pos.name)
106 rendering = model.rendering()
107 offset <- model.doc.offset(node_pos.pos)
108 } yield (rendering, offset)
111 /* input from client or file-system */
113 private val delay_input =
114 Standard_Thread.delay_last(options.seconds("vscode_input_delay"))
115 { resources.flush_input(session) }
117 private val delay_load =
118 Standard_Thread.delay_last(options.seconds("vscode_load_delay"))
119 { if (resources.resolve_dependencies(session)) delay_input.invoke() }
121 private val watcher =
122 File_Watcher(sync_documents(_), options.seconds("vscode_load_delay"))
124 private def sync_documents(changed: Set[JFile]): Unit =
125 if (resources.sync_models(changed)) delay_input.invoke()
127 private def update_document(uri: String, text: String)
129 resources.update_model(session, uri, text)
133 private def close_document(uri: String)
135 resources.close_model(uri) match {
137 model.register(watcher)
138 sync_documents(Set(model.file))
144 /* output to client */
146 private val delay_output: Standard_Thread.Delay =
147 Standard_Thread.delay_last(options.seconds("vscode_output_delay"))
149 if (session.current_state().stable_tip_version.isEmpty) delay_output.invoke()
150 else resources.flush_output(channel)
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()
162 Session.Consumer[Prover.Message](getClass.getName) {
163 case output: Prover.Output if output.is_syslog =>
164 channel.log_writeln(XML.content(output.message))
171 def init(id: Protocol.Id)
173 def reply(err: String)
175 channel.write(Protocol.Initialize.reply(id, err))
177 channel.writeln("Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")")
178 else channel.error_message(err)
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)
186 val start_msg = "Build started for Isabelle/" + session_name + " ..."
187 val fail_msg = "Session build failed -- prover process remains inactive!"
189 val progress = channel.make_progress(verbose = true)
190 progress.echo(start_msg); channel.writeln(start_msg)
192 if (!Build.build(options = options, progress = progress, build_heap = true,
193 system_mode = system_mode, dirs = session_dirs, sessions = List(session_name)).ok)
195 progress.echo(fail_msg); error(fail_msg)
199 val content = Build.session_content(options, false, session_dirs, session_name)
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()
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")
214 catch { case ERROR(msg) => reply(msg); None }
216 for (session <- try_session) {
217 var session_phase: Session.Consumer[Session.Phase] = null
219 Session.Consumer(getClass.getName) {
220 case Session.Ready =>
221 session.phase_changed -= session_phase
222 session.update_options(options)
224 case Session.Failed =>
225 session.phase_changed -= session_phase
226 reply("Prover startup failed")
229 session.phase_changed += session_phase
231 session.commands_changed += prover_output
232 session.all_messages += syslog
234 session.start(receiver =>
235 Isabelle_Process(options = options, logic = session_name, dirs = session_dirs,
236 modes = modes, receiver = receiver))
238 session_.change(_ => Some(session))
242 def shutdown(id: Protocol.Id)
244 def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
247 case Some(session) =>
248 var session_phase: Session.Consumer[Session.Phase] = null
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
258 session.phase_changed += session_phase
261 delay_output.revoke()
265 reply("Prover inactive")
272 sys.exit(if (session_.value.isDefined) 1 else 0)
278 def hover(id: Protocol.Id, node_pos: Line.Node_Position)
282 (rendering, offset) <- rendering_offset(node_pos)
283 info <- rendering.tooltip(Text.Range(offset, offset + 1))
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
290 channel.write(Protocol.Hover.reply(id, result))
294 /* goto definition */
296 def goto_definition(id: Protocol.Id, node_pos: Line.Node_Position)
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))
309 log("Server started " + Date.now())
311 def handle(json: JSON.T)
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) =>
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")
329 catch { case exn: Throwable => channel.log_error_message(Exn.message(exn)) }
334 channel.read() match {
337 case bulk: List[_] => bulk.foreach(handle(_))
338 case _ => handle(json)
341 case None => log("### TERMINATE")