#! @file requests.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains how the server answers what the client asks of the program: #! checking the workspace, whose notes it publishes as diagnostics, hovering, #! completing, the help shown while a call's arguments are written, colouring #! a file, going to where a name is declared, finding where it is written, and #! renaming it. import std::json; import system; import sakura::analyzer; module sakura::server; #! Publishes the diagnostics of a file. #! @param this The server. #! @param uri The file's URI. #! @param diagnostics Its diagnostics, as a JSON array. def server::publish(&mut this, uri: strview, diagnostics: strview): void { var body := notification("textDocument/publishDiagnostics"); body.begin_object(); body.member("uri"); body.text(uri); body.member("diagnostics"); body.raw(diagnostics); body.end_object(); this.send_written(&mut body); } #! Checks the program, then publishes the diagnostics of each file, clearing #! those of the files that no longer have any. Should checking with the files #! whose syntax has mistakes fail, they are left out, and the rest checked again. #! @param this The server. def server::check(&mut this): void { var asked := empty_job(); var output := string::new(nothing {}); if !this.run_job(&mut asked, &mut output) { asked.strict = true; output.clear(); # A check that did not finish keeps the diagnostics already shown. return if !this.fork_job(&asked, &mut output); this.answered(&asked, &mut output); } # Each line is the URI of a file, a space, and its diagnostics. Those of files # no longer reported are cleared first, so a client that takes two URIs for # one file, as the editor's spelling of it while it is open and its path's # once it is closed, keeps the diagnostics published last. var published := vector::::new(); var reported := vector::::new(); val space: u8 = ' '; for line in output.view().split('\n') { val at := line.index_of(&space) else { continue; }; published.append(string::from(line.substr(0, at), nothing {})); reported.append(line.substr(at + 1, line.length - at - 1)); } var cleared := move(&mut this.published); this.published = move(&mut published); for &each in cleared { if !this.published.view().contains(&each) { this.publish(each.view(), "[]"); } } for i in 0..this.published.length { this.publish(this.published[i].view(), reported[i]); } # A base stopped for being out of date is made again now, while nothing waits. this.start_base(); } #! The job a request about a position asks for: the file of its document, and #! its position. #! @param params What the request is given. #! @param kind The kind of job. #! @param out Where the job is written. #! @returns Whether the request gives a file and a position. def job_at(params: &json::value, kind: task, out: &mut job): bool { val item := params.get("textDocument") else { return false; }; val position := params.get("position") else { return false; }; val at := position_in(&position) else { return false; }; var path := uri_path(text_of(&item, "uri")) else { return false; }; out.task = kind; out.path = move(&mut path); out.line = at.line; out.character = at.character; return true; } #! Answers a hover, completion, or the help shown while a call's arguments are #! written, from the files as they are now. #! @param this The server. #! @param id The request's ID. #! @param params What it is given. #! @param kind What it asks. def server::query(&mut this, id: strview, params: &json::value, kind: task): void { val none_text: strview = kind == task::complete ? "{\"isIncomplete\":false,\"items\":[]}" : "null"; var asked := empty_job(); if !job_at(params, kind, &mut asked) { this.respond(id, none_text); return; } # Typing `:` only completes a path after `::`, not a type after `name:`. if params.get("context") is some(context) { if text_of(&context, "triggerCharacter") == ":" { val item := params.get("textDocument") else { return; }; val at := this.document_of(text_of(&item, "uri")); if at < this.documents.length { val text := this.documents[at].text.view(); val offset := locate(text, asked.line as u64, asked.character as u64); if offset < 2 || text[(offset - 2) as u64] != ':' { this.respond(id, none_text); return; } } } } var output := string::new(nothing {}); val done := this.run_job(&mut asked, &mut output); # The documentation follows the items, after a zero byte, and is kept here so # that resolving an item is answered without asking the program again. var items := output.length; if kind == task::complete { this.documented.clear(); val parts := output.view().split(0).to_vector(); items = parts[0].length; if done { # Each item's documentation ends in a zero, after which nothing is left. for i in 1..parts.length { continue if i + 1 == parts.length && parts[i].length == 0; this.documented.append(string::from(parts[i], nothing {})); } } } this.respond(id, done && items != 0 ? output.substr(0, items) : none_text); } #! Answers `textDocument/semanticTokens/full` with the names of the file, which #! the editor colours by what the checker made of them rather than by their #! shape. #! @param this The server. #! @param id The request's ID. #! @param params What it is given. def server::colour(&mut this, id: strview, params: &json::value): void { var asked := empty_job(); asked.task = task::tokens; var done := false; var output := string::new(nothing {}); if params.get("textDocument") is some(item) { if uri_path(text_of(&item, "uri")) is some(&found) { asked.path = string::copy_of(found); done = this.run_job(&mut asked, &mut output); } } this.respond(id, done && output.length != 0 ? output.view() : "{\"data\":[]}"); } #! Answers `completionItem/resolve` with the item as it was sent, and the #! documentation the server kept for it, which the list itself did not carry. #! @param this The server. #! @param id The request's ID. #! @param params The item. def server::resolve(&mut this, id: strview, params: &json::value): void { var which: u64 = 0xFFFFFFFFFFFFFFFF; if params.get("data") is some(data) { if data.as_u64() is value(found) { which = found; } } # What the client gave is written again as `json_text` writes it, which writes # a value it cannot write whole as `null`. var body := response(id); body.begin_object(); for member in params.members() { continue if member.key == "documentation"; var written := json_text(&member.value); body.member(member.key); body.raw(written.view()); } if which < this.documented.length && this.documented[which].length != 0 { body.member("documentation"); write_markdown(&mut body, this.documented[which].view()); } body.end_object(); this.send_written(&mut body); } #! Asks for a job about the name at the position a request gives, and gives #! what it wrote. #! @param this The server. #! @param params What the request is given. #! @param kind The kind of job. #! @param output Where what the job wrote is written. #! @returns Whether a name the checker resolved is there. def server::ask_name(&mut this, params: &json::value, kind: task, output: &mut string): bool { var asked := empty_job(); return false if !job_at(params, kind, &mut asked); return this.run_job(&mut asked, output) && output.length != 0; } #! Answers `textDocument/definition` with where what the name at the position #! is declared, or null for what has no declaration to go to, as a built-in #! type. #! @param this The server. #! @param id The request's ID. #! @param params What it is given. def server::define(&mut this, id: strview, params: &json::value): void { var output := string::new(nothing {}); if this.ask_name(params, task::name, &mut output) { var parsed := json::parse(output.view()) else (_) { this.respond(id, "null"); return; }; if parsed.root.get("declaration") is some(found) { var body := response(id); found.encode(&mut body); this.send_written(&mut body); return; } } this.respond(id, "null"); } #! Answers `textDocument/references` with everywhere what the name at the #! position refers to is written, leaving out its declaration where the request #! asks. #! @param this The server. #! @param id The request's ID. #! @param params What it is given. def server::references(&mut this, id: strview, params: &json::value): void { var declared := true; if params.get("context") is some(context) { if context.get("includeDeclaration") is some(include) { if include.as_bool() is value(given) { declared = given; } } } var output := string::new(nothing {}); if !this.ask_name(params, task::refer, &mut output) { this.respond(id, "null"); return; } var parsed := json::parse(output.view()) else (_) { this.respond(id, "null"); return; }; val named := parsed.root; var declaration := string::new(nothing {}); if named.get("declaration") is some(found) { declaration = json_text(&found); } var body := response(id); body.begin_array(); if named.get("locations") is some(locations) { for each in locations.elements() { if !declared { var written := json_text(&each); continue if written.view() == declaration.view(); } each.encode(&mut body); } } body.end_array(); this.send_written(&mut body); } #! Whether a rename may change a file: one within a workspace folder, or one open #! in the editor. The standard library is changed only where the workspace holds #! it, so renaming a name a program uses never rewrites the library it came from. #! @param this The server. #! @param at The file's path. #! @returns Whether it may. def server::editable(&this, at: strview): bool { return false if at.length == 0; for &root in this.roots { return true if at.starts_with(root.view()) && (at.length == root.length || at[root.length] == '/'); } for &each in this.documents { return true if each.path.view() == at; } return false; } #! Why the name a job found cannot be renamed, or empty text where it can. What #! the checker refuses is said first, then any place it is written that the #! workspace does not hold. #! @param this The server. #! @param named What the job wrote, or nothing where no name was found. #! @returns Why, or empty text. def server::refuse_rename(&this, named: maybe): string { var reason := string::new(nothing {}); val found := named else { reason.append("Nothing the checker resolved is named here."); return reason; }; val name := text_of(&found, "name"); if has_text(&found, "refusal") { reason.append("`"); reason.append(name); reason.append("` cannot be renamed. "); reason.append(text_of(&found, "refusal")); return reason; } # The declaration comes first, then each place it is written. var places := vector::::new(); if found.get("declaration") is some(declared) { places.append(declared); } if found.get("locations") is some(locations) { for each in locations.elements() { places.append(each); } } for &place in places { var at := string::new(nothing {}); var made := uri_path(text_of(&place, "uri")); if made is some(&mut found) { at = move(found); } if !this.editable(at.view()) { reason.append("`"); reason.append(name); reason.append("` cannot be renamed. It is written in "); reason.append(at.length != 0 ? at.view() : "a file the server cannot name"); reason.append(", which is outside the workspace."); return reason; } } return reason; } #! Asks for a job about the name at the position a request about renaming gives, #! and reads what it wrote, answering the request where the name cannot be #! renamed: with an error saying why, or null where what the job wrote is not #! JSON. #! @param this The server. #! @param id The request's ID. #! @param params What it is given. #! @param kind The kind of job. #! @param output Where what the job wrote is kept, which the document read #! views. #! @returns What the job wrote, read, or nothing where the request is answered. def server::ask_renamable(&mut this, id: strview, params: &json::value, kind: task, output: &mut string): maybe { val asked := this.ask_name(params, kind, output); var parsed := json::parse(asked ? output.view() : "null") else (_) { this.respond(id, "null"); return nothing {}; }; val named: maybe = asked && parsed.root.kind == json::kind::object ? parsed.root : nothing {}; var refusal := this.refuse_rename(named); if refusal.length != 0 { this.respond_error(id, request_failed, refusal.view()); return nothing {}; } return move(parsed); } #! Answers `textDocument/prepareRename` with the name at the position, or an #! error saying why it cannot be renamed, so the editor says so before asking #! for a name. #! @param this The server. #! @param id The request's ID. #! @param params What it is given. def server::prepare_rename(&mut this, id: strview, params: &json::value): void { var output := string::new(nothing {}); val parsed := this.ask_renamable(id, params, task::name, &mut output) else { return; }; val found := parsed.root; var body := response(id); body.begin_object(); body.member("range"); write_range_of(found.get("at"), &mut body); body.member("placeholder"); body.text(text_of(&found, "name")); body.end_object(); this.send_written(&mut body); } #! Writes the range of a location a job wrote, or `null` where there is none. #! @param location The location, or nothing. #! @param out Where it is written. def write_range_of(location: maybe, out: &mut json::writer): void { val found := location else { out.empty(); return; }; val range := found.get("range") else { out.empty(); return; }; range.encode(out); } #! Whether text is a name a declaration may be given: a letter or `_`, then #! letters, digits, and `_`, which is no keyword, nor a word the language keeps. #! @param text The text. #! @returns Whether it is. def is_name(text: strview): bool { return false if text.length == 0 || (text[0] >= '0' && text[0] <= '9'); for i in 0..text.length { return false if !is_word_byte(text[i]); } var names := names::new(); val id := names.intern(&text); return !names.is_keyword(id) && !names.is_reserved(id); } #! Answers `textDocument/rename` with an edit replacing everywhere the name at #! the position is written, declaration and all, grouped by file. #! @param this The server. #! @param id The request's ID. #! @param params What it is given. def server::rename(&mut this, id: strview, params: &json::value): void { val given := text_of(params, "newName"); if !is_name(given) { var reason := string::from("`", nothing {}); reason.append(given); reason.append("` is not a name: a name is a letter or `_`, then letters, digits, and `_`, and is not a keyword."); this.respond_error(id, request_failed, reason.view()); return; } var output := string::new(nothing {}); val parsed := this.ask_renamable(id, params, task::refer, &mut output) else { return; }; # Each file is given once, with every place in it, in the order they were found. val found := parsed.root; var locations := vector::::new(); if found.get("locations") is some(all) { for each in all.elements() { locations.append(each); } } var body := response(id); body.begin_object(); body.member("changes"); body.begin_object(); for i in 0..locations.length { val uri := text_of(&locations[i], "uri"); var seen := false; for j in 0..i { seen = seen || text_of(&locations[j], "uri") == uri; } continue if seen; body.member(uri); body.begin_array(); for j in i..locations.length { continue if text_of(&locations[j], "uri") != uri; body.begin_object(); body.member("range"); write_range_of(locations[j], &mut body); body.member("newText"); body.text(given); body.end_object(); } body.end_array(); } body.end_object(); body.end_object(); this.send_written(&mut body); this.warn_unresolved(&found, given); } #! A path as the editor's user is shown it: within a root of the workspace, #! relative to it. #! @param this The server. #! @param path The path. #! @returns The path shown. def server::shown_path(&this, path: strview): strview { var shown := path; for &root in this.roots { if shown.starts_with(root.view()) && shown.length > root.length && shown[root.length] == '/' { shown = shown.substr(root.length + 1, shown.length - root.length - 1); } } return shown; } #! Tells the editor where a name a rename changed is also written but was never #! resolved, as in a branch of `when` for another target, or in the runtime of #! executables where the target is not one, so what the rename left as it is #! can be looked at rather than found broken on that target. #! @param this The server. #! @param named What the job found. #! @param given The name given. def server::warn_unresolved(&mut this, named: &json::value, given: strview): void { val name := text_of(named, "name"); var places := string::new(nothing {}); var count := 0; if named.get("unresolved") is some(unresolved) { for place in unresolved.elements() { var at := uri_path(text_of(&place, "uri")) else { continue; }; val range := place.get("range") else { continue; }; val start := range.get("start") else { continue; }; val begins := position_in(&start) else { continue; }; val shown := this.shown_path(at.view()); if places.length != 0 { places.append(", "); } val text := $"{shown}:{begins.line + 1}:{begins.character + 1}"; places.append(text.view()); count++; } } return if count == 0; var message := string::from("Renamed `", nothing {}); message.append(name); message.append("` to `"); message.append(given); message.append("`, but `"); message.append(name); message.append("` is also written in code the checker does not read for this target, where it may be the same name, and there it was left as it is: "); message.append(places.view()); message.append("."); this.tell("window/showMessage", log_warning, message.view()); }