navid/haze / cb1bac46fbd9fca0f0e2a401590740b0840b47821983a25743fc29c1572577d9 / src/lsp.cpp

lsp.cpp

← src · 44161 bytes · raw · download

#include "haze.h"

#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <regex>
#include <sstream>
#include <string>
#include <vector>

#if defined(_WIN32)
#include <fcntl.h>
#include <io.h>
#endif

namespace haze {

namespace {

namespace fs = std::filesystem;

class Json {
public:
    enum class Kind { Null, Bool, Number, String, Array, Object };

    Kind kind = Kind::Null;
    bool boolean = false;
    long long number = 0;
    std::string string;
    std::vector<Json> array;
    std::map<std::string, Json> object;

    const Json* get(const std::string& key) const {
        auto it = object.find(key);
        return it == object.end() ? nullptr : &it->second;
    }

    std::string str() const {
        return kind == Kind::String ? string : "";
    }
};

class JsonParser {
public:
    explicit JsonParser(const std::string& text) : text_(text) {}

    Json parse() {
        Json value = value_at();
        skip();
        return value;
    }

private:
    const std::string& text_;
    size_t i_ = 0;

    void skip() {
        while (i_ < text_.size() &&
               (text_[i_] == ' ' || text_[i_] == '\t' || text_[i_] == '\r' ||
                text_[i_] == '\n'))
            i_++;
    }

    bool consume(char c) {
        skip();
        if (i_ < text_.size() && text_[i_] == c) {
            i_++;
            return true;
        }
        return false;
    }

    Json value_at() {
        skip();
        if (i_ >= text_.size())
            return Json{};
        char c = text_[i_];
        if (c == '{')
            return object_at();
        if (c == '[')
            return array_at();
        if (c == '"') {
            Json j;
            j.kind = Json::Kind::String;
            j.string = string_at();
            return j;
        }
        if (c == 't' || c == 'f') {
            Json j;
            j.kind = Json::Kind::Bool;
            if (text_.compare(i_, 4, "true") == 0) {
                j.boolean = true;
                i_ += 4;
            } else if (text_.compare(i_, 5, "false") == 0) {
                i_ += 5;
            }
            return j;
        }
        if (c == 'n') {
            if (text_.compare(i_, 4, "null") == 0)
                i_ += 4;
            return Json{};
        }
        Json j;
        j.kind = Json::Kind::Number;
        size_t start = i_;
        if (i_ < text_.size() && (text_[i_] == '-' || text_[i_] == '+'))
            i_++;
        while (i_ < text_.size() &&
               (std::isdigit(static_cast<unsigned char>(text_[i_])) || text_[i_] == '.' ||
                text_[i_] == 'e' || text_[i_] == 'E' || text_[i_] == '+' || text_[i_] == '-'))
            i_++;
        j.number = std::strtoll(text_.substr(start, i_ - start).c_str(), nullptr, 10);
        return j;
    }

    Json object_at() {
        Json j;
        j.kind = Json::Kind::Object;
        consume('{');
        for (;;) {
            skip();
            if (consume('}'))
                break;
            std::string key = string_at();
            consume(':');
            j.object[key] = value_at();
            skip();
            if (consume(','))
                continue;
            consume('}');
            break;
        }
        return j;
    }

    Json array_at() {
        Json j;
        j.kind = Json::Kind::Array;
        consume('[');
        for (;;) {
            skip();
            if (consume(']'))
                break;
            j.array.push_back(value_at());
            skip();
            if (consume(','))
                continue;
            consume(']');
            break;
        }
        return j;
    }

    std::string string_at() {
        skip();
        if (i_ >= text_.size() || text_[i_] != '"')
            return "";
        i_++;
        std::string out;
        while (i_ < text_.size() && text_[i_] != '"') {
            char c = text_[i_++];
            if (c != '\\') {
                out.push_back(c);
                continue;
            }
            if (i_ >= text_.size())
                break;
            char e = text_[i_++];
            switch (e) {
            case 'n':
                out.push_back('\n');
                break;
            case 'r':
                out.push_back('\r');
                break;
            case 't':
                out.push_back('\t');
                break;
            case 'b':
                out.push_back('\b');
                break;
            case 'f':
                out.push_back('\f');
                break;
            case 'u': {
                unsigned value = 0;
                for (int k = 0; k < 4 && i_ < text_.size(); k++) {
                    char h = text_[i_++];
                    value <<= 4;
                    if (h >= '0' && h <= '9')
                        value += static_cast<unsigned>(h - '0');
                    else if (h >= 'a' && h <= 'f')
                        value += static_cast<unsigned>(h - 'a' + 10);
                    else if (h >= 'A' && h <= 'F')
                        value += static_cast<unsigned>(h - 'A' + 10);
                }
                if (value < 0x80) {
                    out.push_back(static_cast<char>(value));
                } else if (value < 0x800) {
                    out.push_back(static_cast<char>(0xC0 | (value >> 6)));
                    out.push_back(static_cast<char>(0x80 | (value & 0x3F)));
                } else {
                    out.push_back(static_cast<char>(0xE0 | (value >> 12)));
                    out.push_back(static_cast<char>(0x80 | ((value >> 6) & 0x3F)));
                    out.push_back(static_cast<char>(0x80 | (value & 0x3F)));
                }
                break;
            }
            default:
                out.push_back(e);
                break;
            }
        }
        if (i_ < text_.size() && text_[i_] == '"')
            i_++;
        return out;
    }
};

std::string json_escape(const std::string& s) {
    std::string out;
    for (char c : s) {
        switch (c) {
        case '"':
            out += "\\\"";
            break;
        case '\\':
            out += "\\\\";
            break;
        case '\n':
            out += "\\n";
            break;
        case '\r':
            out += "\\r";
            break;
        case '\t':
            out += "\\t";
            break;
        default:
            if (static_cast<unsigned char>(c) < 0x20) {
                char buf[8];
                std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast<unsigned>(c));
                out += buf;
            } else {
                out.push_back(c);
            }
            break;
        }
    }
    return out;
}

std::string json_string(const std::string& s) {
    return "\"" + json_escape(s) + "\"";
}

std::string percent_decode(const std::string& s) {
    std::string out;
    for (size_t i = 0; i < s.size(); i++) {
        if (s[i] == '%' && i + 2 < s.size()) {
            auto hex = [](char c) -> int {
                if (c >= '0' && c <= '9')
                    return c - '0';
                if (c >= 'a' && c <= 'f')
                    return c - 'a' + 10;
                if (c >= 'A' && c <= 'F')
                    return c - 'A' + 10;
                return 0;
            };
            out.push_back(static_cast<char>(hex(s[i + 1]) * 16 + hex(s[i + 2])));
            i += 2;
        } else {
            out.push_back(s[i]);
        }
    }
    return out;
}

std::string percent_encode(const std::string& s) {
    std::string out;
    for (unsigned char c : s) {
        if (std::isalnum(c) || c == '/' || c == ':' || c == '-' || c == '_' || c == '.' ||
            c == '~') {
            out.push_back(static_cast<char>(c));
        } else {
            char buf[4];
            std::snprintf(buf, sizeof(buf), "%%%02X", static_cast<unsigned>(c));
            out += buf;
        }
    }
    return out;
}

std::string path_to_uri(const fs::path& path) {
    std::error_code ec;
    fs::path abs = fs::absolute(path, ec);
    return "file://" + percent_encode(abs.generic_string());
}

fs::path uri_to_path(const std::string& uri) {
    std::string s = uri;
    if (s.rfind("file://", 0) == 0)
        s = s.substr(7);
    else if (s.rfind("file:", 0) == 0)
        s = s.substr(5);
    return fs::path(percent_decode(s));
}

std::string read_file(const fs::path& path) {
    std::ifstream in(path, std::ios::binary);
    if (!in)
        return {};
    std::ostringstream ss;
    ss << in.rdbuf();
    return ss.str();
}

struct DeclInfo {
    enum class Kind { Function, Type, Contract, Global, Field };
    Kind kind = Kind::Global;
    std::string name;
    std::string signature;
    std::string detail;
    bool pub = false;
    fs::path file;
    Pos pos;
    const Type* type = nullptr;
};

struct ModuleInfo {
    fs::path path;
    std::string text;
    Program program;
    std::vector<Use> uses;
    std::vector<DeclInfo> decls;
    std::vector<DeclInfo> fields;
    std::vector<TypePtr> owned_types;
};

struct Index {
    std::map<std::string, std::unique_ptr<ModuleInfo>> modules;
    std::vector<ModuleInfo*> order;
    std::map<std::string, std::vector<DeclInfo*>> by_name;
};

std::string type_text(const TypePtr& type) {
    return type ? type_name(type) : "?";
}

std::string params_text(const std::vector<Param>& params) {
    std::string s;
    for (size_t i = 0; i < params.size(); i++) {
        if (i)
            s += ", ";
        s += params[i].name + " " + type_text(params[i].type);
    }
    return s;
}

DeclInfo make_function_decl(const Function& fn, const fs::path& path) {
    DeclInfo d;
    d.kind = DeclInfo::Kind::Function;
    d.name = fn.name;
    d.pub = fn.pub;
    d.file = path;
    d.pos = fn.pos;
    std::string sig = "fn " + fn.name + "(" + params_text(fn.params) + ")";
    if (fn.ret)
        sig += " " + type_text(fn.ret);
    d.signature = sig;
    d.detail = sig;
    if (fn.pure)
        d.detail = "pure " + d.detail;
    return d;
}

DeclInfo make_type_decl(const Type& type, const fs::path& path) {
    DeclInfo d;
    d.kind = DeclInfo::Kind::Type;
    d.name = type.name;
    d.pub = type.pub;
    d.file = path;
    d.pos = Pos{};
    d.type = &type;
    if (type.kind == Type::Kind::Record) {
        d.signature = "type " + type.name + " {";
        for (auto& f : type.fields)
            d.signature += "\n    " + f.name + " " + type_text(f.type);
        d.signature += "\n}";
    } else {
        d.signature = "type " + type.name + " =";
        for (auto& v : type.variants) {
            d.signature += " | " + v.name;
            if (!v.fields.empty()) {
                d.signature += "(";
                for (size_t i = 0; i < v.fields.size(); i++) {
                    if (i)
                        d.signature += ", ";
                    d.signature += v.fields[i].name + " " + type_text(v.fields[i].type);
                }
                d.signature += ")";
            }
        }
    }
    d.detail = d.signature;
    return d;
}

std::string module_relative_name(const fs::path& module, const fs::path& base) {
    std::error_code ec;
    fs::path rel = fs::relative(module, base, ec);
    if (ec)
        rel = module.filename();
    rel.replace_extension();
    return rel.generic_string();
}

class Server {
public:
    void run() {
        std::string body;
        while (read_message(std::cin, body)) {
            Json request;
            try {
                request = JsonParser(body).parse();
            } catch (...) {
                continue;
            }
            handle(request);
            if (exiting_)
                break;
        }
    }

private:
    std::map<std::string, std::string> documents_;
    bool exiting_ = false;

    static bool read_message(std::istream& in, std::string& body) {
        size_t length = 0;
        std::string line;
        bool header = false;
        while (std::getline(in, line)) {
            if (!line.empty() && line.back() == '\r')
                line.pop_back();
            if (line.empty())
                break;
            header = true;
            if (line.rfind("Content-Length:", 0) == 0) {
                try {
                    length = static_cast<size_t>(std::stoull(line.substr(15)));
                } catch (...) {
                    length = 0;
                }
            }
        }
        if (!header || length == 0)
            return false;
        body.resize(length);
        in.read(&body[0], static_cast<std::streamsize>(length));
        return static_cast<size_t>(in.gcount()) == length;
    }

    static void write_message(const std::string& body) {
        std::cout << "Content-Length: " << body.size() << "\r\n\r\n";
        std::cout.write(body.data(), static_cast<std::streamsize>(body.size()));
        std::cout.flush();
    }

    static void respond(const Json& id, const std::string& result) {
        std::string out = "{\"jsonrpc\":\"2.0\",\"id\":";
        if (id.kind == Json::Kind::Number)
            out += std::to_string(id.number);
        else
            out += json_string(id.str());
        out += ",\"result\":" + result + "}";
        write_message(out);
    }

    static void respond_null(const Json& id) {
        respond(id, "null");
    }

    void handle(const Json& request) {
        const Json* method_json = request.get("method");
        std::string method = method_json ? method_json->str() : "";
        const Json* id = request.get("id");
        const Json* params = request.get("params");

        if (method == "initialize") {
            if (id)
                respond(*id, capabilities());
        } else if (method == "initialized") {
        } else if (method == "shutdown") {
            if (id)
                respond_null(*id);
        } else if (method == "exit") {
            exiting_ = true;
        } else if (method == "textDocument/didOpen") {
            did_open(params);
        } else if (method == "textDocument/didChange") {
            did_change(params);
        } else if (method == "textDocument/didClose") {
            did_close(params);
        } else if (method == "textDocument/completion") {
            if (id)
                handle_completion(*id, params);
        } else if (method == "textDocument/signatureHelp") {
            if (id)
                handle_signature(*id, params);
        } else if (method == "textDocument/hover") {
            if (id)
                handle_hover(*id, params);
        } else if (method == "textDocument/definition") {
            if (id)
                handle_definition(*id, params);
        } else if (id) {
            respond_null(*id);
        }
    }

    static std::string capabilities() {
        return "{\"capabilities\":{\"textDocumentSync\":{\"openClose\":true,\"change\":1},"
               "\"completionProvider\":{\"triggerCharacters\":[\":\",\".\"]},"
               "\"signatureHelpProvider\":{\"triggerCharacters\":[\"(\",\",\"]},"
               "\"hoverProvider\":true,\"definitionProvider\":true},"
               "\"serverInfo\":{\"name\":\"hz-lsp\",\"version\":\"0.1\"}}";
    }

    void did_open(const Json* params) {
        if (!params)
            return;
        const Json* doc = params->get("textDocument");
        if (!doc)
            return;
        const Json* uri = doc->get("uri");
        const Json* text = doc->get("text");
        if (!uri || !text)
            return;
        std::error_code ec;
        fs::path path = fs::weakly_canonical(uri_to_path(uri->str()), ec);
        documents_[path.generic_string()] = text->str();
    }

    void did_change(const Json* params) {
        if (!params)
            return;
        const Json* doc = params->get("textDocument");
        const Json* changes = params->get("contentChanges");
        if (!doc || !changes || changes->array.empty())
            return;
        const Json* uri = doc->get("uri");
        if (!uri)
            return;
        std::error_code ec;
        fs::path path = fs::weakly_canonical(uri_to_path(uri->str()), ec);
        for (auto it = changes->array.rbegin(); it != changes->array.rend(); ++it) {
            const Json* text = it->get("text");
            if (text) {
                documents_[path.generic_string()] = text->str();
                break;
            }
        }
    }

    void did_close(const Json* params) {
        (void)params;
    }

    std::string document_text(const fs::path& path) {
        auto it = documents_.find(path.generic_string());
        if (it != documents_.end())
            return it->second;
        return read_file(path);
    }

    std::shared_ptr<Index> build_index(const fs::path& root) {
        auto index = std::make_shared<Index>();
        std::error_code ec;
        fs::path root_path = fs::weakly_canonical(root, ec);
        if (ec)
            root_path = root;
        load_module(*index, root_path, root_path.parent_path());

        for (auto& [key, text] : documents_) {
            fs::path path(key);
            load_module(*index, path, root_path.parent_path());
        }
        return index;
    }

    void fallback_index(ModuleInfo& module) {
        std::vector<std::string> lines = split(module.text);
        std::regex use_re(R"(^\s*use\s+([^\s{]+)\s*(?:\{([^}]*)\})?)");
        std::regex fn_re(
            R"(^\s*(pub\s+)?(pure\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\))");
        std::regex contract_re(
            R"(^\s*(pub\s+)?contract\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\))");
        std::regex type_re(
            R"(^\s*(pub\s+)?type\s+([A-Za-z_][A-Za-z0-9_]*)\s*([={].*)?$)");
        std::regex global_re(
            R"(^\s*(pub\s+)?const\s+([A-Za-z_][A-Za-z0-9_]*)\s+([A-Za-z_][A-Za-z0-9_]*\s*(?:\[[^\]]*\])?))");
        std::regex field_re(R"(^\s*([A-Za-z_][A-Za-z0-9_]*)\s+([A-Za-z_][^\s]*)\s*$)");

        Type* current_type = nullptr;
        for (size_t i = 0; i < lines.size(); i++) {
            const std::string& line = lines[i];
            std::smatch m;
            if (std::regex_search(line, m, use_re)) {
                Use use;
                use.module = m[1].str();
                use.pos = Pos{static_cast<int>(i) + 1, 1};
                if (m[2].matched) {
                    std::string names = m[2].str();
                    std::stringstream ss(names);
                    std::string name;
                    while (std::getline(ss, name, ',')) {
                        size_t a = name.find_first_not_of(" \t");
                        size_t b = name.find_last_not_of(" \t");
                        if (a != std::string::npos)
                            use.names.push_back(name.substr(a, b - a + 1));
                    }
                }
                module.uses.push_back(std::move(use));
            }
            if (std::regex_search(line, m, fn_re)) {
                DeclInfo d;
                d.kind = DeclInfo::Kind::Function;
                d.name = m[3].str();
                d.pub = m[1].matched;
                d.file = module.path;
                size_t at = line.find(d.name);
                d.pos = Pos{static_cast<int>(i) + 1,
                            at == std::string::npos ? 1 : static_cast<int>(at) + 1};
                d.signature = "fn " + d.name + "(" + m[4].str() + ")";
                std::string rest = line.substr(static_cast<size_t>(m.position() + m.length()));
                size_t a = rest.find_first_not_of(" \t");
                if (a != std::string::npos && rest[a] != ':' && rest[a] != '{' &&
                    rest[a] != '=' && rest[a] != '-') {
                    size_t b = rest.find_first_of(" \t:{=", a);
                    d.signature += " " + rest.substr(a, b == std::string::npos ? b : b - a);
                }
                d.detail = d.signature;
                module.decls.push_back(std::move(d));
            }
            if (std::regex_search(line, m, contract_re)) {
                DeclInfo d;
                d.kind = DeclInfo::Kind::Contract;
                d.name = m[2].str();
                d.pub = m[1].matched;
                d.file = module.path;
                size_t at = line.find(d.name);
                d.pos = Pos{static_cast<int>(i) + 1,
                            at == std::string::npos ? 1 : static_cast<int>(at) + 1};
                d.signature = "contract " + d.name + "(" + m[3].str() + ")";
                d.detail = d.signature;
                module.decls.push_back(std::move(d));
            }
            if (std::regex_search(line, m, type_re)) {
                auto type = std::make_shared<Type>();
                type->name = m[2].str();
                type->pub = m[1].matched;
                bool record = !m[3].matched || m[3].str().empty() || m[3].str()[0] == '{';
                type->kind = record ? Type::Kind::Record : Type::Kind::Sum;
                DeclInfo d;
                d.kind = DeclInfo::Kind::Type;
                d.name = type->name;
                d.pub = type->pub;
                d.file = module.path;
                size_t at = line.find(d.name);
                d.pos = Pos{static_cast<int>(i) + 1,
                            at == std::string::npos ? 1 : static_cast<int>(at) + 1};
                d.type = type.get();
                d.signature = "type " + type->name;
                d.detail = d.signature;
                module.decls.push_back(std::move(d));
                module.owned_types.push_back(type);
                current_type = record ? type.get() : nullptr;
                continue;
            }
            if (current_type) {
                std::string trimmed = line;
                size_t a = trimmed.find_first_not_of(" \t");
                if (a != std::string::npos && trimmed[a] == '}') {
                    current_type = nullptr;
                    continue;
                }
                if (std::regex_search(line, m, field_re)) {
                    Field field;
                    field.name = m[1].str();
                    field.type = t_unknown(m[2].str());
                    field.pos = Pos{static_cast<int>(i) + 1, 1};
                    current_type->fields.push_back(field);
                }
            }
            if (std::regex_search(line, m, global_re)) {
                DeclInfo d;
                d.kind = DeclInfo::Kind::Global;
                d.name = m[2].str();
                d.pub = m[1].matched;
                d.file = module.path;
                size_t at = line.find(d.name);
                d.pos = Pos{static_cast<int>(i) + 1,
                            at == std::string::npos ? 1 : static_cast<int>(at) + 1};
                d.signature = "const " + d.name + " " + m[3].str();
                d.detail = d.signature;
                module.decls.push_back(std::move(d));
            }
        }
    }

    void load_module(Index& index, const fs::path& raw_path, const fs::path& base) {
        std::error_code ec;
        fs::path path = fs::weakly_canonical(raw_path, ec);
        if (ec)
            path = raw_path;
        std::string key = path.generic_string();
        if (index.modules.count(key))
            return;

        auto module = std::make_unique<ModuleInfo>();
        module->path = path;
        module->text = document_text(path);
        bool parsed = true;
        if (!module->text.empty()) {
            try {
                module->program = parse_program(module->text);
            } catch (...) {
                module->program = Program{};
                parsed = false;
                fallback_index(*module);
            }
        }
        if (parsed)
            module->uses = module->program.uses;
        module->program.module = module_relative_name(path, base);

        for (auto& fn : module->program.functions) {
            DeclInfo d = make_function_decl(*fn, path);
            module->decls.push_back(std::move(d));
        }
        for (auto& type : module->program.types) {
            DeclInfo d = make_type_decl(*type, path);
            d.pos = Pos{};
            module->decls.push_back(std::move(d));
            for (auto& f : type->fields) {
                DeclInfo field;
                field.kind = DeclInfo::Kind::Field;
                field.name = f.name;
                field.pub = type->pub;
                field.file = path;
                field.pos = f.pos;
                field.type = type.get();
                field.signature = f.name + " " + type_text(f.type);
                field.detail = field.signature;
                module->fields.push_back(std::move(field));
            }
        }
        for (auto& c : module->program.contracts) {
            DeclInfo d;
            d.kind = DeclInfo::Kind::Contract;
            d.name = c->name;
            d.pub = c->pub;
            d.file = path;
            d.pos = c->pos;
            d.signature = "contract " + c->name + "(" + params_text(c->params) + ")";
            d.detail = d.signature;
            module->decls.push_back(std::move(d));
        }
        for (auto& g : module->program.globals) {
            DeclInfo d;
            d.kind = DeclInfo::Kind::Global;
            d.name = g.name;
            d.pub = g.pub;
            d.file = path;
            d.pos = g.pos;
            d.signature = "const " + g.name;
            if (g.type)
                d.signature += " " + type_text(g.type);
            d.detail = d.signature;
            module->decls.push_back(std::move(d));
        }

        ModuleInfo* saved = module.get();
        index.modules[key] = std::move(module);
        index.order.push_back(saved);

        for (auto& d : saved->decls)
            index.by_name[d.name].push_back(&d);
        for (auto& d : saved->fields)
            index.by_name[d.name].push_back(&d);

        for (auto& use : saved->uses) {
            std::error_code use_ec;
            fs::path target = fs::weakly_canonical(path.parent_path() /
                                                        fs::path(use.module + ".hz"),
                                                    use_ec);
            if (use_ec)
                target = path.parent_path() / fs::path(use.module + ".hz");
            if (fs::is_regular_file(target) || documents_.count(target.generic_string()))
                load_module(index, target, base);
        }
    }

    struct Position {
        int line = 0;
        int character = 0;
    };

    struct DocContext {
        fs::path path;
        std::string text;
        std::vector<std::string> lines;
        ModuleInfo* module = nullptr;
    };

    DocContext context(const Json* params, Index& index) {
        DocContext ctx;
        if (!params)
            return ctx;
        const Json* doc = params->get("textDocument");
        if (!doc)
            return ctx;
        const Json* uri = doc->get("uri");
        if (!uri)
            return ctx;
        std::error_code ec;
        ctx.path = fs::weakly_canonical(uri_to_path(uri->str()), ec);
        ctx.text = document_text(ctx.path);
        ctx.lines = split(ctx.text);
        std::string key = ctx.path.generic_string();
        auto it = index.modules.find(key);
        if (it != index.modules.end())
            ctx.module = it->second.get();
        return ctx;
    }

    static std::vector<std::string> split(const std::string& text) {
        std::vector<std::string> lines;
        std::string cur;
        for (char c : text) {
            if (c == '\n') {
                if (!cur.empty() && cur.back() == '\r')
                    cur.pop_back();
                lines.push_back(cur);
                cur.clear();
            } else {
                cur.push_back(c);
            }
        }
        if (!cur.empty() && cur.back() == '\r')
            cur.pop_back();
        lines.push_back(cur);
        return lines;
    }

    static Position position_of(const Json* params) {
        Position p;
        if (!params)
            return p;
        const Json* pos = params->get("position");
        if (!pos)
            return p;
        if (const Json* line = pos->get("line"))
            p.line = static_cast<int>(line->number);
        if (const Json* character = pos->get("character"))
            p.character = static_cast<int>(character->number);
        return p;
    }

    static std::string line_at(const std::vector<std::string>& lines, int line) {
        if (line < 0 || static_cast<size_t>(line) >= lines.size())
            return "";
        return lines[static_cast<size_t>(line)];
    }

    static std::string word_at(const std::string& line, int character) {
        if (line.empty())
            return "";
        int i = std::clamp(character, 0, static_cast<int>(line.size()));
        auto ident = [](char c) {
            return std::isalnum(static_cast<unsigned char>(c)) || c == '_';
        };
        int start = i;
        while (start > 0 && ident(line[start - 1]))
            start--;
        int end = i;
        while (end < static_cast<int>(line.size()) && ident(line[end]))
            end++;
        return line.substr(static_cast<size_t>(start), static_cast<size_t>(end - start));
    }

    static std::string location(const DeclInfo& d) {
        int line = d.pos.line > 0 ? d.pos.line - 1 : 0;
        int col = d.pos.col > 0 ? d.pos.col - 1 : 0;
        return "{\"uri\":" + json_string(path_to_uri(d.file)) +
               ",\"range\":{\"start\":{\"line\":" + std::to_string(line) +
               ",\"character\":" + std::to_string(col) + "},\"end\":{\"line\":" +
               std::to_string(line) + ",\"character\":" + std::to_string(col) + "}}}";
    }

    std::vector<DeclInfo*> lookup(Index& index, const std::string& name,
                                  ModuleInfo* current) {
        std::vector<DeclInfo*> result;
        if (current) {
            for (auto& d : current->decls)
                if (d.name == name)
                    result.push_back(&d);
        }
        auto it = index.by_name.find(name);
        if (it != index.by_name.end()) {
            for (auto* d : it->second) {
                if (std::find(result.begin(), result.end(), d) == result.end())
                    result.push_back(d);
            }
        }
        return result;
    }

    static ModuleInfo* find_used_module(Index& index, ModuleInfo* current,
                                        const std::string& prefix) {
        if (!current)
            return nullptr;
        for (auto& use : current->uses) {
            std::string raw = use.module;
            fs::path p(raw);
            std::string base = p.filename().string();
            std::string stem = p.stem().string();
            if (raw == prefix || base == prefix || stem == prefix)
                return module_by_use(index, current, use);
        }
        auto it = index.modules.find(prefix);
        if (it != index.modules.end())
            return it->second.get();
        for (auto& [key, module] : index.modules) {
            if (module_relative_name(module->path, index.order.empty()
                                                       ? fs::path()
                                                       : index.order.front()->path.parent_path()) ==
                prefix)
                return module.get();
        }
        return nullptr;
    }

    static ModuleInfo* module_by_use(Index& index, ModuleInfo* current, const Use& use) {
        std::error_code ec;
        fs::path target =
            fs::weakly_canonical(current->path.parent_path() / fs::path(use.module + ".hz"), ec);
        if (ec)
            target = current->path.parent_path() / fs::path(use.module + ".hz");
        auto it = index.modules.find(target.generic_string());
        return it == index.modules.end() ? nullptr : it->second.get();
    }

    static Type* find_type(Index& index, ModuleInfo* current, const std::string& name) {
        if (current) {
            for (auto& t : current->program.types)
                if (t->name == name)
                    return t.get();
        }
        auto it = index.by_name.find(name);
        if (it != index.by_name.end()) {
            for (auto* d : it->second) {
                if (d->kind == DeclInfo::Kind::Type && d->type)
                    return const_cast<Type*>(d->type);
            }
        }
        return nullptr;
    }

    static std::string receiver_type(Index& index, ModuleInfo* current,
                                     const std::string& document,
                                     const std::string& receiver) {
        std::regex local("\\b(?:var|const)\\s+" + receiver +
                         "\\s+([A-Za-z_][A-Za-z0-9_]*)");
        std::smatch match;
        if (std::regex_search(document, match, local))
            return match[1].str();

        std::regex param("\\b" + receiver + "\\s+([A-Za-z_][A-Za-z0-9_]*)");
        if (std::regex_search(document, match, param))
            return match[1].str();
        (void)index;
        (void)current;
        return "";
    }

    static std::string completion_item(const std::string& label, int kind,
                                       const std::string& detail) {
        return "{\"label\":" + json_string(label) + ",\"kind\":" + std::to_string(kind) +
               ",\"detail\":" + json_string(detail) + "}";
    }

    void handle_completion(const Json& id, const Json* params) {
        auto index = build_index_from_params(params);
        DocContext ctx = context(params, *index);
        Position pos = position_of(params);
        std::string line = line_at(ctx.lines, pos.line);
        std::string prefix = line.substr(0, static_cast<size_t>(
                                                std::clamp(pos.character, 0,
                                                           static_cast<int>(line.size()))));

        std::vector<std::string> items;
        if (prefix.size() >= 2 && prefix.compare(prefix.size() - 2, 2, "::") == 0) {
            std::string module_prefix = prefix.substr(0, prefix.size() - 2);
            size_t start = module_prefix.size();
            while (start > 0) {
                char c = module_prefix[start - 1];
                if (std::isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '/' ||
                    c == '.' || c == '-')
                    start--;
                else
                    break;
            }
            module_prefix = module_prefix.substr(start);
            ModuleInfo* mod = find_used_module(*index, ctx.module, module_prefix);
            if (mod) {
                for (auto& d : mod->decls) {
                    if (!d.pub)
                        continue;
                    int kind = 3;
                    if (d.kind == DeclInfo::Kind::Type)
                        kind = 7;
                    else if (d.kind == DeclInfo::Kind::Contract)
                        kind = 8;
                    else if (d.kind == DeclInfo::Kind::Global)
                        kind = 21;
                    items.push_back(completion_item(d.name, kind, d.detail));
                }
            }
        } else if (!prefix.empty() && prefix.back() == '.') {
            bool range = prefix.size() >= 2 && prefix[prefix.size() - 2] == '.';
            if (!range) {
                std::string before = prefix.substr(0, prefix.size() - 1);
                size_t start = before.size();
                while (start > 0) {
                    char c = before[start - 1];
                    if (std::isalnum(static_cast<unsigned char>(c)) || c == '_' ||
                        c == '.')
                        start--;
                    else
                        break;
                }
                std::string receiver = before.substr(start);
                size_t dot = receiver.find_last_of('.');
                if (dot != std::string::npos)
                    receiver = receiver.substr(dot + 1);
                std::string type_name = receiver_type(*index, ctx.module, ctx.text, receiver);
                if (!type_name.empty()) {
                    Type* type = find_type(*index, ctx.module, type_name);
                    if (type && type->kind == Type::Kind::Record) {
                        for (auto& field : type->fields) {
                            if (!field.type)
                                continue;
                            items.push_back(completion_item(field.name, 5,
                                                            field.name + " " +
                                                                type_text(field.type)));
                        }
                    }
                }
            }
        }

        std::string result = "{\"isIncomplete\":false,\"items\":[";
        for (size_t i = 0; i < items.size(); i++) {
            if (i)
                result += ",";
            result += items[i];
        }
        result += "]}";
        respond(id, result);
    }

    void handle_signature(const Json& id, const Json* params) {
        auto index = build_index_from_params(params);
        DocContext ctx = context(params, *index);
        Position pos = position_of(params);
        std::string line = line_at(ctx.lines, pos.line);
        int cursor = std::clamp(pos.character, 0, static_cast<int>(line.size()));

        int depth = 0;
        int open = -1;
        for (int i = cursor - 1; i >= 0; i--) {
            if (line[i] == ')')
                depth++;
            else if (line[i] == '(') {
                if (depth == 0) {
                    open = i;
                    break;
                }
                depth--;
            }
        }
        if (open < 0) {
            respond_null(id);
            return;
        }

        int end = open;
        while (end > 0 && std::isspace(static_cast<unsigned char>(line[end - 1])))
            end--;
        int start = end;
        while (start > 0) {
            char c = line[start - 1];
            if (std::isalnum(static_cast<unsigned char>(c)) || c == '_' || c == ':')
                start--;
            else
                break;
        }
        std::string callee = line.substr(static_cast<size_t>(start),
                                         static_cast<size_t>(end - start));
        size_t sep = callee.find_last_of(':');
        if (sep != std::string::npos)
            callee = callee.substr(sep + 1);

        DeclInfo* found = nullptr;
        for (auto* d : lookup(*index, callee, ctx.module)) {
            if (d->kind == DeclInfo::Kind::Function) {
                found = d;
                break;
            }
        }

        int active = 0;
        int paren = 0;
        for (int i = open + 1; i < cursor; i++) {
            if (line[i] == '(')
                paren++;
            else if (line[i] == ')')
                paren--;
            else if (line[i] == ',' && paren == 0)
                active++;
        }

        if (!found) {
            respond_null(id);
            return;
        }

        std::string label = found->signature;
        std::string inside;
        size_t lparen = label.find('(');
        size_t rparen = label.rfind(')');
        if (lparen != std::string::npos && rparen != std::string::npos && rparen > lparen)
            inside = label.substr(lparen + 1, rparen - lparen - 1);

        std::vector<std::string> parts;
        std::string part;
        int nesting = 0;
        for (char c : inside) {
            if (c == '(' || c == '[')
                nesting++;
            else if (c == ')' || c == ']')
                nesting--;
            if (c == ',' && nesting == 0) {
                parts.push_back(part);
                part.clear();
            } else {
                part.push_back(c);
            }
        }
        if (!part.empty() || !inside.empty())
            parts.push_back(part);

        if (!parts.empty() && active >= static_cast<int>(parts.size()))
            active = static_cast<int>(parts.size()) - 1;

        std::string parameters = "[";
        for (size_t i = 0; i < parts.size(); i++) {
            size_t a = parts[i].find_first_not_of(" \t");
            size_t b = parts[i].find_last_not_of(" \t");
            std::string p = a == std::string::npos ? "" : parts[i].substr(a, b - a + 1);
            if (i)
                parameters += ",";
            parameters += "{\"label\":" + json_string(p) + "}";
        }
        parameters += "]";

        std::string result = "{\"signatures\":[{\"label\":" + json_string(label) +
                             ",\"parameters\":" + parameters +
                             "}],\"activeSignature\":0,\"activeParameter\":" +
                             std::to_string(active) + "}";
        respond(id, result);
    }

    void handle_hover(const Json& id, const Json* params) {
        auto index = build_index_from_params(params);
        DocContext ctx = context(params, *index);
        Position pos = position_of(params);
        std::string line = line_at(ctx.lines, pos.line);
        std::string name = word_at(line, pos.character);
        if (name.empty()) {
            respond_null(id);
            return;
        }

        for (auto* d : lookup(*index, name, ctx.module)) {
            std::string value = d->detail.empty() ? d->signature : d->detail;
            std::string result = "{\"contents\":{\"kind\":\"markdown\",\"value\":" +
                                 json_string("```haze\n" + value + "\n```") + "}}";
            respond(id, result);
            return;
        }

        std::regex local("\\b(?:var|const)\\s+" + name +
                         "\\s+([A-Za-z_][A-Za-z0-9_]*)");
        std::smatch match;
        if (std::regex_search(ctx.text, match, local)) {
            std::string value = name + " " + match[1].str();
            std::string result = "{\"contents\":{\"kind\":\"markdown\",\"value\":" +
                                 json_string("```haze\n" + value + "\n```") + "}}";
            respond(id, result);
            return;
        }
        respond_null(id);
    }

    void handle_definition(const Json& id, const Json* params) {
        auto index = build_index_from_params(params);
        DocContext ctx = context(params, *index);
        Position pos = position_of(params);
        std::string line = line_at(ctx.lines, pos.line);
        std::string name = word_at(line, pos.character);

        if (name.empty()) {
            respond_null(id);
            return;
        }

        std::regex local("\\b(?:var|const)\\s+" + name + "\\b");
        for (size_t i = 0; i < ctx.lines.size(); i++) {
            if (!std::regex_search(ctx.lines[i], local))
                continue;
            int col = static_cast<int>(ctx.lines[i].find(name));
            if (col < 0)
                col = 0;
            std::string result =
                "{\"uri\":" + json_string(path_to_uri(ctx.path)) +
                ",\"range\":{\"start\":{\"line\":" + std::to_string(i) +
                ",\"character\":" + std::to_string(col) + "},\"end\":{\"line\":" +
                std::to_string(i) + ",\"character\":" +
                std::to_string(col + static_cast<int>(name.size())) + "}}}";
            respond(id, result);
            return;
        }

        for (auto* d : lookup(*index, name, ctx.module)) {
            respond(id, location(*d));
            return;
        }
        respond_null(id);
    }

    std::shared_ptr<Index> build_index_from_params(const Json* params) {
        fs::path root;
        if (params) {
            const Json* doc = params->get("textDocument");
            if (doc) {
                const Json* uri = doc->get("uri");
                if (uri) {
                    std::error_code ec;
                    root = fs::weakly_canonical(uri_to_path(uri->str()), ec);
                }
            }
        }
        return build_index(root);
    }
};

} // namespace

void run_lsp_server() {
#if defined(_WIN32)
    _setmode(_fileno(stdin), _O_BINARY);
    _setmode(_fileno(stdout), _O_BINARY);
#endif
    Server server;
    server.run();
}

} // namespace haze