#! @file server.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the language server: it serves the language server protocol over #! the standard input and output until the client exits. Every `.sakura` file #! of the workspace folders is checked together with the standard library, #! using the text of the editor for the files open in it, and each file's notes #! are published as its diagnostics. Where several files declare `main`, each #! begins a program holding every file that does not, and one program is #! checked at a time: that of the file declaring `main` last opened, edited, or #! asked about. #! #! The server itself never checks anything. Each job, as checking the workspace #! or describing the name hovered, is worked out by a process of its own, so a #! fault while checking cannot stop the server, and one taking too long is #! stopped. The server keeps a process, the base, holding the files of the #! workspace parsed and checked. A job is worked out by a process the base #! starts as a copy of itself, which parses again what changed of the files as #! they are, checks again only what that affects, and answers. A check of the #! workspace checks the program whole, so its diagnostics are what #! `sakura check` would say. Once a check is answered, the base brings itself #! up to date with the files, so the next job has less to do. Where the base #! cannot answer, as where files are new or gone, it is made again, and where it #! still cannot, the job is worked out from nothing by a process of its own. #! Windows cannot copy a process, so there the base answers each job itself, as #! a process of its own still, and the server stops it and makes it again where #! a job faults or takes too long. import std::io; import std::json; import system; import sakura::analyzer; module sakura::server; #! How the server is run. pub struct server_options { pub var native: bool; #! Whether the workspace is checked for an executable. pub var system: strview; #! The operating system it is checked for, as `linux`. pub var libraries: span; #! The libraries, each as `NAME=DIR`, as `--lib` gives them, the standard library's among them. } #! The base: the process holding the workspace parsed and checked, which works #! out each job. struct base_link { var process: i64; #! The process, by its number on Linux and its handle on Windows, or 0 where there is none. var jobs: system::fd; #! Where jobs are written to it. var answers: system::fd; #! Where its answers are read. } #! The server. struct server { var options: server_options; var libraries: vector; #! The libraries, each as `NAME=DIR`, their directories made absolute. var core: string; #! `core`'s directory, beside the server's executable or above it, or empty. var platform: string; #! `system`'s directory, found as `core`'s is, or empty. var runtime: string; #! The runtime's directory, `runtime`, found as `core`'s is, or empty. var roots: vector; #! The paths of the workspace folders. var documents: vector; #! The documents open in the editor. var published: vector; #! The URIs last published with diagnostics. var documented: vector; #! The documentation of the last completion's items, which resolving one is answered from. var initialized: bool; var shutdown: bool; var dirty: bool; #! Whether something changed since the last check. var touched: string; #! The file last opened, edited, or asked about. var entry: string; #! The file declaring `main` the last job was answered from, or empty. var base: base_link; } #! Milliseconds without changes before the workspace is checked. const delay: i64 = 200; #! Milliseconds a job may take before it is stopped. const timeout: i64 = 30000; # Error codes of JSON-RPC and the protocol. const invalid_request: i64 = -32600; const method_not_found: i64 = -32601; const not_initialized: i64 = -32002; const request_failed: i64 = -32803; # Message types of `window/logMessage` and `window/showMessage`. const log_error: u32 = 1; const log_warning: u32 = 2; const log_info: u32 = 3; # What a process says of a job: answered, not finished, or that the files moved # on, so the base must be made again. A job says so by its exit status. const answer_ok: u64 = 0; const answer_fail: u64 = 1; const answer_stale: u64 = 2; const worker_stale: i32 = 3; #! Serves the language server protocol over the standard input and output #! until the client exits. #! @param given How the server is run. #! @returns The status to exit with: 0 where the client shut the server down #! before it exited, and 1 otherwise. pub def serve(given: server_options): i32 { system::ignore(system::signal::pipe); var running := make_server(&given); for each in given.libraries { val split := each.index_of(&'=') else { continue; }; var folder := spelled_folder(each.substr(split + 1, each.length - split - 1)) else { continue; }; running.libraries.append($"{each.substr(0, split)}={folder}"); } var input := string::new(nothing {}); var chunk: u8[65536]; while true { # Each whole message that has arrived is handled. while true { var body := string::new(nothing {}); break if !take_message(&mut input, &mut body); var parsed := json::parse(body.span) else (_) { running.log(log_warning, "A message from the client was not valid JSON."); continue; }; val going := running.handle(parsed.root); if !going { running.stop_base(); return running.shutdown ? 0 : 1; } } # Checking waits for a pause in the changes, so typing is not held up by it. val waited := wait_readable(system::fd::stdin, running.dirty ? delay : -1); if waited == -4 { continue; } if waited == 0 { running.dirty = false; running.check(); continue; } val size := system::fd::stdin.read((&mut chunk) as *mut u8, 65536); if size == -4 { continue; } if size <= 0 { running.stop_base(); return running.shutdown ? 0 : 1; } input.append(strview::over((&chunk) as *u8, size as u64)); } return 1; } #! Makes a server, which knows of no folder or document yet. #! @param given How the server is run, which is copied. #! @returns The server. def make_server(given: &server_options): server { return server { options = server_options { native = given.native, system = given.system, libraries = given.libraries }, libraries = vector::::new(), core = toolchain_folder("core"), platform = toolchain_folder("system"), runtime = toolchain_folder("runtime"), roots = vector::::new(), documents = vector::::new(), published = vector::::new(), documented = vector::::new(), touched = string::new(nothing {}), entry = string::new(nothing {}) }; } #! A library's directory, spelled as the paths of the documents are, which its #! files' paths are compared with: made absolute, and on Windows, which spells a #! file many ways, in the one way of its own. #! @param folder The directory, as given. #! @returns The directory, or `nothing` where it cannot be spelled so. def spelled_folder(folder: strview): maybe { var made: maybe = nothing {}; when os == linux { if path::parse(folder) is value(&found) { if io::absolute(found) is value(&whole) { made = string::from(whole.span, nothing {}); } } } when os == windows { made = canonical_path(folder); } return made; } #! Takes the body of the next whole message from what has arrived, if one has. #! A header without a length cannot be followed, so it is dropped. #! @param input What has arrived, which the message is taken from. #! @param body Where the body is written. #! @returns Whether a whole message had arrived. def take_message(input: &mut string, body: &mut string): bool { while true { val text := input.span; var end: u64 = 0; var found := false; while end + 4 <= text.length { if text.substr(end, 4) == "\r\n\r\n" { found = true; break; } end++; } return false if !found; val header := end + 4; var known := false; var length: u64 = 0; var line: u64 = 0; while line < end { var stop := line; while stop + 1 < end + 2 && text.substr(stop, 2) != "\r\n" { stop++; } val field := text.substr(line, stop - line); if field.length >= 15 && field.substr(0, 15).lower().span == "content-length:" { val number := field.substr(15, field.length - 15).trim(); length = 0; for i in 0..number.length { break if number[i] < '0' || number[i] > '9'; length = length * 10 + (number[i] - '0') as u64; } known = true; } line = stop + 2; } if !known { input = string::from(text.substr(header, text.length - header), nothing {}); continue; } return false if text.length < header + length; body = string::from(text.substr(header, length), nothing {}); input = string::from(text.substr(header + length, text.length - header - length), nothing {}); return true; } return false; } #! Sends a message to the client. #! @param this The server. #! @param body The message, as JSON. def server::send(&mut this, body: strview): void { var made := $"Content-Length: {body.length}\r\n\r\n"; made.append(body); if !put_all(system::fd::stdout, made.span) { system::exit(1); } } #! Begins a message to the client, as JSON-RPC 2.0 writes one, leaving it open #! for its members, which `send_written` closes. #! @returns The writer, within the message. def envelope(): json::writer { var made := message_writer(); made.begin_object(); made.member("jsonrpc"); made.text("2.0"); return made; } #! Begins the response to a request, whose outcome is written next, as a value. #! @param id The request's ID, as JSON. #! @param outcome The outcome's member: `result`, or `error`. #! @returns The writer, within the response. def response(id: strview, outcome: strview = "result"): json::writer { var made := envelope(); made.member("id"); made.raw(id); made.member(outcome); return made; } #! Begins a notification to the client, whose parameters are written next, as a #! value. #! @param method The method it notifies. #! @returns The writer, within the notification. def notification(method: strview): json::writer { var made := envelope(); made.member("method"); made.text(method); made.member("params"); return made; } #! Sends a message `response` or `notification` began, once what follows its #! beginning is written. #! @param this The server. #! @param body The message. def server::send_written(&mut this, body: &mut json::writer): void { body.end_object(); # A lossy writer given nothing but integers and text never fails. val text := body.finish() else (_) { return; }; this.send(text); } #! Tells the client something, which it logs, or shows its user. #! @param this The server. #! @param method `window/logMessage`, or `window/showMessage`. #! @param kind How grave it is. #! @param text What it says. def server::tell(&mut this, method: strview, kind: u32, text: strview): void { var body := notification(method); body.begin_object(); body.member("type"); body.unsigned(kind as u64); body.member("message"); body.text(text); body.end_object(); this.send_written(&mut body); } #! Logs a message in the client's log. #! @param this The server. #! @param kind How grave it is. #! @param text What it says. def server::log(&mut this, kind: u32, text: strview): void { this.tell("window/logMessage", kind, text); } #! Answers a request. #! @param this The server. #! @param id The request's ID, as JSON. #! @param result The answer, as JSON. def server::respond(&mut this, id: strview, result: strview): void { var body := response(id); body.raw(result); this.send_written(&mut body); } #! Answers a request with an error. #! @param this The server. #! @param id The request's ID, as JSON. #! @param code The error's code. #! @param message What it says. def server::respond_error(&mut this, id: strview, code: i64, message: strview): void { var body := response(id, "error"); body.begin_object(); body.member("code"); body.signed(code); body.member("message"); body.text(message); body.end_object(); this.send_written(&mut body); } #! The JSON a value is written as. #! @param value The value. #! @returns Its text. def json_text(value: &json::value): string { var writer := json::writer::new(); value.encode(&mut writer); val made := writer.finish() else (_) { return string::from("null", nothing {}); }; return string::from(made, nothing {}); } #! The text of a string member of an object, or empty text where it is none. #! @param value The object. #! @param key The member's name. #! @returns The text. def text_of(value: &json::value, key: strview): strview { val member := value.get(key) else { return ""; }; return member.as_text() else ""; } #! Whether an object has a string member of the name. #! @param value The object. #! @param key The member's name. #! @returns Whether it has. def has_text(value: &json::value, key: strview): bool { val member := value.get(key) else { return false; }; return member.kind == json::kind::text; } #! Keeps the file last opened, edited, or asked about, whose program the next #! job is answered from where it declares `main`. #! @param this The server. #! @param at The file's path, or empty. def server::touch(&mut this, at: strview): void { return if at.length == 0; this.touched = string::from(at, nothing {}); } #! The document open of a URI, or the count of documents. #! @param this The server. #! @param uri The URI. #! @returns Its index. def server::document_of(&this, uri: strview): u64 { for i in 0..this.documents.length { return i if this.documents[i].uri.span == uri; } return this.documents.length; } #! Adds a workspace folder, once. #! @param this The server. #! @param uri The folder's URI. def server::add_root(&mut this, uri: strview): void { var found := uri_path(uri) else { return; }; return if this.roots.span.contains(&found); this.roots.append(move(&mut found)); } #! Takes a workspace folder away. #! @param this The server. #! @param uri The folder's URI. def server::remove_root(&mut this, uri: strview): void { val found := uri_path(uri) else { return; }; val at := this.roots.span.index_of(&found) else { return; }; this.roots.remove_at(at); } #! Whether any of the libraries is the standard library's, or one of its #! modules', as `std::io`. #! @param this The server. #! @returns Whether one is. def server::reads_std(&this): bool { for &each in this.libraries { return true if each.span.starts_with("std=") || each.span.starts_with("std::"); } return false; } #! What the files of a check are gathered from now. #! @param this The server. #! @returns What they are gathered from. def server::gathering(&this): gathering { return gathering { core = this.core.span, system = this.platform.span, runtime = this.runtime.span, libraries = this.libraries.span, roots = &this.roots, documents = &this.documents }; } #! Handles a message, giving whether the server goes on: it stops once the #! client asks it to exit. #! @param this The server. #! @param message The message. #! @returns Whether it goes on. def server::handle(&mut this, message: json::value): bool { val method := text_of(&message, "method"); # A response to the server, which asks nothing. return true if method.length == 0; return false if method == "exit"; var params := message; if message.get("params") is some(given) { params = given; } if message.get("id") is some(found) { var id := json_text(&found); if method == "initialize" { this.initialize(id.span, ¶ms); } else if !this.initialized { this.respond_error(id.span, not_initialized, "The server was not initialized."); } else if this.shutdown { this.respond_error(id.span, invalid_request, "The server is shutting down."); } else if method == "shutdown" { this.shutdown = true; this.respond(id.span, "null"); } else if method == "textDocument/hover" { this.query(id.span, ¶ms, task::hover); } else if method == "textDocument/completion" { this.query(id.span, ¶ms, task::complete); } else if method == "completionItem/resolve" { this.resolve(id.span, ¶ms); } else if method == "textDocument/definition" { this.define(id.span, ¶ms); } else if method == "textDocument/references" { this.references(id.span, ¶ms); } else if method == "textDocument/prepareRename" { this.prepare_rename(id.span, ¶ms); } else if method == "textDocument/rename" { this.rename(id.span, ¶ms); } else if method == "textDocument/signatureHelp" { this.query(id.span, ¶ms, task::call); } else if method == "textDocument/semanticTokens/full" { this.colour(id.span, ¶ms); } else { this.respond_error(id.span, method_not_found, "The server does not support this request."); } return true; } return true if !this.initialized || this.shutdown; if method == "initialized" { # Making the base takes as long as a check, so it is made before it is # asked for, leaving the first check of a session to pay for nothing but # checking. this.start_base(); if this.core.length == 0 { this.log(log_warning, "No `core` folder is beside the server's executable or above it, so checks know nothing of the language's own types."); } if !this.reads_std() { this.log(log_warning, "The standard library was not found, so it is left out of checks. Put it beside the server's executable or above it, install it with `blossom install`, or give `--lib std=DIR` to `sakura lsp`."); } } if method == "initialized" || method == "textDocument/didSave" || method == "workspace/didChangeWatchedFiles" || method == "workspace/didChangeConfiguration" { this.dirty = true; } else if method == "textDocument/didOpen" { this.open(¶ms); } else if method == "textDocument/didChange" { this.change(¶ms); } else if method == "textDocument/didClose" { this.close(¶ms); } else if method == "workspace/didChangeWorkspaceFolders" { this.folders(¶ms); } return true; } #! Answers `initialize` with what the server can do, taking the workspace #! folders it is given. #! @param this The server. #! @param id The request's ID. #! @param params What it is given. def server::initialize(&mut this, id: strview, params: &json::value): void { if params.get("workspaceFolders") is some(folders) { for folder in folders.elements() { this.add_root(text_of(&folder, "uri")); } } else if has_text(params, "rootUri") { this.add_root(text_of(params, "rootUri")); } this.initialized = true; this.respond(id, """ {"capabilities":{ "positionEncoding":"utf-16", "textDocumentSync":{"openClose":true,"change":2,"save":{"includeText":false}}, "hoverProvider":true, "completionProvider":{"triggerCharacters":[".",":"],"resolveProvider":true}, "definitionProvider":true, "referencesProvider":true, "renameProvider":{"prepareProvider":true}, "signatureHelpProvider":{"triggerCharacters":["(",","],"retriggerCharacters":[",",")"]}, "semanticTokensProvider":{"legend":{"tokenTypes":[ "namespace","struct","interface","enum","type","typeParameter", "parameter","variable","property","enumMember","function","method", "keyword"], "tokenModifiers":["declaration","readonly"]},"full":true}, "workspace":{"workspaceFolders":{"supported":true,"changeNotifications":true}} }, "serverInfo":{"name":"sakura"}} """); } #! Takes a document the editor opened. #! @param this The server. #! @param params What `textDocument/didOpen` is given. def server::open(&mut this, params: &json::value): void { val item := params.get("textDocument") else { return; }; return if !has_text(&item, "uri") || !has_text(&item, "text"); val uri := text_of(&item, "uri"); var at := this.document_of(uri); if at == this.documents.length { var path := string::new(nothing {}); var made := uri_path(uri); if made is some(&mut found) { path = move(found); } this.documents.append(document { uri = string::from(uri, nothing {}), path = move(&mut path), text = string::new(nothing {}) }); } this.documents[at].text = string::from(text_of(&item, "text"), nothing {}); this.touch(this.documents[at].path.span); this.dirty = true; } #! The byte of a document's text a position of the protocol is at. #! @param text The text. #! @param position The position. #! @param out Where the byte is written. #! @returns Whether the value is a position. def position_at(text: strview, position: &json::value, out: &mut u32): bool { val at := position_in(position) else { return false; }; out = locate(text, at.line as u64, at.character as u64); return true; } #! The position of the protocol a value is. #! @param value The value, as `{"line":0,"character":4}`. #! @returns The position, or nothing where the value is none. def position_in(value: &json::value): maybe { val line := value.get("line") else { return nothing {}; }; val character := value.get("character") else { return nothing {}; }; val row := line.as_u64() else (_) { return nothing {}; }; val column := character.as_u64() else (_) { return nothing {}; }; return position { line = row as u32, character = column as u32 }; } #! Takes the changes the editor made to a document. A change is the text a range #! becomes, and they are made in turn, since each is given against the text the #! one before it left. A change without a range is the whole document. #! @param this The server. #! @param params What `textDocument/didChange` is given. def server::change(&mut this, params: &json::value): void { val item := params.get("textDocument") else { return; }; val at := this.document_of(text_of(&item, "uri")); return if at == this.documents.length; val changes := params.get("contentChanges") else { return; }; for each in changes.elements() { continue if !has_text(&each, "text"); val text := text_of(&each, "text"); if each.get("range") is some(range) { var from: u32 = 0; var to: u32 = 0; val start := range.get("start") else { continue; }; val end := range.get("end") else { continue; }; val old := this.documents[at].text.span; continue if !position_at(old, &start, &mut from) || !position_at(old, &end, &mut to); if to < from { to = from; } var edited := string::from(old.substr(0, from as u64), nothing {}); edited.append(text); edited.append(old.substr(to as u64, old.length - to as u64)); this.documents[at].text = move(&mut edited); } else { this.documents[at].text = string::from(text, nothing {}); } } this.touch(this.documents[at].path.span); this.dirty = true; } #! Lets go of a document the editor closed, which is read from disk again. #! @param this The server. #! @param params What `textDocument/didClose` is given. def server::close(&mut this, params: &json::value): void { val item := params.get("textDocument") else { return; }; val at := this.document_of(text_of(&item, "uri")); return if at == this.documents.length; this.documents.remove_at(at); this.dirty = true; } #! Takes the workspace folders the editor added and removed. #! @param this The server. #! @param params What `workspace/didChangeWorkspaceFolders` is given. def server::folders(&mut this, params: &json::value): void { val event := params.get("event") else { return; }; if event.get("removed") is some(removed) { for folder in removed.elements() { this.remove_root(text_of(&folder, "uri")); } } if event.get("added") is some(added) { for folder in added.elements() { this.add_root(text_of(&folder, "uri")); } } # The base gathers the files of the folders it was made with, so it is made # again with these. this.stop_base(); this.dirty = true; }