navid/haze / commit
29e7ef5e690b
Navid M <navidmomtahen@gmail.com> · 2026-12-02
parents: 94d8e2a02684
Browse files at this commit · Download source
--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -98,6 +98,7 @@ VERBATIM) add_executable(hz+ src/cfg.cpp src/codegen.cpp src/driver.cpp src/eval.cpp@@ -184,6 +185,9 @@ "${CMAKE_CURRENT_SOURCE_DIR}/samples/baseline_2.8/*.hz") file(GLOB baseline_29_samples CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/samples/baseline_2.9/*.hz")+file(GLOB baseline_3_language_samples CONFIGURE_DEPENDS+ "${CMAKE_CURRENT_SOURCE_DIR}/samples/baseline_3/runes*.hz"+ "${CMAKE_CURRENT_SOURCE_DIR}/samples/baseline_3/cfg*.hz") list(SORT baseline_samples) list(SORT baseline_21_samples) list(SORT baseline_22_samples)@@ -194,10 +198,12 @@ list(SORT baseline_27_samples) list(SORT baseline_28_samples) list(SORT baseline_29_samples)+list(SORT baseline_3_language_samples) foreach(source IN LISTS baseline_samples baseline_21_samples baseline_22_samples baseline_23_samples baseline_24_samples baseline_25_samples baseline_26_samples- baseline_27_samples baseline_28_samples baseline_29_samples)+ baseline_27_samples baseline_28_samples baseline_29_samples+ baseline_3_language_samples) add_haze_sample_test("${source}") endforeach() add_haze_sample_test("${CMAKE_CURRENT_SOURCE_DIR}/samples/baseline_2/main.hz")--- a/TODO.md+++ b/TODO.md@@ -1,6 +1,6 @@ - [x] General user-defined generic type declarations (type Map[K, V] ...) - [x] u8/u16/u32/u64, bitwise operators, f64, bytes, UTF-8 string operations-- [ ] @cfg conditional compilation+- [x] @cfg conditional compilation - [ ] extern (C) functions and C-layout extern type - [ ] String interpolation and format specs - [ ] hazelib standard library modules and native OS bindings--- a/runtime/hazert.cpp+++ b/runtime/hazert.cpp@@ -1619,6 +1619,262 @@ void* haze_bytes_ptr(void* object) { return haze_bytes_data(object);+}++static void* haze_result_ok_w(uint32_t value) {+ uint8_t* object = static_cast<uint8_t*>(haze_alloc_slow(16, 0));+ *reinterpret_cast<uint32_t*>(object + 8) = 0;+ *reinterpret_cast<uint32_t*>(object + 16) = value;+ return object;+}++static void* haze_result_ok_l(uint64_t value) {+ uint8_t* object = static_cast<uint8_t*>(haze_alloc_slow(16, 0));+ *reinterpret_cast<uint32_t*>(object + 8) = 0;+ *reinterpret_cast<uint64_t*>(object + 16) = value;+ return object;+}++static void* haze_result_error(uint32_t tag) {+ uint8_t* object = static_cast<uint8_t*>(haze_alloc_slow(16, 0));+ *reinterpret_cast<uint32_t*>(object + 8) = 1;+ *reinterpret_cast<uint32_t*>(object + 16) = tag;+ return object;+}++static bool haze_valid_scalar(uint32_t cp) {+ return cp <= 0x10ffff && !(cp >= 0xd800 && cp <= 0xdfff);+}++static bool haze_utf8_next(const uint8_t* s, size_t len, size_t& index, uint32_t& cp) {+ if (index >= len)+ return false;+ uint8_t b0 = s[index];+ if (b0 < 0x80) {+ cp = b0;+ index += 1;+ return true;+ }+ int extra = 0;+ uint32_t value = 0;+ uint32_t minimum = 0;+ if (b0 >= 0xc2 && b0 <= 0xdf) {+ extra = 1;+ value = b0 & 0x1f;+ minimum = 0x80;+ } else if (b0 >= 0xe0 && b0 <= 0xef) {+ extra = 2;+ value = b0 & 0x0f;+ minimum = 0x800;+ } else if (b0 >= 0xf0 && b0 <= 0xf4) {+ extra = 3;+ value = b0 & 0x07;+ minimum = 0x10000;+ } else {+ return false;+ }+ if (index + static_cast<size_t>(extra) >= len)+ return false;+ for (int i = 1; i <= extra; i++) {+ uint8_t b = s[index + static_cast<size_t>(i)];+ if ((b & 0xc0) != 0x80)+ return false;+ value = (value << 6) | (b & 0x3f);+ }+ if (value < minimum || !haze_valid_scalar(value))+ return false;+ cp = value;+ index += static_cast<size_t>(extra + 1);+ return true;+}++void* haze_rune_from_u32(uint32_t value) {+ if (!haze_valid_scalar(value))+ return haze_result_error(0);+ return haze_result_ok_w(value);+}++uint32_t haze_rune_to_u32(uint32_t rune) {+ return rune;+}++void* haze_str_rune_count(const char* text) {+ if (!text)+ return haze_result_ok_l(0);+ const uint8_t* s = reinterpret_cast<const uint8_t*>(text);+ size_t len = std::strlen(text);+ size_t index = 0;+ uint64_t count = 0;+ while (index < len) {+ uint32_t cp = 0;+ if (!haze_utf8_next(s, len, index, cp))+ return haze_result_error(0);+ count++;+ }+ return haze_result_ok_l(count);+}++uint64_t haze_str_rune_count_lossy(const char* text) {+ if (!text)+ return 0;+ const uint8_t* s = reinterpret_cast<const uint8_t*>(text);+ size_t len = std::strlen(text);+ size_t index = 0;+ uint64_t count = 0;+ while (index < len) {+ uint32_t cp = 0;+ if (!haze_utf8_next(s, len, index, cp))+ index++;+ count++;+ }+ return count;+}++void* haze_str_rune_at(const char* text, uint64_t target) {+ if (!text)+ return haze_result_error(1);+ const uint8_t* s = reinterpret_cast<const uint8_t*>(text);+ size_t len = std::strlen(text);+ size_t index = 0;+ uint64_t ordinal = 0;+ while (index < len) {+ uint32_t cp = 0;+ if (!haze_utf8_next(s, len, index, cp))+ return haze_result_error(0);+ if (ordinal == target)+ return haze_result_ok_w(cp);+ ordinal++;+ }+ return haze_result_error(1);+}++static void* haze_rune_list(const uint8_t* s, size_t len, bool lossy) {+ if (lossy) {+ uint64_t count = 0;+ size_t index = 0;+ while (index < len) {+ uint32_t cp = 0;+ if (!haze_utf8_next(s, len, index, cp))+ index++;+ count++;+ }+ uint8_t* list = static_cast<uint8_t*>(+ haze_alloc_slow(static_cast<uint32_t>(8 + count * 4), 0));+ *reinterpret_cast<uint32_t*>(list + 8) = static_cast<uint32_t>(count);+ index = 0;+ uint32_t slot = 0;+ while (index < len) {+ uint32_t cp = 0;+ if (!haze_utf8_next(s, len, index, cp)) {+ cp = 0xfffd;+ index++;+ }+ *reinterpret_cast<uint32_t*>(list + 16 + slot * 4) = cp;+ slot++;+ }+ return list;+ }++ uint64_t count = 0;+ size_t index = 0;+ while (index < len) {+ uint32_t cp = 0;+ if (!haze_utf8_next(s, len, index, cp))+ return nullptr;+ count++;+ }+ uint8_t* list = static_cast<uint8_t*>(+ haze_alloc_slow(static_cast<uint32_t>(8 + count * 4), 0));+ *reinterpret_cast<uint32_t*>(list + 8) = static_cast<uint32_t>(count);+ index = 0;+ for (uint64_t i = 0; i < count; i++) {+ uint32_t cp = 0;+ haze_utf8_next(s, len, index, cp);+ *reinterpret_cast<uint32_t*>(list + 16 + i * 4) = cp;+ }+ return list;+}++void* haze_str_runes(const char* text) {+ const uint8_t* s = reinterpret_cast<const uint8_t*>(text ? text : "");+ size_t len = text ? std::strlen(text) : 0;+ void* list = haze_rune_list(s, len, false);+ if (!list)+ return haze_result_error(0);+ return haze_result_ok_l(reinterpret_cast<uint64_t>(list));+}++void* haze_str_runes_lossy(const char* text) {+ const uint8_t* s = reinterpret_cast<const uint8_t*>(text ? text : "");+ size_t len = text ? std::strlen(text) : 0;+ return haze_rune_list(s, len, true);+}++void* haze_str_slice_runes(const char* text, uint64_t start, uint64_t end) {+ const uint8_t* s = reinterpret_cast<const uint8_t*>(text ? text : "");+ size_t len = text ? std::strlen(text) : 0;+ size_t index = 0;+ uint64_t count = 0;+ while (index < len) {+ uint32_t cp = 0;+ if (!haze_utf8_next(s, len, index, cp))+ return haze_result_error(0);+ count++;+ }+ if (start > end || end > count)+ return haze_result_error(1);++ index = 0;+ uint64_t ordinal = 0;+ size_t begin_byte = 0;+ size_t end_byte = len;+ while (index < len) {+ if (ordinal == start)+ begin_byte = index;+ if (ordinal == end) {+ end_byte = index;+ break;+ }+ uint32_t cp = 0;+ haze_utf8_next(s, len, index, cp);+ ordinal++;+ }+ if (ordinal == start)+ begin_byte = index;+ if (ordinal == end)+ end_byte = index;+ return haze_result_ok_l(+ reinterpret_cast<uint64_t>(haze_str_slice(text ? text : "", begin_byte, end_byte)));+}++const char* haze_str_slice_runes_lossy(const char* text, uint64_t start, uint64_t end) {+ const uint8_t* s = reinterpret_cast<const uint8_t*>(text ? text : "");+ size_t len = text ? std::strlen(text) : 0;+ if (start > end)+ return "";+ size_t index = 0;+ uint64_t ordinal = 0;+ size_t begin_byte = len;+ size_t end_byte = len;+ while (index < len) {+ if (ordinal == start && begin_byte == len)+ begin_byte = index;+ if (ordinal == end) {+ end_byte = index;+ break;+ }+ uint32_t cp = 0;+ if (!haze_utf8_next(s, len, index, cp))+ index++;+ ordinal++;+ }+ if (ordinal == start && begin_byte == len)+ begin_byte = index;+ if (ordinal == end)+ end_byte = index;+ if (begin_byte > end_byte)+ begin_byte = end_byte;+ return haze_str_slice(text ? text : "", begin_byte, end_byte); } void haze_print_bool(int32_t value) {--- a/samples/baseline_2.9/bytes_strings.hz+++ b/samples/baseline_2.9/bytes_strings.hz@@ -1,7 +1,7 @@ // Managed bytes buffers and UTF-8 byte-oriented string operations. fn main() {- var buffer = bytes_new(4)+ var buffer = bytes::new(4) buffer[0] = 65 buffer[1] = 66 buffer[2] = 67@@ -10,22 +10,22 @@ print(buffer[0]) print(buffer[3]) - buffer = bytes_append(buffer, 69)+ buffer = bytes::append(buffer, 69) print(buffer.len)- print(bytes_to_str(buffer))+ print(bytes::to_str(buffer)) - var copy = bytes_from_str("hello")+ var copy = bytes::from_str("hello") print(copy.len) copy[0] = 72- print(bytes_to_str(copy))+ print(bytes::to_str(copy)) - var slice = bytes_slice(copy, 1, 4)- print(bytes_to_str(slice))+ var slice = bytes::slice(copy, 1, 4)+ print(bytes::to_str(slice)) var text = "hello" print(text.len) print(text[1]) print(text + " world")- print(str_slice(text, 1, 4))+ print(str::slice(text, 1, 4)) print(text == "hello") }--- /dev/null+++ b/samples/baseline_3/cfg.hz@@ -0,0 +1,38 @@+// Target-dependent items, statements, and expressions.++@cfg(family == unix)+fn platform_value() i32 => 1++@cfg(family == windows)+fn platform_value() i32 => 2++@cfg(any(os == linux, os == macos, os == freebsd, os == dragonflybsd,+ os == netbsd, os == openbsd, os == windows))+fn known_platform() i32 => 3++@cfg(not(os == windows))+const NOT_WINDOWS i32 = 4++@cfg(ptr_width == 64)+fn wide_pointer() i32 => 5++fn main() {+ print(platform_value())+ print(known_platform())+ print(wide_pointer())++ @cfg(family == unix) {+ print(10)+ print(NOT_WINDOWS)+ }++ @cfg(family == windows) {+ print(20)+ }++ const separator = @cfg {+ family == windows => "\\"+ family == unix => "/"+ }+ print(separator)+}--- /dev/null+++ b/samples/baseline_3/cfg_no_arm_error.hz@@ -0,0 +1,8 @@+// An expression-level @cfg must have a matching arm for the target.++fn main() {+ const value = @cfg {+ os == plan9 => 1+ }+ print(value)+}--- /dev/null+++ b/samples/baseline_3/cfg_non_bool_error.hz@@ -0,0 +1,8 @@+// A cfg condition must evaluate to a boolean.++@cfg(ptr_width)+fn bad() i32 => 1++fn main() {+ print(1)+}--- /dev/null+++ b/samples/baseline_3/runes.hz@@ -0,0 +1,46 @@+// Nominal rune values and strict/lossy UTF-8 decoding.++fn main() {+ const text = "aé日"+ print(text.len)++ match str::rune_count(text) {+ OK(count) => print(count)+ Error(err) => print(-1)+ }++ match str::rune_at(text, 2) {+ OK(r) => print(rune::to_u32(r))+ Error(err) => print(-2)+ }++ const lossy = str::runes_lossy("a\xFFb")+ print(lossy.len)+ print(rune::to_u32(lossy[0]))+ print(rune::to_u32(lossy[1]))+ print(rune::to_u32(lossy[2]))+ print(str::rune_count_lossy("a\xFFb"))++ match str::runes("a\xFFb") {+ OK(runes) => print(runes.len)+ Error(err) => match err {+ Utf8Error.InvalidEncoding => print(-3)+ Utf8Error.OutOfBounds => print(-4)+ }+ }++ match str::slice_runes(text, 1, 3) {+ OK(slice) => print(slice)+ Error(err) => print(-5)+ }+ print(str::slice_runes_lossy("a\xFFb", 1, 3))++ match rune::from_u32(0xD800) {+ OK(r) => print(1)+ Error(err) => print(-6)+ }+ match rune::from_u32(0x1F600) {+ OK(r) => print(rune::to_u32(r))+ Error(err) => print(-7)+ }+}--- /dev/null+++ b/samples/baseline_3/runes_error.hz@@ -0,0 +1,6 @@+// rune is nominal, not an integer alias.++fn main() {+ var r rune = 65+ print(rune::to_u32(r))+}--- /dev/null+++ b/src/cfg.cpp@@ -0,0 +1,237 @@+#include "haze.h"++#include <string>++namespace haze {++namespace {++TargetInfo g_target;+bool g_target_set = false;++struct CfgValue {+ enum class Kind { Bool, Int, String };+ Kind kind = Kind::Bool;+ bool boolean = false;+ long long integer = 0;+ std::string string;+};++CfgValue cfg_bool(bool v) {+ CfgValue c;+ c.kind = CfgValue::Kind::Bool;+ c.boolean = v;+ return c;+}++CfgValue cfg_int(long long v) {+ CfgValue c;+ c.kind = CfgValue::Kind::Int;+ c.integer = v;+ return c;+}++CfgValue cfg_string(std::string v) {+ CfgValue c;+ c.kind = CfgValue::Kind::String;+ c.string = std::move(v);+ return c;+}++CfgValue eval_cfg_expr(const Expr& e, const TargetInfo& target) {+ switch (e.kind) {+ case Expr::Kind::Bool:+ return cfg_bool(e.bval);+ case Expr::Kind::Int:+ return cfg_int(e.ival);+ case Expr::Kind::String:+ return cfg_string(e.text);+ case Expr::Kind::Var:+ if (e.text == "os")+ return cfg_string(target.os);+ if (e.text == "arch")+ return cfg_string(target.arch);+ if (e.text == "family")+ return cfg_string(target.family);+ if (e.text == "endian")+ return cfg_string(target.endian);+ if (e.text == "ptr_width")+ return cfg_int(target.ptr_width);+ if (e.text == "true")+ return cfg_bool(true);+ if (e.text == "false")+ return cfg_bool(false);+ return cfg_string(e.text);+ case Expr::Kind::Unary: {+ CfgValue value = eval_cfg_expr(*e.lhs, target);+ if (e.op == "!") {+ if (value.kind != CfgValue::Kind::Bool)+ throw Error(e.pos, "cfg '!' requires a boolean");+ return cfg_bool(!value.boolean);+ }+ if (e.op == "-") {+ if (value.kind != CfgValue::Kind::Int)+ throw Error(e.pos, "cfg unary '-' requires an integer");+ return cfg_int(-value.integer);+ }+ throw Error(e.pos, "unsupported cfg unary operator '" + e.op + "'");+ }+ case Expr::Kind::Binary: {+ CfgValue a = eval_cfg_expr(*e.lhs, target);+ CfgValue b = eval_cfg_expr(*e.rhs, target);+ if (e.op == "&&" || e.op == "||") {+ if (a.kind != CfgValue::Kind::Bool || b.kind != CfgValue::Kind::Bool)+ throw Error(e.pos, "cfg logical operands must be boolean");+ return cfg_bool(e.op == "&&" ? (a.boolean && b.boolean)+ : (a.boolean || b.boolean));+ }+ if (e.op == "==" || e.op == "!=") {+ bool equal = false;+ if (a.kind == CfgValue::Kind::String && b.kind == CfgValue::Kind::String)+ equal = a.string == b.string;+ else if (a.kind == CfgValue::Kind::Int && b.kind == CfgValue::Kind::Int)+ equal = a.integer == b.integer;+ else if (a.kind == CfgValue::Kind::Bool && b.kind == CfgValue::Kind::Bool)+ equal = a.boolean == b.boolean;+ else+ throw Error(e.pos, "cfg comparison operands have different kinds");+ return cfg_bool(e.op == "==" ? equal : !equal);+ }+ if (a.kind == CfgValue::Kind::Int && b.kind == CfgValue::Kind::Int) {+ if (e.op == "<")+ return cfg_bool(a.integer < b.integer);+ if (e.op == "<=")+ return cfg_bool(a.integer <= b.integer);+ if (e.op == ">")+ return cfg_bool(a.integer > b.integer);+ if (e.op == ">=")+ return cfg_bool(a.integer >= b.integer);+ }+ throw Error(e.pos, "unsupported cfg condition operator '" + e.op + "'");+ }+ case Expr::Kind::Call: {+ if (e.lhs->kind != Expr::Kind::Var)+ throw Error(e.pos, "cfg call must be all(...), any(...), or not(...)");+ const std::string& name = e.lhs->text;+ if (name == "not") {+ if (e.args.size() != 1)+ throw Error(e.pos, "cfg not(...) expects one argument");+ CfgValue arg = eval_cfg_expr(*e.args[0], target);+ if (arg.kind != CfgValue::Kind::Bool)+ throw Error(e.pos, "cfg not(...) requires a boolean");+ return cfg_bool(!arg.boolean);+ }+ if (name == "all" || name == "any") {+ if (e.args.empty())+ throw Error(e.pos, "cfg " + name + "(...) requires arguments");+ bool result = name == "all";+ for (auto& arg : e.args) {+ CfgValue value = eval_cfg_expr(*arg, target);+ if (value.kind != CfgValue::Kind::Bool)+ throw Error(arg->pos, "cfg " + name + "(...) requires booleans");+ if (name == "all")+ result = result && value.boolean;+ else+ result = result || value.boolean;+ }+ return cfg_bool(result);+ }+ throw Error(e.pos, "unknown cfg predicate '" + name + "'");+ }+ default:+ throw Error(e.pos, "unsupported cfg expression");+ }+}++} // namespace++TargetInfo host_target() {+ TargetInfo target;+#if defined(_WIN32)+ target.os = "windows";+ target.family = "windows";+#elif defined(__APPLE__)+ target.os = "macos";+ target.family = "unix";+#elif defined(__FreeBSD__)+ target.os = "freebsd";+ target.family = "unix";+#elif defined(__DragonFly__)+ target.os = "dragonflybsd";+ target.family = "unix";+#elif defined(__OpenBSD__)+ target.os = "openbsd";+ target.family = "unix";+#elif defined(__NetBSD__)+ target.os = "netbsd";+ target.family = "unix";+#elif defined(__linux__)+ target.os = "linux";+ target.family = "unix";+#else+ target.os = "unknown";+ target.family = "unix";+#endif++#if defined(__x86_64__) || defined(_M_X64)+ target.arch = "x86_64";+#elif defined(__aarch64__) || defined(_M_ARM64)+ target.arch = "aarch64";+#elif defined(__riscv) && __riscv_xlen == 64+ target.arch = "riscv64";+#else+ target.arch = "unknown";+#endif++#if defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \+ __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__+ target.endian = "big";+#else+ target.endian = "little";+#endif++ target.ptr_width = static_cast<int>(sizeof(void*) * 8);+ return target;+}++TargetInfo target_for_qbe(const std::string& name) {+ TargetInfo target = host_target();+ if (name.rfind("amd64", 0) == 0)+ target.arch = "x86_64";+ else if (name.rfind("arm64", 0) == 0)+ target.arch = "aarch64";+ else if (name.rfind("rv64", 0) == 0)+ target.arch = "riscv64";+ if (name.find("apple") != std::string::npos) {+ target.os = "macos";+ target.family = "unix";+ } else if (name.find("win") != std::string::npos) {+ target.os = "windows";+ target.family = "windows";+ }+ target.endian = "little";+ target.ptr_width = 64;+ return target;+}++void set_compile_target(const TargetInfo& target) {+ g_target = target;+ g_target_set = true;+}++const TargetInfo& compile_target() {+ if (!g_target_set) {+ g_target = host_target();+ g_target_set = true;+ }+ return g_target;+}++bool eval_cfg_condition(const Expr& expr) {+ CfgValue value = eval_cfg_expr(expr, compile_target());+ if (value.kind != CfgValue::Kind::Bool)+ throw Error(expr.pos, "cfg condition must produce a boolean");+ return value.boolean;+}++} // namespace haze--- a/src/codegen.cpp+++ b/src/codegen.cpp@@ -84,6 +84,7 @@ class Gen { public: Gen(Program& p, std::string source_name) : program_(p), source_name_(std::move(source_name)) {+ types_["Utf8Error"] = t_utf8_error(); for (auto& t : program_.types) { types_[t->name] = t; if (t->kind == Type::Kind::Sum)@@ -1877,19 +1878,41 @@ return Value{}; }; - if (name == "bytes_new")+ if (name == "rune::from_u32")+ return call("haze_rune_from_u32", {t_u32()}, t_result(t_rune(), t_utf8_error()));+ if (name == "rune::to_u32")+ return call("haze_rune_to_u32", {t_rune()}, t_u32());+ if (name == "str::rune_count")+ return call("haze_str_rune_count", {t_str()}, t_result(t_u64(), t_utf8_error()));+ if (name == "str::rune_count_lossy")+ return call("haze_str_rune_count_lossy", {t_str()}, t_u64());+ if (name == "str::rune_at")+ return call("haze_str_rune_at", {t_str(), t_u64()},+ t_result(t_rune(), t_utf8_error()));+ if (name == "str::runes")+ return call("haze_str_runes", {t_str()},+ t_result(t_list(t_rune()), t_utf8_error()));+ if (name == "str::runes_lossy")+ return call("haze_str_runes_lossy", {t_str()}, t_list(t_rune()));+ if (name == "str::slice_runes")+ return call("haze_str_slice_runes", {t_str(), t_u64(), t_u64()},+ t_result(t_str(), t_utf8_error()));+ if (name == "str::slice_runes_lossy")+ return call("haze_str_slice_runes_lossy", {t_str(), t_u64(), t_u64()}, t_str());++ if (name == "bytes::new") return call("haze_bytes_new", {t_u64()}, t_bytes());- if (name == "bytes_from_str")+ if (name == "bytes::from_str") return call("haze_bytes_from_str", {t_str()}, t_bytes());- if (name == "bytes_to_str")+ if (name == "bytes::to_str") return call("haze_bytes_to_str", {t_bytes()}, t_str());- if (name == "bytes_append")+ if (name == "bytes::append") return call("haze_bytes_append", {t_bytes(), t_u8()}, t_bytes());- if (name == "bytes_slice")+ if (name == "bytes::slice") return call("haze_bytes_slice", {t_bytes(), t_u64(), t_u64()}, t_bytes());- if (name == "str_slice")+ if (name == "str::slice") return call("haze_str_slice", {t_str(), t_u64(), t_u64()}, t_str());- if (name == "bytes_ptr")+ if (name == "bytes::ptr") return call("haze_bytes_ptr", {t_bytes()}, t_ptr()); if (name == "print") {@@ -1906,6 +1929,8 @@ return call("haze_print_u64", {t_u64()}, t_void()); if (t->kind == Type::Kind::F64) return call("haze_print_f64", {t_f64()}, t_void());+ if (t->kind == Type::Kind::Rune)+ return call("haze_print_u32", {t_u32()}, t_void()); if (t->kind == Type::Kind::Bool) return call("haze_print_bool", {t_bool()}, t_void()); return call("haze_print_str", {t_str()}, t_void());--- a/src/driver.cpp+++ b/src/driver.cpp@@ -497,6 +497,8 @@ if (!qbe_target_supported(target.c_str())) throw std::runtime_error("unknown target '" + target + "'; supported: " + qbe_target_list());++ haze::set_compile_target(haze::target_for_qbe(target)); haze::Program program = haze::load_program(input.string()); program.release = opt.release;--- a/src/formatter.cpp+++ b/src/formatter.cpp@@ -357,6 +357,8 @@ const std::string& prev = tokens[i - 1].text; if (cur == "," || cur == ")" || cur == "]" || cur == "." || cur == "::")+ return false;+ if (prev == "@") return false; if (prev == "(" || prev == "[" || prev == "." || prev == "::") return false;--- a/src/haze.h+++ b/src/haze.h@@ -50,6 +50,7 @@ F64, Bool, Str,+ Rune, Ptr, Bytes, List,@@ -89,8 +90,10 @@ TypePtr t_f64(); TypePtr t_bool(); TypePtr t_str();+TypePtr t_rune(); TypePtr t_ptr(); TypePtr t_bytes();+TypePtr t_utf8_error(); TypePtr t_list(TypePtr elem); TypePtr t_record(const std::string& name); TypePtr t_sum(const std::string& name);@@ -108,6 +111,7 @@ bool is_signed_int(const TypePtr& t); bool is_unsigned_int(const TypePtr& t); bool is_float(const TypePtr& t);+bool is_rune(const TypePtr& t); bool is_narrow_int(const TypePtr& t); int int_rank(const TypePtr& t); long long truncate_int(long long v, const TypePtr& t);@@ -116,6 +120,22 @@ std::string type_name(const TypePtr& t); std::string qbe_type(const TypePtr& t); bool assignable(const TypePtr& to, const TypePtr& from);++struct Expr;++struct TargetInfo {+ std::string os = "linux";+ std::string arch = "x86_64";+ std::string family = "unix";+ std::string endian = "little";+ int ptr_width = 64;+};++TargetInfo host_target();+TargetInfo target_for_qbe(const std::string& target);+void set_compile_target(const TargetInfo& target);+const TargetInfo& compile_target();+bool eval_cfg_condition(const Expr& expr); enum class Tok { End,--- a/src/module.cpp+++ b/src/module.cpp@@ -210,6 +210,10 @@ std::string resolve_value_name(const std::string& name, Pos p) { if (local(name))+ return name;++ if (name.rfind("str::", 0) == 0 || name.rfind("bytes::", 0) == 0 ||+ name.rfind("rune::", 0) == 0) return name; std::string module;--- a/src/parser.cpp+++ b/src/parser.cpp@@ -15,6 +15,9 @@ Program program() { Program p; while (!at(Tok::End)) {+ ExprPtr cfg;+ if (at(Tok::At))+ cfg = parse_cfg_attribute(); bool pure = false; bool pub = false; for (;;) {@@ -28,28 +31,41 @@ break; } }+ if (!cfg && at(Tok::At))+ cfg = parse_cfg_attribute();+ bool enabled = !cfg || eval_cfg_condition(*cfg); if (is_ident("fn")) {- p.functions.push_back(parse_fn(pure, pub));+ auto fn = parse_fn(pure, pub);+ if (enabled)+ p.functions.push_back(std::move(fn)); continue; } if (is_ident("type")) {- p.types.push_back(parse_type_decl(pub));+ auto type = parse_type_decl(pub);+ if (enabled)+ p.types.push_back(std::move(type)); continue; } if (is_ident("const")) { if (pure) throw Error(cur().pos, "'pure' is only valid on functions");- p.globals.push_back(parse_global(pub));+ auto global = parse_global(pub);+ if (enabled)+ p.globals.push_back(std::move(global)); continue; } if (pure) throw Error(cur().pos, "expected 'fn' after modifier"); if (is_ident("contract")) {- p.contracts.push_back(parse_contract_decl(pub));+ auto contract = parse_contract_decl(pub);+ if (enabled)+ p.contracts.push_back(std::move(contract)); continue; } if (is_ident("use")) {- p.uses.push_back(parse_use());+ auto use = parse_use();+ if (enabled)+ p.uses.push_back(std::move(use)); continue; } if (is_ident("interface") || is_ident("trait") || is_ident("impl") ||@@ -145,6 +161,10 @@ return t_bool(); if (name == "str") return t_str();+ if (name == "rune")+ return t_rune();+ if (name == "Utf8Error")+ return t_utf8_error(); if (name == "ptr") return t_ptr(); if (name == "bytes")@@ -340,6 +360,43 @@ expect(Tok::Assign, "'=' in constant declaration"); g.expr = parse_expr(); return g;+ }++ ExprPtr parse_cfg_attribute() {+ Pos p = cur().pos;+ expect(Tok::At, "'@'");+ expect_ident("cfg");+ expect(Tok::LParen, "'(' after @cfg");+ ExprPtr cond = parse_expr();+ expect(Tok::RParen, "')' after cfg condition");+ if (!cond)+ throw Error(p, "empty cfg condition");+ return cond;+ }++ ExprPtr parse_cfg_value() {+ Pos p = cur().pos;+ expect(Tok::At, "'@'");+ expect_ident("cfg");+ expect(Tok::LBrace, "'{' after @cfg");+ struct Arm {+ ExprPtr condition;+ ExprPtr value;+ };+ std::vector<Arm> arms;+ while (!at(Tok::RBrace)) {+ if (at(Tok::End))+ throw Error(cur().pos, "unterminated @cfg expression");+ ExprPtr condition = parse_expr();+ expect(Tok::Arrow, "'=>' in @cfg arm");+ ExprPtr value = parse_expr();+ arms.push_back(Arm{std::move(condition), std::move(value)});+ }+ expect(Tok::RBrace, "'}' after @cfg arms");+ for (auto& arm : arms)+ if (eval_cfg_condition(*arm.condition))+ return std::move(arm.value);+ throw Error(p, "no @cfg arm matches the target"); } Use parse_use() {@@ -559,6 +616,17 @@ StmtPtr parse_stmt() { Pos p = cur().pos;++ if (at(Tok::At)) {+ ExprPtr cfg = parse_cfg_attribute();+ auto s = std::make_unique<Stmt>();+ s->kind = Stmt::Kind::Block;+ s->pos = p;+ s->block = parse_block();+ if (!eval_cfg_condition(*cfg))+ s->block->stmts.clear();+ return s;+ } if (match_ident("const") || match_ident("var")) { bool is_const = tokens_[i_ - 1].text == "const";@@ -969,6 +1037,8 @@ ExprPtr parse_primary() { Pos p = cur().pos;+ if (at(Tok::At))+ return parse_cfg_value(); if (at(Tok::Int)) { auto e = std::make_unique<Expr>(); e->kind = Expr::Kind::Int;--- a/src/sema.cpp+++ b/src/sema.cpp@@ -307,6 +307,8 @@ void run() { if (program_.functions.empty()) throw Error(Pos{}, "program contains no functions");++ types_["Utf8Error"] = t_utf8_error(); for (auto& t : program_.types) { if (types_.count(t->name))@@ -530,8 +532,8 @@ } static bool printable(const TypePtr& t) {- return t && (is_int(t) || is_float(t) || t->kind == Type::Kind::Bool ||- t->kind == Type::Kind::Str);+ return t && (is_int(t) || is_float(t) || is_rune(t) ||+ t->kind == Type::Kind::Bool || t->kind == Type::Kind::Str); } TypePtr unify_int(const TypePtr& a, const TypePtr& b, Pos p) {@@ -1202,9 +1204,10 @@ return inst; } - if (name == "bytes_new" || name == "bytes_from_str" || name == "bytes_to_str" ||- name == "bytes_append" || name == "bytes_slice" || name == "str_slice" ||- name == "bytes_ptr") {+ if (name == "rune::from_u32" || name == "rune::to_u32" || name == "str::rune_count" ||+ name == "str::rune_count_lossy" || name == "str::rune_at" || name == "str::runes" ||+ name == "str::runes_lossy" || name == "str::slice_runes" ||+ name == "str::slice_runes_lossy") { for (auto& a : e.args) check_expr(*a); auto require = [&](size_t count) {@@ -1212,47 +1215,101 @@ throw Error(e.pos, name + " expects " + std::to_string(count) + " arguments"); };- if (name == "bytes_new") {+ if (name == "rune::from_u32") { require(1); if (!is_int(e.args[0]->ty))- throw Error(e.pos, "bytes_new expects an integer length");+ throw Error(e.pos, "rune::from_u32 expects u32");+ return t_result(t_rune(), t_utf8_error());+ }+ if (name == "rune::to_u32") {+ require(1);+ if (!is_rune(e.args[0]->ty))+ throw Error(e.pos, "rune::to_u32 expects rune");+ return t_u32();+ }+ if (name == "str::rune_count" || name == "str::rune_count_lossy") {+ require(1);+ if (e.args[0]->ty->kind != Type::Kind::Str)+ throw Error(e.pos, name + " expects str");+ if (name == "str::rune_count")+ return t_result(t_u64(), t_utf8_error());+ return t_u64();+ }+ if (name == "str::rune_at") {+ require(2);+ if (e.args[0]->ty->kind != Type::Kind::Str || !is_int(e.args[1]->ty))+ throw Error(e.pos, "str::rune_at expects (str, u64)");+ return t_result(t_rune(), t_utf8_error());+ }+ if (name == "str::runes" || name == "str::runes_lossy") {+ require(1);+ if (e.args[0]->ty->kind != Type::Kind::Str)+ throw Error(e.pos, name + " expects str");+ TypePtr list = t_list(t_rune());+ if (name == "str::runes")+ return t_result(list, t_utf8_error());+ return list;+ }+ require(3);+ if (e.args[0]->ty->kind != Type::Kind::Str || !is_int(e.args[1]->ty) ||+ !is_int(e.args[2]->ty))+ throw Error(e.pos, name + " expects (str, u64, u64)");+ if (name == "str::slice_runes")+ return t_result(t_str(), t_utf8_error());+ return t_str();+ }++ if (name == "bytes::new" || name == "bytes::from_str" || name == "bytes::to_str" ||+ name == "bytes::append" || name == "bytes::slice" || name == "str::slice" ||+ name == "bytes::ptr") {+ for (auto& a : e.args)+ check_expr(*a);+ auto require = [&](size_t count) {+ if (e.args.size() != count)+ throw Error(e.pos, name + " expects " + std::to_string(count) ++ " arguments");+ };+ if (name == "bytes::new") {+ require(1);+ if (!is_int(e.args[0]->ty))+ throw Error(e.pos, "bytes::new expects an integer length"); return t_bytes(); }- if (name == "bytes_from_str") {+ if (name == "bytes::from_str") { require(1); if (e.args[0]->ty->kind != Type::Kind::Str)- throw Error(e.pos, "bytes_from_str expects str");+ throw Error(e.pos, "bytes::from_str expects str"); return t_bytes(); }- if (name == "bytes_to_str") {+ if (name == "bytes::to_str") { require(1); if (e.args[0]->ty->kind != Type::Kind::Bytes)- throw Error(e.pos, "bytes_to_str expects bytes");+ throw Error(e.pos, "bytes::to_str expects bytes"); return t_str(); }- if (name == "bytes_append") {+ if (name == "bytes::append") { require(2); if (e.args[0]->ty->kind != Type::Kind::Bytes || !is_int(e.args[1]->ty))- throw Error(e.pos, "bytes_append expects (bytes, u8)");+ throw Error(e.pos, "bytes::append expects (bytes, u8)"); return t_bytes(); }- if (name == "bytes_slice") {+ if (name == "bytes::slice") { require(3); if (e.args[0]->ty->kind != Type::Kind::Bytes || !is_int(e.args[1]->ty) || !is_int(e.args[2]->ty))- throw Error(e.pos, "bytes_slice expects (bytes, u64, u64)");+ throw Error(e.pos, "bytes::slice expects (bytes, u64, u64)"); return t_bytes(); }- if (name == "str_slice") {+ if (name == "str::slice") { require(3); if (e.args[0]->ty->kind != Type::Kind::Str || !is_int(e.args[1]->ty) || !is_int(e.args[2]->ty))- throw Error(e.pos, "str_slice expects (str, u64, u64)");+ throw Error(e.pos, "str::slice expects (str, u64, u64)"); return t_str(); } require(1); if (e.args[0]->ty->kind != Type::Kind::Bytes)- throw Error(e.pos, "bytes_ptr expects bytes");+ throw Error(e.pos, "bytes::ptr expects bytes"); return t_ptr(); } --- a/src/types.cpp+++ b/src/types.cpp@@ -48,6 +48,9 @@ } TypePtr t_str() { return make(Type::Kind::Str);+}+TypePtr t_rune() {+ return make(Type::Kind::Rune); } TypePtr t_ptr() { return make(Type::Kind::Ptr);@@ -54,6 +57,21 @@ } TypePtr t_bytes() { return make(Type::Kind::Bytes);+}++TypePtr t_utf8_error() {+ static TypePtr type = [] {+ auto t = make(Type::Kind::Enum);+ t->name = "Utf8Error";+ Variant invalid;+ invalid.name = "InvalidEncoding";+ Variant bounds;+ bounds.name = "OutOfBounds";+ t->variants.push_back(std::move(invalid));+ t->variants.push_back(std::move(bounds));+ return t;+ }();+ return type; } TypePtr t_list(TypePtr elem) {@@ -302,6 +320,10 @@ bool is_float(const TypePtr& t) { return t && t->kind == Type::Kind::F64;+}++bool is_rune(const TypePtr& t) {+ return t && t->kind == Type::Kind::Rune; } bool is_narrow_int(const TypePtr& t) {@@ -411,6 +433,8 @@ return "bool"; case Type::Kind::Str: return "str";+ case Type::Kind::Rune:+ return "rune"; case Type::Kind::Ptr: return "ptr"; case Type::Kind::Bytes:--- /dev/null+++ b/t.hz@@ -0,0 +1,1 @@+fn main(){ const a=str_rune_at("abc",9) match a { OK(x)=>print(1) Error(e)=>match e { Utf8Error.InvalidEncoding=>print(-1) Utf8Error.OutOfBounds=>print(-2) } } }