bootstrap

Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-11-25 02:11:19 +03:00
commit ca04975d54
62 files changed
+3381

No files matched your search

+131
View File
@@ -0,0 +1,131 @@
#include <vls/Framing.hpp>
#include <charconv>
#include <istream>
#include <limits>
#include <ostream>
namespace vls {
namespace {
std::string_view trim(std::string_view text) {
const auto first = text.find_first_not_of(" \t");
if (first == std::string_view::npos)
return {};
return text.substr(first, text.find_last_not_of(" \t") - first + 1);
}
std::string lower(std::string_view text) {
std::string result{text};
for (char &c : result)
if (c >= 'A' && c <= 'Z')
c = static_cast<char>(c + ('a' - 'A'));
return result;
}
bool supported_content_type(std::string_view text) {
auto separator = text.find(';');
const auto media = lower(trim(text.substr(0, separator)));
if (media != "application/vscode-jsonrpc" && media != "application/json")
return false;
bool seen_charset = false;
while (separator != std::string_view::npos) {
text.remove_prefix(separator + 1);
separator = text.find(';');
const auto parameter = trim(text.substr(0, separator));
const auto equals = parameter.find('=');
if (equals == std::string_view::npos)
return false;
if (lower(trim(parameter.substr(0, equals))) == "charset") {
if (seen_charset)
return false;
seen_charset = true;
auto encoding = trim(parameter.substr(equals + 1));
if (encoding.size() >= 2 && encoding.front() == '"' && encoding.back() == '"')
encoding = encoding.substr(1, encoding.size() - 2);
const auto name = lower(encoding);
if (name != "utf-8" && name != "utf8")
return false;
}
}
return true;
}
} // namespace
std::expected<std::optional<std::string>, std::string> read_frame(std::istream &input,
FrameLimits limits) {
std::string header;
while (!header.ends_with("\r\n\r\n")) {
const auto next = input.get();
if (next == std::char_traits<char>::eof()) {
if (input.bad() || !input.eof())
return std::unexpected{"input stream failure"};
if (header.empty())
return std::optional<std::string>{};
return std::unexpected{"truncated frame header"};
}
if (header.size() >= limits.header_bytes)
return std::unexpected{"frame header exceeds byte limit"};
const char c = static_cast<char>(next);
if ((c == '\n' && (header.empty() || header.back() != '\r')) ||
(!header.empty() && header.back() == '\r' && c != '\n'))
return std::unexpected{"frame headers require CRLF"};
if (c != '\r' && c != '\n' && c != '\t' && (c < 0x20 || c > 0x7e))
return std::unexpected{"non-ASCII frame header"};
header.push_back(c);
}
std::optional<std::size_t> length;
bool seen_type = false;
std::string_view remaining{header};
while (!remaining.starts_with("\r\n")) {
const auto end = remaining.find("\r\n");
const auto line = remaining.substr(0, end);
const auto colon = line.find(':');
if (colon == std::string_view::npos || colon == 0)
return std::unexpected{"invalid frame header field"};
const auto name = line.substr(0, colon);
if (name.find_first_of(" \t") != std::string_view::npos)
return std::unexpected{"invalid frame header name"};
const auto value = trim(line.substr(colon + 1));
if (lower(name) == "content-length") {
if (length)
return std::unexpected{"duplicate Content-Length"};
if (value.empty() || value.find_first_not_of("0123456789") != std::string_view::npos)
return std::unexpected{"invalid Content-Length"};
std::size_t parsed{};
const auto result = std::from_chars(value.data(), value.data() + value.size(), parsed);
if (result.ec != std::errc{} || result.ptr != value.data() + value.size())
return std::unexpected{"Content-Length overflow"};
if (parsed > limits.body_bytes || parsed > std::numeric_limits<std::streamsize>::max())
return std::unexpected{"frame body exceeds byte limit"};
length = parsed;
} else if (lower(name) == "content-type") {
if (seen_type || !supported_content_type(value))
return std::unexpected{"duplicate or unsupported Content-Type/charset"};
seen_type = true;
}
remaining.remove_prefix(end + 2);
}
if (!length)
return std::unexpected{"missing Content-Length"};
std::string body(*length, '\0');
input.read(body.data(), static_cast<std::streamsize>(*length));
if (!input)
return std::unexpected{"truncated frame body or input failure"};
return std::optional{std::move(body)};
}
std::expected<void, std::string> write_frame(std::ostream &output, std::string_view body) {
if (body.size() > static_cast<std::size_t>(std::numeric_limits<std::streamsize>::max()))
return std::unexpected{"output frame exceeds stream limit"};
output << "Content-Length: " << body.size() << "\r\n\r\n";
output.write(body.data(), static_cast<std::streamsize>(body.size()));
output.flush();
if (!output)
return std::unexpected{"output stream failure"};
return {};
}
} // namespace vls
+99
View File
@@ -0,0 +1,99 @@
#include <vls/Json.hpp>
#include <Void/Unicode/Utf.hpp>
#include <cmath>
#include <limits>
#include <type_traits>
#include <utility>
namespace vls {
std::expected<Json, std::string> parse_json(std::string_view text, std::size_t maximum_depth) {
if (!Void::Unicode::validate_utf8(text))
return std::unexpected{"invalid UTF-8"};
// Bound structural nesting before calling a recursive dependency parser.
// This scan does not parse JSON or numbers: StrictJson owns that grammar,
// including escape validation and rejection of unpaired surrogate escapes.
std::size_t depth{};
bool in_string = false;
bool escaped = false;
for (const char c : text) {
if (in_string) {
if (escaped)
escaped = false;
else if (c == '\\')
escaped = true;
else if (c == '"')
in_string = false;
} else if (c == '"') {
in_string = true;
} else if (c == '{' || c == '[') {
if (depth >= maximum_depth)
return std::unexpected{"JSON nesting exceeds depth limit"};
++depth;
} else if ((c == '}' || c == ']') && depth > 0) {
--depth;
}
}
auto parsed = Void::Json::Strict::parse(text, maximum_depth);
if (!parsed)
return std::unexpected{parsed.error().message};
return std::move(*parsed);
}
std::expected<RequestId, std::string> request_id(const Json &value) {
// LSP integer IDs are constrained by value, not by JSON number spelling.
// Preserve the value only after checking integrality and the signed range.
return std::visit(
[](const auto &item) -> std::expected<RequestId, std::string> {
using T = std::remove_cvref_t<decltype(item)>;
if constexpr (std::is_same_v<T, std::string>) {
return RequestId{item};
} else if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
if (std::in_range<std::int32_t>(item))
return RequestId{static_cast<std::int32_t>(item)};
} else if constexpr (std::is_floating_point_v<T>) {
const long double wide = static_cast<long double>(item);
if (std::isfinite(item) && std::trunc(item) == item &&
wide >= std::numeric_limits<std::int32_t>::min() &&
wide <= std::numeric_limits<std::int32_t>::max())
return RequestId{static_cast<std::int32_t>(item)};
}
return std::unexpected{"request ID must be a signed 32-bit integer or string"};
},
value.value);
}
std::string quote_json(std::string_view text) {
constexpr char hex[] = "0123456789abcdef";
std::string result{"\""};
for (const unsigned char c : text) {
if (c == '"' || c == '\\') {
result.push_back('\\');
result.push_back(static_cast<char>(c));
} else if (c < 0x20) {
result += "\\u00";
result.push_back(hex[c >> 4]);
result.push_back(hex[c & 15]);
} else {
result.push_back(static_cast<char>(c));
}
}
result.push_back('"');
return result;
}
std::string encode_id(const RequestId &id) {
return std::visit(
[](const auto &item) -> std::string {
if constexpr (std::is_same_v<std::remove_cvref_t<decltype(item)>, std::string>)
return quote_json(item);
else
return std::to_string(item);
},
id);
}
} // namespace vls
+147
View File
@@ -0,0 +1,147 @@
#include <vls/Server.hpp>
#include <vls/Json.hpp>
#include <exception>
#include <ostream>
namespace vls {
namespace {
const Json *member(const Json::Object &object, std::string_view key) {
const auto found = object.find(key);
return found == object.end() ? nullptr : &found->second;
}
const std::string *string(const Json *value) {
return value ? std::get_if<std::string>(&value->value) : nullptr;
}
DispatchResult error(std::string_view id, int code, std::string_view message) {
return {.response = "{\"jsonrpc\":\"2.0\",\"id\":" + std::string{id} + ",\"error\":{\"code\":" +
std::to_string(code) + ",\"message\":" + quote_json(message) + "}}",
.exit_code = std::nullopt};
}
DispatchResult result(std::string_view id, std::string_view value) {
return {.response = "{\"jsonrpc\":\"2.0\",\"id\":" + std::string{id} +
",\"result\":" + std::string{value} + "}",
.exit_code = std::nullopt};
}
} // namespace
DispatchResult Server::handle(std::string_view body) {
auto parsed = parse_json(body);
if (!parsed)
return error("null", -32700, "Parse error");
const auto *object = std::get_if<Json::Object>(&parsed->value);
if (!object)
return error("null", -32600, "Invalid Request");
const auto *id_value = member(*object, "id");
const auto *method_value = member(*object, "method");
const auto *method = string(method_value);
const auto *version = string(member(*object, "jsonrpc"));
const auto *params = member(*object, "params");
const auto *result_value = member(*object, "result");
const auto *error_value = member(*object, "error");
// This shell issues no requests. Valid peer responses are unmatched and
// must be ignored, including errors whose correlation ID is null.
if (version && *version == "2.0" && !method_value && id_value &&
((result_value != nullptr) != (error_value != nullptr))) {
const bool valid_id = std::holds_alternative<std::nullptr_t>(id_value->value) ||
request_id(*id_value).has_value();
bool valid_payload = result_value != nullptr;
if (error_value) {
if (const auto *details = std::get_if<Json::Object>(&error_value->value)) {
if (const auto *code = member(*details, "code");
code && string(member(*details, "message"))) {
const auto checked = request_id(*code);
valid_payload = checked && std::holds_alternative<std::int32_t>(*checked);
}
}
}
if (valid_id && valid_payload)
return {};
}
const bool notification = !id_value;
std::string id{"null"};
if (id_value) {
auto checked = request_id(*id_value);
if (!checked)
return error("null", -32600, "Invalid Request");
id = encode_id(*checked);
}
if (!version || *version != "2.0" || !method || result_value || error_value) {
// Method-bearing objects without IDs are notifications, even when
// malformed. They must never elicit a response.
if (notification && method_value)
return {};
return error(id, -32600, "Invalid Request");
}
if (notification) {
if (*method == "exit")
return {.response = std::nullopt, .exit_code = state_ == State::shutdown ? 0 : 1};
return {};
}
if (state_ == State::shutdown)
return error(id, -32600, "Invalid Request");
if (state_ == State::awaiting_initialize && *method != "initialize")
return error(id, -32002, "Server not initialized");
if (*method == "initialize") {
if (state_ != State::awaiting_initialize)
return error(id, -32600, "Invalid Request");
if (!params || !std::holds_alternative<Json::Object>(params->value))
return error(id, -32602, "initialize params must be an object");
state_ = State::running;
return result(id, "{\"capabilities\":{},\"serverInfo\":{\"name\":\"VoidLanguageServer\","
"\"version\":\"0.1.0\"}}");
}
if (params && !std::holds_alternative<Json::Object>(params->value) &&
!std::holds_alternative<Json::Array>(params->value) &&
!std::holds_alternative<std::nullptr_t>(params->value))
return error(id, -32600, "Invalid Request");
if (*method == "shutdown") {
if (params && !std::holds_alternative<std::nullptr_t>(params->value))
return error(id, -32602, "shutdown takes no params");
state_ = State::shutdown;
return result(id, "null");
}
return error(id, -32601, "Method not found");
}
int run_stdio(std::istream &input, std::ostream &output, std::ostream &diagnostics,
FrameLimits limits) {
try {
Server server;
for (;;) {
auto frame = read_frame(input, limits);
if (!frame) {
diagnostics << "vls: " << frame.error() << '\n';
return 1;
}
if (!*frame) {
diagnostics << "vls: unexpected EOF before exit notification\n";
return 1;
}
auto dispatched = server.handle(**frame);
if (dispatched.response) {
const auto written = write_frame(output, *dispatched.response);
if (!written) {
diagnostics << "vls: " << written.error() << '\n';
return 1;
}
}
if (dispatched.exit_code)
return *dispatched.exit_code;
}
} catch (const std::exception &) {
diagnostics << "vls: failed to process protocol stream\n";
return 1;
}
}
} // namespace vls
+39
View File
@@ -0,0 +1,39 @@
#include <vls/Server.hpp>
#include <Void/Configuration/Argparse.hpp>
#include <csignal>
#include <iostream>
#include <string_view>
int main(int argc, char **argv) {
bool stdio = false;
bool version = false;
Void::Argparse::Parser parser{
"vls", "VoidLanguageServer 0.1.0: stdio LSP lifecycle shell.\n"
"No arguments starts stdio. Language and debugger features are planned."};
parser.flag("--stdio", "", "run the stdio LSP lifecycle shell", stdio);
parser.flag("--version", "-V", "show version", version);
if (argc == 2 && (std::string_view{argv[1]} == "--help" || std::string_view{argv[1]} == "-h")) {
std::cout << parser.help();
return std::cout ? 0 : 1;
}
// Each mode is standalone. This also rejects duplicate flags deterministically.
if (argc > 2) {
std::cerr << "vls: options must be used alone; use --help\n";
return 2;
}
const auto parsed = parser.parse(argc, argv);
if (!parsed) {
std::cerr << "vls: " << parsed.error() << '\n';
return 2;
}
if (version) {
std::cout << "VoidLanguageServer " << vls::server_version << '\n';
return std::cout ? 0 : 1;
}
#ifdef SIGPIPE
std::signal(SIGPIPE, SIG_IGN);
#endif
return vls::run_stdio(std::cin, std::cout, std::cerr);
}