navid/haze / commit
dcbf51460867
Navid M <navidmomtahen@gmail.com> · 2026-12-02
parents: a23ce0522231
Browse files at this commit · Download source
--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -101,7 +101,9 @@ src/codegen.cpp src/driver.cpp src/eval.cpp+ src/formatter.cpp src/lexer.cpp+ src/lsp.cpp src/module.cpp src/parser.cpp src/sema.cpp@@ -174,6 +176,8 @@ "${CMAKE_CURRENT_SOURCE_DIR}/samples/baseline_2.4/*.hz") file(GLOB baseline_25_samples CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/samples/baseline_2.5/*.hz")+file(GLOB baseline_26_samples CONFIGURE_DEPENDS+ "${CMAKE_CURRENT_SOURCE_DIR}/samples/baseline_2.6/*.hz") list(SORT baseline_samples) list(SORT baseline_21_samples) list(SORT baseline_22_samples)@@ -180,9 +184,10 @@ list(SORT baseline_23_samples) list(SORT baseline_24_samples) list(SORT baseline_25_samples)+list(SORT baseline_26_samples) foreach(source IN LISTS baseline_samples baseline_21_samples baseline_22_samples- baseline_23_samples baseline_24_samples baseline_25_samples)+ baseline_23_samples baseline_24_samples baseline_25_samples baseline_26_samples) add_haze_sample_test("${source}") endforeach() add_haze_sample_test("${CMAKE_CURRENT_SOURCE_DIR}/samples/baseline_2/main.hz")@@ -190,6 +195,24 @@ add_test(NAME runtime COMMAND hazert_test) set_tests_properties(runtime PROPERTIES ENVIRONMENT "HAZE_GC_WORKERS=4;HAZE_GC_VERIFY=1")++add_test(+ NAME format+ COMMAND "${CMAKE_COMMAND}"+ "-DHZ=$<TARGET_FILE:hz>"+ "-DSOURCE=${CMAKE_CURRENT_SOURCE_DIR}/tests/format/unformatted.hz"+ "-DEXPECTED=${CMAKE_CURRENT_SOURCE_DIR}/tests/format/expected.hz"+ "-DOUTPUT=${CMAKE_CURRENT_BINARY_DIR}/format-test.hz"+ -P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/run_format_test.cmake")++add_test(+ NAME lsp+ COMMAND "${CMAKE_COMMAND}"+ "-DHZ=$<TARGET_FILE:hz>"+ "-DFIXTURE_DIR=${CMAKE_CURRENT_SOURCE_DIR}/tests/lsp"+ "-DREQUEST_FILE=${CMAKE_CURRENT_BINARY_DIR}/lsp-test.input"+ "-DOUTPUT=${CMAKE_CURRENT_BINARY_DIR}/lsp-test.output"+ -P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/run_lsp_test.cmake") add_custom_target(check-samples COMMAND "${CMAKE_CTEST_COMMAND}" --output-on-failure--- /dev/null+++ b/cmake/run_format_test.cmake@@ -0,0 +1,48 @@+if(NOT DEFINED HZ OR NOT DEFINED SOURCE OR NOT DEFINED EXPECTED OR NOT DEFINED OUTPUT)+ message(FATAL_ERROR "HZ, SOURCE, EXPECTED, and OUTPUT are required")+endif()++execute_process(+ COMMAND "${HZ}" fmt "${SOURCE}"+ OUTPUT_FILE "${OUTPUT}"+ RESULT_VARIABLE result+ ERROR_VARIABLE error)+if(NOT result EQUAL 0)+ message(FATAL_ERROR "hz fmt failed: ${error}")+endif()++file(READ "${OUTPUT}" formatted)+file(READ "${EXPECTED}" expected)++if(NOT formatted STREQUAL expected)+ message(FATAL_ERROR "formatted output does not match expected output")+endif()++execute_process(+ COMMAND "${HZ}" fmt -check "${SOURCE}"+ RESULT_VARIABLE check_unformatted)+if(check_unformatted EQUAL 0)+ message(FATAL_ERROR "hz fmt -check accepted an unformatted file")+endif()++execute_process(+ COMMAND "${HZ}" fmt -check "${EXPECTED}"+ RESULT_VARIABLE check_formatted)+if(NOT check_formatted EQUAL 0)+ message(FATAL_ERROR "hz fmt -check rejected an already formatted file")+endif()++set(copy_path "${OUTPUT}.write.hz")+configure_file("${SOURCE}" "${copy_path}" COPYONLY)+execute_process(+ COMMAND "${HZ}" fmt -w "${copy_path}"+ RESULT_VARIABLE write_result+ ERROR_VARIABLE write_error)+if(NOT write_result EQUAL 0)+ message(FATAL_ERROR "hz fmt -w failed: ${write_error}")+endif()++file(READ "${copy_path}" rewritten)+if(NOT rewritten STREQUAL expected)+ message(FATAL_ERROR "hz fmt -w did not write the expected output")+endif()--- /dev/null+++ b/cmake/run_lsp_test.cmake@@ -0,0 +1,66 @@+if(NOT DEFINED HZ OR NOT DEFINED FIXTURE_DIR OR NOT DEFINED REQUEST_FILE OR NOT DEFINED OUTPUT)+ message(FATAL_ERROR "HZ, FIXTURE_DIR, REQUEST_FILE, and OUTPUT are required")+endif()++file(READ "${FIXTURE_DIR}/main.hz" source)+set(text "${source}fn probe() { seq:: }\n")+string(REPLACE "\\" "\\\\" text_json "${text}")+string(REPLACE "\"" "\\\"" text_json "${text_json}")+string(REPLACE "\n" "\\n" text_json "${text_json}")+string(REPLACE "\r" "\\r" text_json "${text_json}")++file(TO_CMAKE_PATH "${FIXTURE_DIR}/main.hz" main_path)+set(main_uri "file://${main_path}")++set(messages "")++macro(add_frame json)+ string(LENGTH "${json}" length)+ string(APPEND messages "Content-Length: ${length}\r\n\r\n${json}")+endmacro()++add_frame("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"rootUri\":\"file://${FIXTURE_DIR}\",\"capabilities\":{}}}")+add_frame("{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}")+add_frame("{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didOpen\",\"params\":{\"textDocument\":{\"uri\":\"${main_uri}\",\"languageId\":\"haze\",\"version\":1,\"text\":\"${text_json}\"}}}")++add_frame("{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"textDocument/completion\",\"params\":{\"textDocument\":{\"uri\":\"${main_uri}\"},\"position\":{\"line\":9,\"character\":18}}}")+add_frame("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"textDocument/completion\",\"params\":{\"textDocument\":{\"uri\":\"${main_uri}\"},\"position\":{\"line\":2,\"character\":27}}}")+add_frame("{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"textDocument/signatureHelp\",\"params\":{\"textDocument\":{\"uri\":\"${main_uri}\"},\"position\":{\"line\":6,\"character\":19}}}")+add_frame("{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"textDocument/signatureHelp\",\"params\":{\"textDocument\":{\"uri\":\"${main_uri}\"},\"position\":{\"line\":7,\"character\":17}}}")+add_frame("{\"jsonrpc\":\"2.0\",\"id\":6,\"method\":\"textDocument/hover\",\"params\":{\"textDocument\":{\"uri\":\"${main_uri}\"},\"position\":{\"line\":7,\"character\":12}}}")+add_frame("{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"textDocument/definition\",\"params\":{\"textDocument\":{\"uri\":\"${main_uri}\"},\"position\":{\"line\":6,\"character\":15}}}")+add_frame("{\"jsonrpc\":\"2.0\",\"id\":8,\"method\":\"shutdown\",\"params\":null}")+add_frame("{\"jsonrpc\":\"2.0\",\"method\":\"exit\",\"params\":null}")++file(WRITE "${REQUEST_FILE}" "${messages}")++execute_process(+ COMMAND "${HZ}" lsp+ INPUT_FILE "${REQUEST_FILE}"+ OUTPUT_FILE "${OUTPUT}"+ RESULT_VARIABLE result+ ERROR_VARIABLE error+ TIMEOUT 20)+if(NOT result EQUAL 0)+ message(FATAL_ERROR "hz lsp failed: ${error}")+endif()++file(READ "${OUTPUT}" response)++foreach(needle+ "\"completionProvider\""+ "\"signatureHelpProvider\""+ "\"hoverProvider\":true"+ "\"definitionProvider\":true"+ "\"detail\":\"fn range(a i32, b i32) list[i32]\""+ "\"label\":\"left\""+ "\"label\":\"right\""+ "\"signatures\""+ "\"activeParameter\":0"+ "fn helper(p Pair) i32"+ "seq.hz")+ string(FIND "${response}" "${needle}" position)+ if(position EQUAL -1)+ message(FATAL_ERROR "LSP response did not contain ${needle}\n${response}")+ endif()+endforeach()--- /dev/null+++ b/samples/baseline_2.6/a/b/c/deeper.hz@@ -0,0 +1,4 @@+use ../deep {deep_value}+use ../../../modules/some_module {ROOT}++pub fn deeper_value() i32 => deep_value() + ROOT--- /dev/null+++ b/samples/baseline_2.6/a/b/deep.hz@@ -0,0 +1,5 @@+use ../../modules/some_module {root_value, root_double}+use ../some_less_nested_module+use ../../path/to/more/nested/module {nested_value}++pub fn deep_value() i32 => root_double(less_nested_value()) + nested_value() + root_value()--- /dev/null+++ b/samples/baseline_2.6/a/some_less_nested_module.hz@@ -0,0 +1,1 @@+pub fn less_nested_value() i32 => 10--- /dev/null+++ b/samples/baseline_2.6/main.hz@@ -0,0 +1,11 @@+// Deep and relative module paths.++use a/b/c/deeper {deeper_value}+use path/to/more/nested/module {nested_value}+use whatever/some_mod++fn main() {+ print(deeper_value())+ print(nested_value())+ print(some_value())+}--- /dev/null+++ b/samples/baseline_2.6/modules/some_module.hz@@ -0,0 +1,5 @@+pub const ROOT i32 = 5++pub fn root_value() i32 => ROOT++pub pure fn root_double(x i32) i32 => x * 2--- /dev/null+++ b/samples/baseline_2.6/nested_missing_module_error.hz@@ -0,0 +1,7 @@+// A missing module in a deeply nested path should fail cleanly.++use a/b/c/does_not_exist++fn main() {+ print(1)+}--- /dev/null+++ b/samples/baseline_2.6/path/to/more/nested/module.hz@@ -0,0 +1,1 @@+pub fn nested_value() i32 => 30--- /dev/null+++ b/samples/baseline_2.6/whatever/some_mod.hz@@ -0,0 +1,1 @@+pub fn some_value() i32 => 40--- a/src/driver.cpp+++ b/src/driver.cpp@@ -41,6 +41,8 @@ bool verbose = false; bool dynamic = false; bool release = false;+ bool format_write = false;+ bool format_check = false; }; void usage(FILE* f) {@@ -55,11 +57,17 @@ " -run run the produced executable\n" " -d link dynamically (default is static)\n" " -release omit runtime contract and invariant checks\n"+ " -w write formatted output back to the file\n"+ " -check fail if the file is not formatted\n" " -keep keep temporary files\n" " -cc path C compiler used for assembly/linking\n" " -runtime path path to libhazert.a\n" " -v print version\n"- " -h print this help\n");+ " -h print this help\n"+ "\n"+ "subcommands:\n"+ " hz fmt file.hz pretty-print a source file\n"+ " hz lsp run the language server on stdio\n"); } std::string lower(std::string s) {@@ -368,6 +376,14 @@ } if (a == "-keep") { opt.keep = true;+ continue;+ }+ if (a == "-w") {+ opt.format_write = true;+ continue;+ }+ if (a == "-check") {+ opt.format_check = true; continue; } if (a == "-verbose") {@@ -415,6 +431,42 @@ if (!positional.empty()) { const std::string& first = positional.front();+ if (first == "lsp") {+ if (positional.size() != 1) {+ std::fprintf(stderr, "hz: lsp takes no arguments\n");+ return 2;+ }+ haze::run_lsp_server();+ return 0;+ }+ if (first == "fmt") {+ if (positional.size() != 2) {+ std::fprintf(stderr, "hz: fmt expects one .hz file\n");+ return 2;+ }+ try {+ fs::path path(positional[1]);+ if (!fs::is_regular_file(path))+ throw std::runtime_error("input file not found: " + path.string());+ std::string source = read_file(path);+ std::string formatted = haze::format_source(source);+ if (opt.format_check) {+ if (formatted != source) {+ std::fprintf(stderr, "hz: %s is not formatted\n", path.string().c_str());+ return 1;+ }+ return 0;+ }+ if (opt.format_write)+ write_file(path, formatted);+ else+ std::fwrite(formatted.data(), 1, formatted.size(), stdout);+ return 0;+ } catch (const std::exception& e) {+ std::fprintf(stderr, "hz: %s\n", e.what());+ return 1;+ }+ } if (first == "build" || first == "check" || first == "run" || first == "qbe" || first == "asm" || first == "compile") { if (first == "run")--- /dev/null+++ b/src/formatter.cpp@@ -0,0 +1,504 @@+#include "haze.h"++#include <algorithm>+#include <cctype>+#include <string>+#include <vector>++namespace haze {++namespace {++struct FmtToken {+ enum class Kind { Word, Number, String, Comment, Op, Punct, Raw };+ Kind kind = Kind::Punct;+ std::string text;+};++struct FmtLine {+ std::vector<FmtToken> tokens;+ bool raw = false;+ bool removed = false;+};++bool is_wordlike(const FmtToken& t) {+ return t.kind == FmtToken::Kind::Word || t.kind == FmtToken::Kind::Number ||+ t.kind == FmtToken::Kind::String;+}++bool is_operator(const std::string& s) {+ static const std::vector<std::string> ops = {+ "=>", "==", "!=", "<=", ">=", "&&", "||", "=", "+=", "-=", "*=", "/=",+ "%=", "+", "-", "*", "/", "%", "<", ">", "..", "++", "--"};+ for (auto& op : ops)+ if (s == op)+ return true;+ return false;+}++bool is_control_keyword(const std::string& s) {+ return s == "if" || s == "else" || s == "for" || s == "while" || s == "match" ||+ s == "return";+}++std::string rstrip(std::string s) {+ while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\r'))+ s.pop_back();+ return s;+}++std::string lstrip(const std::string& s) {+ size_t i = 0;+ while (i < s.size() && (s[i] == ' ' || s[i] == '\t'))+ i++;+ return s.substr(i);+}++bool starts_with(const std::string& s, const std::string& prefix) {+ return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0;+}++std::vector<std::string> split_lines(const std::string& src) {+ std::vector<std::string> lines;+ std::string cur;+ for (char c : src) {+ if (c == '\n') {+ lines.push_back(cur);+ cur.clear();+ } else {+ cur.push_back(c);+ }+ }+ lines.push_back(cur);+ return lines;+}++std::vector<FmtToken> tokenize_line(const std::string& line, bool& block_comment,+ bool& multiline_string) {+ std::vector<FmtToken> out;+ size_t i = 0;+ while (i < line.size()) {+ char c = line[i];+ if (c == ' ' || c == '\t' || c == '\r') {+ i++;+ continue;+ }+ if (c == '\\' && i + 1 < line.size() && line[i + 1] == '\\') {+ out.push_back(FmtToken{FmtToken::Kind::String, line.substr(i)});+ multiline_string = true;+ break;+ }+ if (c == '/' && i + 1 < line.size() && line[i + 1] == '/') {+ out.push_back(FmtToken{FmtToken::Kind::Comment, line.substr(i)});+ break;+ }+ if (c == '/' && i + 1 < line.size() && line[i + 1] == '*') {+ size_t end = line.find("*/", i + 2);+ if (end == std::string::npos) {+ out.push_back(FmtToken{FmtToken::Kind::Comment, line.substr(i)});+ block_comment = true;+ break;+ }+ out.push_back(FmtToken{FmtToken::Kind::Comment, line.substr(i, end + 2 - i)});+ i = end + 2;+ continue;+ }+ if (c == '"') {+ size_t start = i++;+ while (i < line.size()) {+ if (line[i] == '\\' && i + 1 < line.size()) {+ i += 2;+ continue;+ }+ if (line[i] == '"') {+ i++;+ break;+ }+ i++;+ }+ out.push_back(FmtToken{FmtToken::Kind::String, line.substr(start, i - start)});+ continue;+ }+ if (std::isalpha(static_cast<unsigned char>(c)) || c == '_') {+ size_t start = i++;+ while (i < line.size() &&+ (std::isalnum(static_cast<unsigned char>(line[i])) || line[i] == '_'))+ i++;+ out.push_back(FmtToken{FmtToken::Kind::Word, line.substr(start, i - start)});+ continue;+ }+ if (std::isdigit(static_cast<unsigned char>(c))) {+ size_t start = i++;+ while (i < line.size() &&+ (std::isalnum(static_cast<unsigned char>(line[i])) || line[i] == '_'))+ i++;+ out.push_back(FmtToken{FmtToken::Kind::Number, line.substr(start, i - start)});+ continue;+ }+ static const char* multi[] = {"=>", "==", "!=", "<=", ">=", "&&", "||",+ "+=", "-=", "*=", "/=", "%=", "++", "--",+ "..", "::"};+ bool matched = false;+ for (auto op : multi) {+ size_t n = std::char_traits<char>::length(op);+ if (line.compare(i, n, op) == 0) {+ out.push_back(FmtToken{FmtToken::Kind::Op, op});+ i += n;+ matched = true;+ break;+ }+ }+ if (matched)+ continue;+ out.push_back(FmtToken{FmtToken::Kind::Punct, std::string(1, c)});+ i++;+ }+ return out;+}++std::vector<FmtLine> scan_lines(const std::string& src) {+ std::vector<std::string> raw = split_lines(src);+ std::vector<FmtLine> lines;+ bool block_comment = false;+ bool multiline_string = false;++ for (auto& source_line : raw) {+ FmtLine line;+ std::string text = rstrip(source_line);+ std::string trimmed = lstrip(text);++ if (block_comment) {+ line.raw = true;+ line.tokens.push_back(FmtToken{FmtToken::Kind::Raw, trimmed});+ if (trimmed.find("*/") != std::string::npos)+ block_comment = false;+ lines.push_back(std::move(line));+ continue;+ }++ if (multiline_string) {+ if (starts_with(trimmed, "\\\\")) {+ line.raw = true;+ line.tokens.push_back(FmtToken{FmtToken::Kind::Raw, trimmed});+ lines.push_back(std::move(line));+ continue;+ }+ multiline_string = false;+ }++ if (starts_with(trimmed, "\\\\")) {+ multiline_string = true;+ line.raw = true;+ line.tokens.push_back(FmtToken{FmtToken::Kind::Raw, trimmed});+ lines.push_back(std::move(line));+ continue;+ }++ line.tokens = tokenize_line(text, block_comment, multiline_string);+ lines.push_back(std::move(line));+ }+ return lines;+}++bool line_starts_with(const FmtLine& line, const std::string& text) {+ for (auto& t : line.tokens) {+ if (t.kind == FmtToken::Kind::Comment)+ return false;+ return t.text == text;+ }+ return false;+}++size_t last_code_index(const FmtLine& line) {+ for (size_t i = line.tokens.size(); i > 0; i--)+ if (line.tokens[i - 1].kind != FmtToken::Kind::Comment)+ return i - 1;+ return line.tokens.size();+}++bool has_code(const FmtLine& line) {+ for (auto& t : line.tokens)+ if (t.kind != FmtToken::Kind::Comment)+ return true;+ return false;+}++void join_open_braces(std::vector<FmtLine>& lines) {+ for (size_t i = 1; i < lines.size(); i++) {+ if (lines[i].raw || lines[i].removed)+ continue;+ size_t code_count = 0;+ size_t code_index = 0;+ for (size_t k = 0; k < lines[i].tokens.size(); k++) {+ if (lines[i].tokens[k].kind == FmtToken::Kind::Comment)+ continue;+ code_count++;+ code_index = k;+ }+ if (code_count != 1 || lines[i].tokens[code_index].text != "{")+ continue;++ size_t prev = i;+ while (prev > 0 && (lines[prev - 1].removed || !has_code(lines[prev - 1])))+ prev--;+ if (prev == 0 || lines[prev - 1].removed)+ continue;+ if (line_starts_with(lines[prev - 1], ":"))+ continue;++ size_t insert_at = last_code_index(lines[prev - 1]);+ if (insert_at >= lines[prev - 1].tokens.size())+ lines[prev - 1].tokens.push_back(lines[i].tokens[code_index]);+ else+ lines[prev - 1].tokens.insert(lines[prev - 1].tokens.begin() + insert_at + 1,+ lines[i].tokens[code_index]);+ lines[i].removed = true;+ }+}++void join_else_lines(std::vector<FmtLine>& lines) {+ for (size_t i = 1; i < lines.size(); i++) {+ if (lines[i].raw || lines[i].removed || !line_starts_with(lines[i], "else"))+ continue;+ size_t prev = i;+ while (prev > 0 && (lines[prev - 1].removed || !has_code(lines[prev - 1])))+ prev--;+ if (prev == 0)+ continue;+ size_t last = last_code_index(lines[prev - 1]);+ if (last >= lines[prev - 1].tokens.size() ||+ lines[prev - 1].tokens[last].text != "}")+ continue;+ for (auto& t : lines[i].tokens)+ lines[prev - 1].tokens.push_back(t);+ lines[i].removed = true;+ }+}++bool line_is_chain_header(const FmtLine& line) {+ size_t i = 0;+ while (i < line.tokens.size() && line.tokens[i].kind == FmtToken::Kind::Word &&+ (line.tokens[i].text == "pub" || line.tokens[i].text == "pure"))+ i++;+ if (i >= line.tokens.size())+ return false;+ const std::string& word = line.tokens[i].text;+ return word == "fn" || word == "for" || word == "contract";+}++void move_braces_after_chains(std::vector<FmtLine>& lines) {+ for (size_t i = 0; i + 1 < lines.size(); i++) {+ if (lines[i].raw || lines[i].removed)+ continue;+ if (!line_is_chain_header(lines[i]))+ continue;++ size_t j = i + 1;+ while (j < lines.size() && !lines[j].raw && !lines[j].removed &&+ line_starts_with(lines[j], ":"))+ j++;+ if (j == i + 1)+ continue;++ FmtLine& last = lines[j - 1];+ size_t code = last_code_index(last);+ if (code >= last.tokens.size() || last.tokens[code].text != "{")+ continue;++ last.tokens.erase(last.tokens.begin() + code);+ FmtLine brace;+ brace.tokens.push_back(FmtToken{FmtToken::Kind::Punct, "{"});+ lines.insert(lines.begin() + j, std::move(brace));+ i = j;+ }+}++bool token_is_unary(const std::vector<FmtToken>& tokens, size_t i) {+ if (!tokens[i].text.empty() && tokens[i].text == "!")+ return true;+ if (tokens[i].text != "-")+ return false;+ if (i == 0)+ return true;+ const std::string& prev = tokens[i - 1].text;+ return is_operator(prev) || prev == "(" || prev == "[" || prev == "," || prev == ":" ||+ prev == "{" || prev == "return";+}++bool need_space(const std::vector<FmtToken>& tokens, size_t i) {+ const std::string& cur = tokens[i].text;+ const std::string& prev = tokens[i - 1].text;++ if (cur == "," || cur == ")" || cur == "]" || cur == "." || cur == "::")+ return false;+ if (prev == "(" || prev == "[" || prev == "." || prev == "::")+ return false;+ if (cur == ":")+ return false;+ if (prev == ":")+ return true;+ if (cur == "(")+ return is_control_keyword(prev);+ if (cur == "[")+ return !(is_wordlike(tokens[i - 1]) || prev == ")" || prev == "]");+ if (cur == "{")+ return prev != "{";+ if (cur == "}")+ return prev != "{";+ if (prev == "{")+ return cur != "}";+ if (prev == ",")+ return true;+ if (cur == ".." || prev == "..")+ return false;+ if (cur == "++" || cur == "--" || prev == "++" || prev == "--")+ return false;+ if (is_operator(cur) || is_operator(prev)) {+ if (is_operator(prev) && token_is_unary(tokens, i - 1))+ return false;+ return true;+ }+ return true;+}++std::string format_tokens(const std::vector<FmtToken>& tokens) {+ std::string code;+ size_t i = 0;+ for (; i < tokens.size(); i++) {+ if (tokens[i].kind == FmtToken::Kind::Comment) {+ if (!code.empty())+ code += " ";+ code += tokens[i].text;+ i++;+ break;+ }+ if (!code.empty() && need_space(tokens, i))+ code += ' ';+ code += tokens[i].text;+ }+ for (; i < tokens.size(); i++) {+ if (tokens[i].kind == FmtToken::Kind::Comment) {+ if (!code.empty())+ code += " ";+ code += tokens[i].text;+ }+ }+ return code;+}++std::string indent(int depth) {+ return std::string(static_cast<size_t>(depth < 0 ? 0 : depth) * 4, ' ');+}++} // namespace++std::string format_source(const std::string& source) {+ std::vector<FmtLine> lines = scan_lines(source);++ join_open_braces(lines);+ join_else_lines(lines);+ move_braces_after_chains(lines);++ std::vector<std::string> output;+ int depth = 0;+ int bracket_depth = 0;+ bool previous_blank = false;++ for (auto& line : lines) {+ if (line.removed)+ continue;++ bool blank = false;+ if (line.raw) {+ blank = line.tokens.empty() || line.tokens[0].text.empty();+ } else {+ blank = !has_code(line) &&+ std::none_of(line.tokens.begin(), line.tokens.end(),+ [](const FmtToken& t) {+ return t.kind == FmtToken::Kind::Comment;+ });+ }+ if (blank) {+ if (!output.empty() && !previous_blank) {+ output.push_back("");+ previous_blank = true;+ }+ continue;+ }+ previous_blank = false;++ if (line.raw) {+ std::string text = line.tokens.empty() ? "" : line.tokens[0].text;+ output.push_back(rstrip(indent(depth) + text));+ continue;+ }++ int leading_closers = 0;+ size_t first_code = 0;+ bool have_first = false;+ for (size_t k = 0; k < line.tokens.size(); k++) {+ if (line.tokens[k].kind == FmtToken::Kind::Comment)+ break;+ if (!have_first) {+ first_code = k;+ have_first = true;+ }+ if (line.tokens[k].text == "}") {+ leading_closers++;+ continue;+ }+ break;+ }++ int continuation = 0;+ if (have_first) {+ const std::string& first = line.tokens[first_code].text;+ if (bracket_depth > 0 && first != ")" && first != "]")+ continuation = 1;+ if (first == "." || first == "::" || is_operator(first))+ continuation = 1;+ }++ int line_depth = depth - leading_closers + continuation;+ if (line_depth < 0)+ line_depth = 0;+ if (line_starts_with(line, ":"))+ line_depth = depth + 1;++ std::string text = format_tokens(line.tokens);+ output.push_back(rstrip(indent(line_depth) + text));++ for (auto& t : line.tokens)+ if (t.kind != FmtToken::Kind::Comment) {+ if (t.text == "{")+ depth++;+ else if (t.text == "}")+ depth--;+ else if (t.text == "(" || t.text == "[")+ bracket_depth++;+ else if (t.text == ")" || t.text == "]")+ bracket_depth--;+ }+ if (depth < 0)+ depth = 0;+ if (bracket_depth < 0)+ bracket_depth = 0;+ }++ while (!output.empty() && output.back().empty())+ output.pop_back();++ if (output.empty())+ return "";++ std::string result;+ for (size_t i = 0; i < output.size(); i++) {+ if (i)+ result.push_back('\n');+ result += output[i];+ }+ result.push_back('\n');+ return result;+}++} // namespace haze--- a/src/haze.h+++ b/src/haze.h@@ -290,7 +290,9 @@ Program load_program(const std::string& entry_path); void check_program(Program& program); void fold_program(Program& program);+std::string format_source(const std::string& source); std::string generate_qbe(Program& program, const std::string& source_name);+void run_lsp_server(); struct FuncSig { TypePtr ret;--- /dev/null+++ b/src/lsp.cpp@@ -0,0 +1,1288 @@+#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--- a/src/module.cpp+++ b/src/module.cpp@@ -481,8 +481,31 @@ Program load_program(const std::string& entry_path) { std::unordered_map<std::string, ModuleCtx> modules; std::vector<std::string> order;- std::deque<std::string> pending;- fs::path entry_file = fs::absolute(entry_path);++ struct Pending {+ fs::path path;+ std::string name;+ Pos pos;+ };+ std::deque<Pending> pending;++ std::error_code ec;+ fs::path entry_file = fs::weakly_canonical(fs::absolute(entry_path), ec);+ if (ec)+ entry_file = fs::absolute(entry_path);+ fs::path entry_dir = entry_file.parent_path();++ auto module_name = [&](const fs::path& resolved) {+ std::error_code rel_ec;+ fs::path rel = fs::relative(resolved, entry_dir, rel_ec);+ if (rel_ec)+ rel = resolved.filename();+ rel.replace_extension();+ std::string name = rel.generic_string();+ if (name.empty())+ name = resolved.stem().string();+ return name;+ }; auto load = [&](const fs::path& path, const std::string& name, bool entry) { ModuleCtx ctx;@@ -493,21 +516,29 @@ ctx.program.module = name; modules.emplace(name, std::move(ctx)); order.push_back(name);- for (auto& use : modules[name].program.uses)- pending.push_back(use.module);++ for (auto& use : modules[name].program.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");+ std::string dep_name = module_name(target);+ use.module = dep_name;+ pending.push_back(Pending{target, dep_name, use.pos});+ } }; load(entry_file, entry_file.stem().string(), true); while (!pending.empty()) {- std::string name = pending.front();+ Pending p = std::move(pending.front()); pending.pop_front();- if (modules.count(name))+ if (modules.count(p.name)) continue;- fs::path path = entry_file.parent_path() / (name + ".hz");- if (!fs::is_regular_file(path))- throw Error(Pos{}, "cannot find module '" + name + "'");- load(path, name, false);+ if (!fs::is_regular_file(p.path))+ throw Error(p.pos, "cannot find module '" + p.name + "'");+ load(p.path, p.name, false); } std::unordered_map<std::string, ModuleCtx*> by_name;--- a/src/parser.cpp+++ b/src/parser.cpp@@ -242,7 +242,25 @@ expect_ident("use"); Use u; u.pos = p;- u.module = expect_ident("module name");+ if (at(Tok::DotDot)) {+ u.module = "..";+ advance();+ } else if (match(Tok::Dot)) {+ u.module = ".";+ } else {+ u.module = expect_ident("module name");+ }+ while (match(Tok::Slash)) {+ u.module += "/";+ if (at(Tok::DotDot)) {+ u.module += "..";+ advance();+ } else if (match(Tok::Dot)) {+ u.module += ".";+ } else {+ u.module += expect_ident("module path component");+ }+ } if (match(Tok::LBrace)) { while (!at(Tok::RBrace)) { u.names.push_back(expect_ident("imported name"));--- /dev/null+++ b/tests/format/expected.hz@@ -0,0 +1,48 @@+fn some_func() {+ var x i32 = 20+ var y i64 = cast[i64](x)+ print(y)+}++contract Positive(n i32) {+ pre n > 0+}++fn classify(n i32) i32+ : Positive(n)+ : post r => r >= 0+{+ if n > 0 {+ return n+ } else {+ return 0+ }+}++fn main() {+ var total = 0+ for i in 0..3+ : invariant total >= 0+ {+ total += i+ }+ print(total)+}++fn chain(xs list[i32]) i32 {+ var total = 0+ for x in xs+ : invariant total >= 0+ {+ total += x+ }+ const ys = [+ 1,+ 2,+ ]+ return -1+}++fn allman(n i32) i32 {+ return n+}--- /dev/null+++ b/tests/format/unformatted.hz@@ -0,0 +1,49 @@+fn some_func ( ) {+var x i32=20 + var y i64 = cast[i64](x)+print(y) +}++contract Positive(n i32){+pre n>0+}++fn classify ( n i32 ) i32+ : Positive(n)+ : post r=>r>=0 {+ if n>0 {+ return n+ }+ else {+ return 0+ }+}++fn main(){+var total=0+for i in 0..3+ : invariant total>=0+{+total+=i+}+print(total)+}++fn chain ( xs list[i32] ) i32 {+var total=0+for x in xs+ : invariant total>=0+{+total+=x+}+const ys=[+1,+2,+]+return -1+}++fn allman ( n i32 ) i32+{+return n+}--- /dev/null+++ b/tests/lsp/main.hz@@ -0,0 +1,9 @@+use seq {range, Pair}++fn helper(p Pair) i32 => p.left + p.right++fn main() {+ var p Pair = Pair{ left = 1, right = 2 }+ var xs = range(1, 10)+ print(helper(p))+}--- /dev/null+++ b/tests/lsp/seq.hz@@ -0,0 +1,8 @@+pub fn range(a i32, b i32) list[i32] => [a, b]++pub pure fn double(x i32) i32 => x * 2++pub type Pair {+ left i32+ right i32+}