Compare commits
6 Commits
746643527d
...
v0.1.8
| Author | SHA1 | Date | |
|---|---|---|---|
| ea3a7ca2dd | |||
| 7b40421a6a | |||
| 26b94935e9 | |||
| 018a799c05 | |||
| ec78286165 | |||
| f2688072ac |
15
Cargo.lock
generated
15
Cargo.lock
generated
@@ -225,7 +225,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"windows-sys 0.59.0",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -392,6 +392,12 @@ dependencies = [
|
|||||||
"wasip3",
|
"wasip3",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "glob"
|
||||||
|
version = "0.3.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "h2"
|
name = "h2"
|
||||||
version = "0.3.27"
|
version = "0.3.27"
|
||||||
@@ -770,8 +776,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lux"
|
name = "lux"
|
||||||
version = "0.1.6"
|
version = "0.1.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"glob",
|
||||||
"lsp-server",
|
"lsp-server",
|
||||||
"lsp-types",
|
"lsp-types",
|
||||||
"postgres",
|
"postgres",
|
||||||
@@ -1182,7 +1189,7 @@ dependencies = [
|
|||||||
"errno",
|
"errno",
|
||||||
"libc",
|
"libc",
|
||||||
"linux-raw-sys",
|
"linux-raw-sys",
|
||||||
"windows-sys 0.59.0",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1475,7 +1482,7 @@ dependencies = [
|
|||||||
"getrandom 0.4.1",
|
"getrandom 0.4.1",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"rustix",
|
"rustix",
|
||||||
"windows-sys 0.59.0",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "lux"
|
name = "lux"
|
||||||
version = "0.1.6"
|
version = "0.1.8"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
description = "A functional programming language with first-class effects, schema evolution, and behavioral types"
|
description = "A functional programming language with first-class effects, schema evolution, and behavioral types"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
@@ -17,6 +17,7 @@ reqwest = { version = "0.11", default-features = false, features = ["blocking",
|
|||||||
tiny_http = "0.12"
|
tiny_http = "0.12"
|
||||||
rusqlite = { version = "0.31", features = ["bundled"] }
|
rusqlite = { version = "0.31", features = ["bundled"] }
|
||||||
postgres = "0.19"
|
postgres = "0.19"
|
||||||
|
glob = "0.3"
|
||||||
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
|||||||
@@ -44,7 +44,7 @@
|
|||||||
printf "\n"
|
printf "\n"
|
||||||
printf " \033[1;35m╦ ╦ ╦╦ ╦\033[0m\n"
|
printf " \033[1;35m╦ ╦ ╦╦ ╦\033[0m\n"
|
||||||
printf " \033[1;35m║ ║ ║╔╣\033[0m\n"
|
printf " \033[1;35m║ ║ ║╔╣\033[0m\n"
|
||||||
printf " \033[1;35m╩═╝╚═╝╩ ╩\033[0m v0.1.6\n"
|
printf " \033[1;35m╩═╝╚═╝╩ ╩\033[0m v0.1.8\n"
|
||||||
printf "\n"
|
printf "\n"
|
||||||
printf " Functional language with first-class effects\n"
|
printf " Functional language with first-class effects\n"
|
||||||
printf "\n"
|
printf "\n"
|
||||||
@@ -62,7 +62,7 @@
|
|||||||
|
|
||||||
packages.default = pkgs.rustPlatform.buildRustPackage {
|
packages.default = pkgs.rustPlatform.buildRustPackage {
|
||||||
pname = "lux";
|
pname = "lux";
|
||||||
version = "0.1.6";
|
version = "0.1.8";
|
||||||
src = ./.;
|
src = ./.;
|
||||||
cargoLock.lockFile = ./Cargo.lock;
|
cargoLock.lockFile = ./Cargo.lock;
|
||||||
|
|
||||||
@@ -79,7 +79,7 @@
|
|||||||
};
|
};
|
||||||
in muslPkgs.rustPlatform.buildRustPackage {
|
in muslPkgs.rustPlatform.buildRustPackage {
|
||||||
pname = "lux";
|
pname = "lux";
|
||||||
version = "0.1.6";
|
version = "0.1.8";
|
||||||
src = ./.;
|
src = ./.;
|
||||||
cargoLock.lockFile = ./Cargo.lock;
|
cargoLock.lockFile = ./Cargo.lock;
|
||||||
|
|
||||||
|
|||||||
@@ -1166,6 +1166,10 @@ impl CBackend {
|
|||||||
self.writeln(" void (*mkdir)(void* env, LuxString path);");
|
self.writeln(" void (*mkdir)(void* env, LuxString path);");
|
||||||
self.writeln(" void (*copy)(void* env, LuxString src, LuxString dst);");
|
self.writeln(" void (*copy)(void* env, LuxString src, LuxString dst);");
|
||||||
self.writeln(" LuxList* (*readDir)(void* env, LuxString path);");
|
self.writeln(" LuxList* (*readDir)(void* env, LuxString path);");
|
||||||
|
self.writeln(" LuxList* (*glob)(void* env, LuxString pattern);");
|
||||||
|
self.writeln(" Result (*tryRead)(void* env, LuxString path);");
|
||||||
|
self.writeln(" Result (*tryWrite)(void* env, LuxString path, LuxString content);");
|
||||||
|
self.writeln(" Result (*tryDelete)(void* env, LuxString path);");
|
||||||
self.writeln(" void* env;");
|
self.writeln(" void* env;");
|
||||||
self.writeln("} LuxFileHandler;");
|
self.writeln("} LuxFileHandler;");
|
||||||
self.writeln("");
|
self.writeln("");
|
||||||
@@ -1386,6 +1390,85 @@ impl CBackend {
|
|||||||
self.writeln(" return result;");
|
self.writeln(" return result;");
|
||||||
self.writeln("}");
|
self.writeln("}");
|
||||||
self.writeln("");
|
self.writeln("");
|
||||||
|
self.writeln("#include <glob.h>");
|
||||||
|
self.writeln("static LuxList* lux_file_glob(LuxString pattern) {");
|
||||||
|
self.writeln(" LuxList* result = lux_list_new(16);");
|
||||||
|
self.writeln(" glob_t globbuf;");
|
||||||
|
self.writeln(" int ret = glob(pattern, 0, NULL, &globbuf);");
|
||||||
|
self.writeln(" if (ret == 0) {");
|
||||||
|
self.writeln(" for (size_t i = 0; i < globbuf.gl_pathc; i++) {");
|
||||||
|
self.writeln(" size_t len = strlen(globbuf.gl_pathv[i]);");
|
||||||
|
self.writeln(" LuxString name = (LuxString)lux_rc_alloc(len + 1, LUX_TAG_STRING);");
|
||||||
|
self.writeln(" memcpy(name, globbuf.gl_pathv[i], len + 1);");
|
||||||
|
self.writeln(" lux_list_push(result, (void*)name);");
|
||||||
|
self.writeln(" }");
|
||||||
|
self.writeln(" globfree(&globbuf);");
|
||||||
|
self.writeln(" }");
|
||||||
|
self.writeln(" return result;");
|
||||||
|
self.writeln("}");
|
||||||
|
self.writeln("");
|
||||||
|
self.writeln("static Result lux_file_tryRead(LuxString path) {");
|
||||||
|
self.writeln(" Result r;");
|
||||||
|
self.writeln(" FILE* f = fopen(path, \"r\");");
|
||||||
|
self.writeln(" if (!f) {");
|
||||||
|
self.writeln(" char buf[512];");
|
||||||
|
self.writeln(" snprintf(buf, sizeof(buf), \"Failed to read file '%s': %s\", path, strerror(errno));");
|
||||||
|
self.writeln(" size_t len = strlen(buf);");
|
||||||
|
self.writeln(" LuxString msg = (LuxString)lux_rc_alloc(len + 1, LUX_TAG_STRING);");
|
||||||
|
self.writeln(" memcpy(msg, buf, len + 1);");
|
||||||
|
self.writeln(" r.tag = Result_TAG_ERR;");
|
||||||
|
self.writeln(" r.data.err.field0 = (void*)msg;");
|
||||||
|
self.writeln(" return r;");
|
||||||
|
self.writeln(" }");
|
||||||
|
self.writeln(" fseek(f, 0, SEEK_END);");
|
||||||
|
self.writeln(" long size = ftell(f);");
|
||||||
|
self.writeln(" fseek(f, 0, SEEK_SET);");
|
||||||
|
self.writeln(" LuxString content = (LuxString)lux_rc_alloc(size + 1, LUX_TAG_STRING);");
|
||||||
|
self.writeln(" size_t read_size = fread(content, 1, size, f);");
|
||||||
|
self.writeln(" content[read_size] = '\\0';");
|
||||||
|
self.writeln(" fclose(f);");
|
||||||
|
self.writeln(" r.tag = Result_TAG_OK;");
|
||||||
|
self.writeln(" r.data.ok.field0 = (void*)content;");
|
||||||
|
self.writeln(" return r;");
|
||||||
|
self.writeln("}");
|
||||||
|
self.writeln("");
|
||||||
|
self.writeln("static Result lux_file_tryWrite(LuxString path, LuxString content) {");
|
||||||
|
self.writeln(" Result r;");
|
||||||
|
self.writeln(" FILE* f = fopen(path, \"w\");");
|
||||||
|
self.writeln(" if (!f) {");
|
||||||
|
self.writeln(" char buf[512];");
|
||||||
|
self.writeln(" snprintf(buf, sizeof(buf), \"Failed to write file '%s': %s\", path, strerror(errno));");
|
||||||
|
self.writeln(" size_t len = strlen(buf);");
|
||||||
|
self.writeln(" LuxString msg = (LuxString)lux_rc_alloc(len + 1, LUX_TAG_STRING);");
|
||||||
|
self.writeln(" memcpy(msg, buf, len + 1);");
|
||||||
|
self.writeln(" r.tag = Result_TAG_ERR;");
|
||||||
|
self.writeln(" r.data.err.field0 = (void*)msg;");
|
||||||
|
self.writeln(" return r;");
|
||||||
|
self.writeln(" }");
|
||||||
|
self.writeln(" fputs(content, f);");
|
||||||
|
self.writeln(" fclose(f);");
|
||||||
|
self.writeln(" r.tag = Result_TAG_OK;");
|
||||||
|
self.writeln(" r.data.ok.field0 = NULL;");
|
||||||
|
self.writeln(" return r;");
|
||||||
|
self.writeln("}");
|
||||||
|
self.writeln("");
|
||||||
|
self.writeln("static Result lux_file_tryDelete(LuxString path) {");
|
||||||
|
self.writeln(" Result r;");
|
||||||
|
self.writeln(" if (remove(path) != 0) {");
|
||||||
|
self.writeln(" char buf[512];");
|
||||||
|
self.writeln(" snprintf(buf, sizeof(buf), \"Failed to delete file '%s': %s\", path, strerror(errno));");
|
||||||
|
self.writeln(" size_t len = strlen(buf);");
|
||||||
|
self.writeln(" LuxString msg = (LuxString)lux_rc_alloc(len + 1, LUX_TAG_STRING);");
|
||||||
|
self.writeln(" memcpy(msg, buf, len + 1);");
|
||||||
|
self.writeln(" r.tag = Result_TAG_ERR;");
|
||||||
|
self.writeln(" r.data.err.field0 = (void*)msg;");
|
||||||
|
self.writeln(" return r;");
|
||||||
|
self.writeln(" }");
|
||||||
|
self.writeln(" r.tag = Result_TAG_OK;");
|
||||||
|
self.writeln(" r.data.ok.field0 = NULL;");
|
||||||
|
self.writeln(" return r;");
|
||||||
|
self.writeln("}");
|
||||||
|
self.writeln("");
|
||||||
self.writeln("static LuxString default_file_read(void* env, LuxString path) {");
|
self.writeln("static LuxString default_file_read(void* env, LuxString path) {");
|
||||||
self.writeln(" (void)env;");
|
self.writeln(" (void)env;");
|
||||||
self.writeln(" return lux_file_read(path);");
|
self.writeln(" return lux_file_read(path);");
|
||||||
@@ -1431,6 +1514,26 @@ impl CBackend {
|
|||||||
self.writeln(" return lux_file_readDir(path);");
|
self.writeln(" return lux_file_readDir(path);");
|
||||||
self.writeln("}");
|
self.writeln("}");
|
||||||
self.writeln("");
|
self.writeln("");
|
||||||
|
self.writeln("static LuxList* default_file_glob(void* env, LuxString pattern) {");
|
||||||
|
self.writeln(" (void)env;");
|
||||||
|
self.writeln(" return lux_file_glob(pattern);");
|
||||||
|
self.writeln("}");
|
||||||
|
self.writeln("");
|
||||||
|
self.writeln("static Result default_file_tryRead(void* env, LuxString path) {");
|
||||||
|
self.writeln(" (void)env;");
|
||||||
|
self.writeln(" return lux_file_tryRead(path);");
|
||||||
|
self.writeln("}");
|
||||||
|
self.writeln("");
|
||||||
|
self.writeln("static Result default_file_tryWrite(void* env, LuxString path, LuxString content) {");
|
||||||
|
self.writeln(" (void)env;");
|
||||||
|
self.writeln(" return lux_file_tryWrite(path, content);");
|
||||||
|
self.writeln("}");
|
||||||
|
self.writeln("");
|
||||||
|
self.writeln("static Result default_file_tryDelete(void* env, LuxString path) {");
|
||||||
|
self.writeln(" (void)env;");
|
||||||
|
self.writeln(" return lux_file_tryDelete(path);");
|
||||||
|
self.writeln("}");
|
||||||
|
self.writeln("");
|
||||||
self.writeln("static LuxFileHandler default_file_handler = {");
|
self.writeln("static LuxFileHandler default_file_handler = {");
|
||||||
self.writeln(" .read = default_file_read,");
|
self.writeln(" .read = default_file_read,");
|
||||||
self.writeln(" .write = default_file_write,");
|
self.writeln(" .write = default_file_write,");
|
||||||
@@ -1441,6 +1544,10 @@ impl CBackend {
|
|||||||
self.writeln(" .mkdir = default_file_mkdir,");
|
self.writeln(" .mkdir = default_file_mkdir,");
|
||||||
self.writeln(" .copy = default_file_copy,");
|
self.writeln(" .copy = default_file_copy,");
|
||||||
self.writeln(" .readDir = default_file_readDir,");
|
self.writeln(" .readDir = default_file_readDir,");
|
||||||
|
self.writeln(" .glob = default_file_glob,");
|
||||||
|
self.writeln(" .tryRead = default_file_tryRead,");
|
||||||
|
self.writeln(" .tryWrite = default_file_tryWrite,");
|
||||||
|
self.writeln(" .tryDelete = default_file_tryDelete,");
|
||||||
self.writeln(" .env = NULL");
|
self.writeln(" .env = NULL");
|
||||||
self.writeln("};");
|
self.writeln("};");
|
||||||
self.writeln("");
|
self.writeln("");
|
||||||
@@ -3790,6 +3897,50 @@ impl CBackend {
|
|||||||
self.register_rc_var(&temp, "LuxList*");
|
self.register_rc_var(&temp, "LuxList*");
|
||||||
return Ok(temp);
|
return Ok(temp);
|
||||||
}
|
}
|
||||||
|
"glob" => {
|
||||||
|
let pattern = self.emit_expr(&args[0])?;
|
||||||
|
let temp = format!("_glob_{}", self.fresh_name());
|
||||||
|
if self.has_evidence {
|
||||||
|
self.writeln(&format!("LuxList* {} = ev->file->glob(ev->file->env, {});", temp, pattern));
|
||||||
|
} else {
|
||||||
|
self.writeln(&format!("LuxList* {} = lux_file_glob({});", temp, pattern));
|
||||||
|
}
|
||||||
|
self.register_rc_var(&temp, "LuxList*");
|
||||||
|
return Ok(temp);
|
||||||
|
}
|
||||||
|
"tryRead" => {
|
||||||
|
let path = self.emit_expr(&args[0])?;
|
||||||
|
let temp = format!("_file_tryread_{}", self.fresh_name());
|
||||||
|
if self.has_evidence {
|
||||||
|
self.writeln(&format!("Result {} = ev->file->tryRead(ev->file->env, {});", temp, path));
|
||||||
|
} else {
|
||||||
|
self.writeln(&format!("Result {} = lux_file_tryRead({});", temp, path));
|
||||||
|
}
|
||||||
|
return Ok(temp);
|
||||||
|
}
|
||||||
|
"tryWrite" => {
|
||||||
|
let path = self.emit_expr(&args[0])?;
|
||||||
|
let content = self.emit_expr(&args[1])?;
|
||||||
|
if self.has_evidence {
|
||||||
|
let temp = format!("_file_trywrite_{}", self.fresh_name());
|
||||||
|
self.writeln(&format!("Result {} = ev->file->tryWrite(ev->file->env, {}, {});", temp, path, content));
|
||||||
|
return Ok(temp);
|
||||||
|
} else {
|
||||||
|
let temp = format!("_file_trywrite_{}", self.fresh_name());
|
||||||
|
self.writeln(&format!("Result {} = lux_file_tryWrite({}, {});", temp, path, content));
|
||||||
|
return Ok(temp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"tryDelete" => {
|
||||||
|
let path = self.emit_expr(&args[0])?;
|
||||||
|
let temp = format!("_file_trydelete_{}", self.fresh_name());
|
||||||
|
if self.has_evidence {
|
||||||
|
self.writeln(&format!("Result {} = ev->file->tryDelete(ev->file->env, {});", temp, path));
|
||||||
|
} else {
|
||||||
|
self.writeln(&format!("Result {} = lux_file_tryDelete({});", temp, path));
|
||||||
|
}
|
||||||
|
return Ok(temp);
|
||||||
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4791,6 +4942,108 @@ impl CBackend {
|
|||||||
self.register_rc_var(&result_var, "LuxList*");
|
self.register_rc_var(&result_var, "LuxList*");
|
||||||
Ok(result_var)
|
Ok(result_var)
|
||||||
}
|
}
|
||||||
|
"findIndex" => {
|
||||||
|
if args.len() != 2 {
|
||||||
|
return Err(CGenError { message: "List.findIndex takes 2 arguments".to_string(), span: None });
|
||||||
|
}
|
||||||
|
let elem_type = self.infer_callback_param_type(&args[1], 0);
|
||||||
|
let elem_is_prim = Self::is_primitive_c_type(&elem_type);
|
||||||
|
|
||||||
|
let list = self.emit_expr(&args[0])?;
|
||||||
|
let closure = self.emit_expr(&args[1])?;
|
||||||
|
let id = self.fresh_name();
|
||||||
|
let result_var = format!("_findidx_{}", id);
|
||||||
|
let i_var = format!("_i_{}", id);
|
||||||
|
let elem_var = format!("_elem_{}", id);
|
||||||
|
let fn_var = format!("_fn_{}", id);
|
||||||
|
let matches_var = format!("_matches_{}", id);
|
||||||
|
|
||||||
|
let arg_pass = if elem_is_prim {
|
||||||
|
format!("{}({})", Self::unbox_fn_for_type(&elem_type), elem_var)
|
||||||
|
} else {
|
||||||
|
elem_var.clone()
|
||||||
|
};
|
||||||
|
let fn_cast = if elem_is_prim {
|
||||||
|
format!("(LuxBool(*)(void*, {}))", elem_type)
|
||||||
|
} else {
|
||||||
|
"(LuxBool(*)(void*, void*))".to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
self.writeln(&format!("Option {} = lux_option_none();", result_var));
|
||||||
|
self.writeln(&format!("for (int64_t {} = 0; {} < {}->length; {}++) {{", i_var, i_var, list, i_var));
|
||||||
|
self.indent += 1;
|
||||||
|
self.writeln(&format!("void* {} = {}->elements[{}];", elem_var, list, i_var));
|
||||||
|
self.writeln(&format!("LuxClosure* {} = (LuxClosure*){};", fn_var, closure));
|
||||||
|
self.writeln(&format!("LuxBool {} = ({}{}->fn_ptr)({}->env, {});", matches_var, fn_cast, fn_var, fn_var, arg_pass));
|
||||||
|
self.writeln(&format!("if ({}) {{", matches_var));
|
||||||
|
self.indent += 1;
|
||||||
|
self.writeln(&format!("{} = lux_option_some((void*)(intptr_t){});", result_var, i_var));
|
||||||
|
self.writeln("break;");
|
||||||
|
self.indent -= 1;
|
||||||
|
self.writeln("}");
|
||||||
|
self.indent -= 1;
|
||||||
|
self.writeln("}");
|
||||||
|
if closure.starts_with("_closure_") || closure.starts_with("_fn_ref_") {
|
||||||
|
self.writeln(&format!("lux_decref_closure({});", closure));
|
||||||
|
}
|
||||||
|
Ok(result_var)
|
||||||
|
}
|
||||||
|
|
||||||
|
"zip" => {
|
||||||
|
if args.len() != 2 {
|
||||||
|
return Err(CGenError { message: "List.zip takes 2 arguments".to_string(), span: None });
|
||||||
|
}
|
||||||
|
let list1 = self.emit_expr(&args[0])?;
|
||||||
|
let list2 = self.emit_expr(&args[1])?;
|
||||||
|
let id = self.fresh_name();
|
||||||
|
let result_var = format!("_zip_{}", id);
|
||||||
|
let len_var = format!("_ziplen_{}", id);
|
||||||
|
let i_var = format!("_i_{}", id);
|
||||||
|
|
||||||
|
self.writeln(&format!("int64_t {} = {}->length < {}->length ? {}->length : {}->length;", len_var, list1, list2, list1, list2));
|
||||||
|
self.writeln(&format!("LuxList* {} = lux_list_new({});", result_var, len_var));
|
||||||
|
self.writeln(&format!("for (int64_t {} = 0; {} < {}; {}++) {{", i_var, i_var, len_var, i_var));
|
||||||
|
self.indent += 1;
|
||||||
|
self.writeln(&format!("LuxTuple* _tup = (LuxTuple*)lux_rc_alloc(sizeof(LuxTuple) + 2 * sizeof(void*), LUX_TAG_TUPLE);"));
|
||||||
|
self.writeln("_tup->length = 2;");
|
||||||
|
self.writeln(&format!("_tup->elements[0] = {}->elements[{}];", list1, i_var));
|
||||||
|
self.writeln(&format!("_tup->elements[1] = {}->elements[{}];", list2, i_var));
|
||||||
|
self.writeln(&format!("lux_incref({}->elements[{}]);", list1, i_var));
|
||||||
|
self.writeln(&format!("lux_incref({}->elements[{}]);", list2, i_var));
|
||||||
|
self.writeln(&format!("lux_list_push({}, (void*)_tup);", result_var));
|
||||||
|
self.indent -= 1;
|
||||||
|
self.writeln("}");
|
||||||
|
self.register_rc_var(&result_var, "LuxList*");
|
||||||
|
Ok(result_var)
|
||||||
|
}
|
||||||
|
|
||||||
|
"flatten" => {
|
||||||
|
if args.len() != 1 {
|
||||||
|
return Err(CGenError { message: "List.flatten takes 1 argument".to_string(), span: None });
|
||||||
|
}
|
||||||
|
let list = self.emit_expr(&args[0])?;
|
||||||
|
let id = self.fresh_name();
|
||||||
|
let result_var = format!("_flat_{}", id);
|
||||||
|
let i_var = format!("_i_{}", id);
|
||||||
|
let j_var = format!("_j_{}", id);
|
||||||
|
let inner_var = format!("_inner_{}", id);
|
||||||
|
|
||||||
|
self.writeln(&format!("LuxList* {} = lux_list_new(16);", result_var));
|
||||||
|
self.writeln(&format!("for (int64_t {} = 0; {} < {}->length; {}++) {{", i_var, i_var, list, i_var));
|
||||||
|
self.indent += 1;
|
||||||
|
self.writeln(&format!("LuxList* {} = (LuxList*){}->elements[{}];", inner_var, list, i_var));
|
||||||
|
self.writeln(&format!("for (int64_t {} = 0; {} < {}->length; {}++) {{", j_var, j_var, inner_var, j_var));
|
||||||
|
self.indent += 1;
|
||||||
|
self.writeln(&format!("lux_incref({}->elements[{}]);", inner_var, j_var));
|
||||||
|
self.writeln(&format!("lux_list_push({}, {}->elements[{}]);", result_var, inner_var, j_var));
|
||||||
|
self.indent -= 1;
|
||||||
|
self.writeln("}");
|
||||||
|
self.indent -= 1;
|
||||||
|
self.writeln("}");
|
||||||
|
self.register_rc_var(&result_var, "LuxList*");
|
||||||
|
Ok(result_var)
|
||||||
|
}
|
||||||
|
|
||||||
_ => Err(CGenError {
|
_ => Err(CGenError {
|
||||||
message: format!("Unsupported List operation: {}", op),
|
message: format!("Unsupported List operation: {}", op),
|
||||||
span: None,
|
span: None,
|
||||||
@@ -5223,8 +5476,8 @@ impl CBackend {
|
|||||||
},
|
},
|
||||||
"List" => match field.name.as_str() {
|
"List" => match field.name.as_str() {
|
||||||
"map" | "filter" | "concat" | "reverse" | "take" | "drop"
|
"map" | "filter" | "concat" | "reverse" | "take" | "drop"
|
||||||
| "range" | "sort" | "sortBy" | "flatten" | "intersperse" => return Some("LuxList*".to_string()),
|
| "range" | "sort" | "sortBy" | "flatten" | "intersperse" | "zip" => return Some("LuxList*".to_string()),
|
||||||
"head" | "tail" | "get" | "find" | "last" => return Some("Option".to_string()),
|
"head" | "tail" | "get" | "find" | "findIndex" | "last" => return Some("Option".to_string()),
|
||||||
"length" => return Some("LuxInt".to_string()),
|
"length" => return Some("LuxInt".to_string()),
|
||||||
"fold" | "foldLeft" => {
|
"fold" | "foldLeft" => {
|
||||||
// Fold return type is the type of the init value (2nd arg)
|
// Fold return type is the type of the init value (2nd arg)
|
||||||
@@ -5318,9 +5571,9 @@ impl CBackend {
|
|||||||
if effect.name == "List" {
|
if effect.name == "List" {
|
||||||
match operation.name.as_str() {
|
match operation.name.as_str() {
|
||||||
// Operations returning lists
|
// Operations returning lists
|
||||||
"map" | "filter" | "concat" | "reverse" | "take" | "drop" | "range" | "sort" | "sortBy" => Some("LuxList*".to_string()),
|
"map" | "filter" | "concat" | "reverse" | "take" | "drop" | "range" | "sort" | "sortBy" | "zip" | "flatten" => Some("LuxList*".to_string()),
|
||||||
// Operations returning Option
|
// Operations returning Option
|
||||||
"head" | "tail" | "get" | "find" => Some("Option".to_string()),
|
"head" | "tail" | "get" | "find" | "findIndex" => Some("Option".to_string()),
|
||||||
// Operations returning Int
|
// Operations returning Int
|
||||||
"length" => Some("LuxInt".to_string()),
|
"length" => Some("LuxInt".to_string()),
|
||||||
// Fold returns the type of the init value
|
// Fold returns the type of the init value
|
||||||
@@ -5332,7 +5585,7 @@ impl CBackend {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Operations returning Bool
|
// Operations returning Bool
|
||||||
"isEmpty" | "any" | "all" => Some("LuxBool".to_string()),
|
"isEmpty" | "any" | "all" | "contains" => Some("LuxBool".to_string()),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
} else if effect.name == "Random" {
|
} else if effect.name == "Random" {
|
||||||
@@ -5353,7 +5606,8 @@ impl CBackend {
|
|||||||
"read" => Some("LuxString".to_string()),
|
"read" => Some("LuxString".to_string()),
|
||||||
"write" | "append" | "delete" | "mkdir" | "copy" => Some("void".to_string()),
|
"write" | "append" | "delete" | "mkdir" | "copy" => Some("void".to_string()),
|
||||||
"exists" | "isDir" => Some("LuxBool".to_string()),
|
"exists" | "isDir" => Some("LuxBool".to_string()),
|
||||||
"readDir" | "listDir" => Some("LuxList*".to_string()),
|
"readDir" | "listDir" | "glob" => Some("LuxList*".to_string()),
|
||||||
|
"tryRead" | "tryWrite" | "tryDelete" => Some("Result".to_string()),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
} else if effect.name == "Http" {
|
} else if effect.name == "Http" {
|
||||||
@@ -6230,7 +6484,8 @@ impl CBackend {
|
|||||||
// These List operations return new lists
|
// These List operations return new lists
|
||||||
return matches!(field.name.as_str(),
|
return matches!(field.name.as_str(),
|
||||||
"map" | "filter" | "concat" | "reverse" |
|
"map" | "filter" | "concat" | "reverse" |
|
||||||
"take" | "drop" | "range"
|
"take" | "drop" | "range" | "zip" | "flatten" |
|
||||||
|
"sort" | "sortBy"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if module.name == "String" {
|
if module.name == "String" {
|
||||||
@@ -6256,7 +6511,8 @@ impl CBackend {
|
|||||||
if effect.name == "List" {
|
if effect.name == "List" {
|
||||||
matches!(operation.name.as_str(),
|
matches!(operation.name.as_str(),
|
||||||
"map" | "filter" | "concat" | "reverse" |
|
"map" | "filter" | "concat" | "reverse" |
|
||||||
"take" | "drop" | "range"
|
"take" | "drop" | "range" | "zip" | "flatten" |
|
||||||
|
"sort" | "sortBy"
|
||||||
)
|
)
|
||||||
} else if effect.name == "Process" {
|
} else if effect.name == "Process" {
|
||||||
// Process.exec returns RC-managed string
|
// Process.exec returns RC-managed string
|
||||||
|
|||||||
@@ -83,10 +83,14 @@ pub enum BuiltinFn {
|
|||||||
// Additional List operations
|
// Additional List operations
|
||||||
ListIsEmpty,
|
ListIsEmpty,
|
||||||
ListFind,
|
ListFind,
|
||||||
|
ListFindIndex,
|
||||||
ListAny,
|
ListAny,
|
||||||
ListAll,
|
ListAll,
|
||||||
ListTake,
|
ListTake,
|
||||||
ListDrop,
|
ListDrop,
|
||||||
|
ListZip,
|
||||||
|
ListFlatten,
|
||||||
|
ListContains,
|
||||||
|
|
||||||
// Additional String operations
|
// Additional String operations
|
||||||
StringStartsWith,
|
StringStartsWith,
|
||||||
@@ -974,10 +978,14 @@ impl Interpreter {
|
|||||||
Value::Builtin(BuiltinFn::ListIsEmpty),
|
Value::Builtin(BuiltinFn::ListIsEmpty),
|
||||||
),
|
),
|
||||||
("find".to_string(), Value::Builtin(BuiltinFn::ListFind)),
|
("find".to_string(), Value::Builtin(BuiltinFn::ListFind)),
|
||||||
|
("findIndex".to_string(), Value::Builtin(BuiltinFn::ListFindIndex)),
|
||||||
("any".to_string(), Value::Builtin(BuiltinFn::ListAny)),
|
("any".to_string(), Value::Builtin(BuiltinFn::ListAny)),
|
||||||
("all".to_string(), Value::Builtin(BuiltinFn::ListAll)),
|
("all".to_string(), Value::Builtin(BuiltinFn::ListAll)),
|
||||||
("take".to_string(), Value::Builtin(BuiltinFn::ListTake)),
|
("take".to_string(), Value::Builtin(BuiltinFn::ListTake)),
|
||||||
("drop".to_string(), Value::Builtin(BuiltinFn::ListDrop)),
|
("drop".to_string(), Value::Builtin(BuiltinFn::ListDrop)),
|
||||||
|
("zip".to_string(), Value::Builtin(BuiltinFn::ListZip)),
|
||||||
|
("flatten".to_string(), Value::Builtin(BuiltinFn::ListFlatten)),
|
||||||
|
("contains".to_string(), Value::Builtin(BuiltinFn::ListContains)),
|
||||||
(
|
(
|
||||||
"forEach".to_string(),
|
"forEach".to_string(),
|
||||||
Value::Builtin(BuiltinFn::ListForEach),
|
Value::Builtin(BuiltinFn::ListForEach),
|
||||||
@@ -2723,6 +2731,55 @@ impl Interpreter {
|
|||||||
Ok(EvalResult::Value(Value::Bool(true)))
|
Ok(EvalResult::Value(Value::Bool(true)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
BuiltinFn::ListFindIndex => {
|
||||||
|
let (list, func) = Self::expect_args_2::<Vec<Value>, Value>(&args, "List.findIndex", span)?;
|
||||||
|
for (i, item) in list.iter().enumerate() {
|
||||||
|
let v = self.eval_call_to_value(func.clone(), vec![item.clone()], span)?;
|
||||||
|
match v {
|
||||||
|
Value::Bool(true) => {
|
||||||
|
return Ok(EvalResult::Value(Value::Constructor {
|
||||||
|
name: "Some".to_string(),
|
||||||
|
fields: vec![Value::Int(i as i64)],
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
Value::Bool(false) => {}
|
||||||
|
_ => return Err(err("List.findIndex predicate must return Bool")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(EvalResult::Value(Value::Constructor {
|
||||||
|
name: "None".to_string(),
|
||||||
|
fields: vec![],
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
BuiltinFn::ListZip => {
|
||||||
|
let (list1, list2) = Self::expect_args_2::<Vec<Value>, Vec<Value>>(&args, "List.zip", span)?;
|
||||||
|
let result: Vec<Value> = list1
|
||||||
|
.into_iter()
|
||||||
|
.zip(list2.into_iter())
|
||||||
|
.map(|(a, b)| Value::Tuple(vec![a, b]))
|
||||||
|
.collect();
|
||||||
|
Ok(EvalResult::Value(Value::List(result)))
|
||||||
|
}
|
||||||
|
|
||||||
|
BuiltinFn::ListFlatten => {
|
||||||
|
let list = Self::expect_arg_1::<Vec<Value>>(&args, "List.flatten", span)?;
|
||||||
|
let mut result = Vec::new();
|
||||||
|
for item in list {
|
||||||
|
match item {
|
||||||
|
Value::List(inner) => result.extend(inner),
|
||||||
|
other => result.push(other),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(EvalResult::Value(Value::List(result)))
|
||||||
|
}
|
||||||
|
|
||||||
|
BuiltinFn::ListContains => {
|
||||||
|
let (list, target) = Self::expect_args_2::<Vec<Value>, Value>(&args, "List.contains", span)?;
|
||||||
|
let found = list.iter().any(|item| Value::values_equal(item, &target));
|
||||||
|
Ok(EvalResult::Value(Value::Bool(found)))
|
||||||
|
}
|
||||||
|
|
||||||
BuiltinFn::ListTake => {
|
BuiltinFn::ListTake => {
|
||||||
let (list, n) = Self::expect_args_2::<Vec<Value>, i64>(&args, "List.take", span)?;
|
let (list, n) = Self::expect_args_2::<Vec<Value>, i64>(&args, "List.take", span)?;
|
||||||
let n = n.max(0) as usize;
|
let n = n.max(0) as usize;
|
||||||
@@ -3968,6 +4025,95 @@ impl Interpreter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
("File", "glob") => {
|
||||||
|
let pattern = match request.args.first() {
|
||||||
|
Some(Value::String(s)) => s.clone(),
|
||||||
|
_ => return Err(RuntimeError {
|
||||||
|
message: "File.glob requires a string pattern".to_string(),
|
||||||
|
span: None,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
match glob::glob(&pattern) {
|
||||||
|
Ok(paths) => {
|
||||||
|
let entries: Vec<Value> = paths
|
||||||
|
.filter_map(|entry| entry.ok())
|
||||||
|
.map(|path| Value::String(path.to_string_lossy().to_string()))
|
||||||
|
.collect();
|
||||||
|
Ok(Value::List(entries))
|
||||||
|
}
|
||||||
|
Err(e) => Err(RuntimeError {
|
||||||
|
message: format!("Invalid glob pattern '{}': {}", pattern, e),
|
||||||
|
span: None,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== File Effect (safe Result-returning variants) =====
|
||||||
|
("File", "tryRead") => {
|
||||||
|
let path = match request.args.first() {
|
||||||
|
Some(Value::String(s)) => s.clone(),
|
||||||
|
_ => return Err(RuntimeError {
|
||||||
|
message: "File.tryRead requires a string path".to_string(),
|
||||||
|
span: None,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
match std::fs::read_to_string(&path) {
|
||||||
|
Ok(content) => Ok(Value::Constructor {
|
||||||
|
name: "Ok".to_string(),
|
||||||
|
fields: vec![Value::String(content)],
|
||||||
|
}),
|
||||||
|
Err(e) => Ok(Value::Constructor {
|
||||||
|
name: "Err".to_string(),
|
||||||
|
fields: vec![Value::String(format!("Failed to read file '{}': {}", path, e))],
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
("File", "tryWrite") => {
|
||||||
|
let path = match request.args.first() {
|
||||||
|
Some(Value::String(s)) => s.clone(),
|
||||||
|
_ => return Err(RuntimeError {
|
||||||
|
message: "File.tryWrite requires a string path".to_string(),
|
||||||
|
span: None,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
let content = match request.args.get(1) {
|
||||||
|
Some(Value::String(s)) => s.clone(),
|
||||||
|
_ => return Err(RuntimeError {
|
||||||
|
message: "File.tryWrite requires string content".to_string(),
|
||||||
|
span: None,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
match std::fs::write(&path, &content) {
|
||||||
|
Ok(()) => Ok(Value::Constructor {
|
||||||
|
name: "Ok".to_string(),
|
||||||
|
fields: vec![Value::Unit],
|
||||||
|
}),
|
||||||
|
Err(e) => Ok(Value::Constructor {
|
||||||
|
name: "Err".to_string(),
|
||||||
|
fields: vec![Value::String(format!("Failed to write file '{}': {}", path, e))],
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
("File", "tryDelete") => {
|
||||||
|
let path = match request.args.first() {
|
||||||
|
Some(Value::String(s)) => s.clone(),
|
||||||
|
_ => return Err(RuntimeError {
|
||||||
|
message: "File.tryDelete requires a string path".to_string(),
|
||||||
|
span: None,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
match std::fs::remove_file(&path) {
|
||||||
|
Ok(()) => Ok(Value::Constructor {
|
||||||
|
name: "Ok".to_string(),
|
||||||
|
fields: vec![Value::Unit],
|
||||||
|
}),
|
||||||
|
Err(e) => Ok(Value::Constructor {
|
||||||
|
name: "Err".to_string(),
|
||||||
|
fields: vec![Value::String(format!("Failed to delete file '{}': {}", path, e))],
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ===== Process Effect =====
|
// ===== Process Effect =====
|
||||||
("Process", "exec") => {
|
("Process", "exec") => {
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|||||||
66
src/types.rs
66
src/types.rs
@@ -964,6 +964,38 @@ impl TypeEnv {
|
|||||||
],
|
],
|
||||||
return_type: Type::Unit,
|
return_type: Type::Unit,
|
||||||
},
|
},
|
||||||
|
EffectOpDef {
|
||||||
|
name: "glob".to_string(),
|
||||||
|
params: vec![("pattern".to_string(), Type::String)],
|
||||||
|
return_type: Type::List(Box::new(Type::String)),
|
||||||
|
},
|
||||||
|
EffectOpDef {
|
||||||
|
name: "tryRead".to_string(),
|
||||||
|
params: vec![("path".to_string(), Type::String)],
|
||||||
|
return_type: Type::App {
|
||||||
|
constructor: Box::new(Type::Named("Result".to_string())),
|
||||||
|
args: vec![Type::String, Type::String],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
EffectOpDef {
|
||||||
|
name: "tryWrite".to_string(),
|
||||||
|
params: vec![
|
||||||
|
("path".to_string(), Type::String),
|
||||||
|
("content".to_string(), Type::String),
|
||||||
|
],
|
||||||
|
return_type: Type::App {
|
||||||
|
constructor: Box::new(Type::Named("Result".to_string())),
|
||||||
|
args: vec![Type::Unit, Type::String],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
EffectOpDef {
|
||||||
|
name: "tryDelete".to_string(),
|
||||||
|
params: vec![("path".to_string(), Type::String)],
|
||||||
|
return_type: Type::App {
|
||||||
|
constructor: Box::new(Type::Named("Result".to_string())),
|
||||||
|
args: vec![Type::Unit, Type::String],
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -1507,6 +1539,16 @@ impl TypeEnv {
|
|||||||
Type::Option(Box::new(Type::var())),
|
Type::Option(Box::new(Type::var())),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
(
|
||||||
|
"findIndex".to_string(),
|
||||||
|
Type::function(
|
||||||
|
vec![
|
||||||
|
Type::List(Box::new(Type::var())),
|
||||||
|
Type::function(vec![Type::var()], Type::Bool),
|
||||||
|
],
|
||||||
|
Type::Option(Box::new(Type::Int)),
|
||||||
|
),
|
||||||
|
),
|
||||||
(
|
(
|
||||||
"any".to_string(),
|
"any".to_string(),
|
||||||
Type::function(
|
Type::function(
|
||||||
@@ -1571,6 +1613,30 @@ impl TypeEnv {
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
(
|
||||||
|
"zip".to_string(),
|
||||||
|
Type::function(
|
||||||
|
vec![
|
||||||
|
Type::List(Box::new(Type::var())),
|
||||||
|
Type::List(Box::new(Type::var())),
|
||||||
|
],
|
||||||
|
Type::List(Box::new(Type::Tuple(vec![Type::var(), Type::var()]))),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"flatten".to_string(),
|
||||||
|
Type::function(
|
||||||
|
vec![Type::List(Box::new(Type::List(Box::new(Type::var()))))],
|
||||||
|
Type::List(Box::new(Type::var())),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"contains".to_string(),
|
||||||
|
Type::function(
|
||||||
|
vec![Type::List(Box::new(Type::var())), Type::var()],
|
||||||
|
Type::Bool,
|
||||||
|
),
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
env.bind("List", TypeScheme::mono(list_module_type));
|
env.bind("List", TypeScheme::mono(list_module_type));
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
pub type Html<M> =
|
pub type Html<M> =
|
||||||
| Element(String, List<Attr<M>>, List<Html<M>>)
|
| Element(String, List<Attr<M>>, List<Html<M>>)
|
||||||
| Text(String)
|
| Text(String)
|
||||||
|
| RawHtml(String)
|
||||||
| Empty
|
| Empty
|
||||||
|
|
||||||
// Attributes that can be applied to elements
|
// Attributes that can be applied to elements
|
||||||
@@ -41,6 +42,7 @@ pub type Attr<M> =
|
|||||||
| OnKeyDown(fn(String): M)
|
| OnKeyDown(fn(String): M)
|
||||||
| OnKeyUp(fn(String): M)
|
| OnKeyUp(fn(String): M)
|
||||||
| DataAttr(String, String)
|
| DataAttr(String, String)
|
||||||
|
| Attribute(String, String)
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// Element builders - Container elements
|
// Element builders - Container elements
|
||||||
@@ -180,6 +182,28 @@ pub fn video<M>(attrs: List<Attr<M>>, children: List<Html<M>>): Html<M> =
|
|||||||
pub fn audio<M>(attrs: List<Attr<M>>, children: List<Html<M>>): Html<M> =
|
pub fn audio<M>(attrs: List<Attr<M>>, children: List<Html<M>>): Html<M> =
|
||||||
Element("audio", attrs, children)
|
Element("audio", attrs, children)
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Element builders - Document / Head elements
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
pub fn meta<M>(attrs: List<Attr<M>>): Html<M> =
|
||||||
|
Element("meta", attrs, [])
|
||||||
|
|
||||||
|
pub fn link<M>(attrs: List<Attr<M>>): Html<M> =
|
||||||
|
Element("link", attrs, [])
|
||||||
|
|
||||||
|
pub fn script<M>(attrs: List<Attr<M>>, children: List<Html<M>>): Html<M> =
|
||||||
|
Element("script", attrs, children)
|
||||||
|
|
||||||
|
pub fn iframe<M>(attrs: List<Attr<M>>, children: List<Html<M>>): Html<M> =
|
||||||
|
Element("iframe", attrs, children)
|
||||||
|
|
||||||
|
pub fn figure<M>(attrs: List<Attr<M>>, children: List<Html<M>>): Html<M> =
|
||||||
|
Element("figure", attrs, children)
|
||||||
|
|
||||||
|
pub fn figcaption<M>(attrs: List<Attr<M>>, children: List<Html<M>>): Html<M> =
|
||||||
|
Element("figcaption", attrs, children)
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// Element builders - Tables
|
// Element builders - Tables
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -285,6 +309,12 @@ pub fn onKeyUp<M>(h: fn(String): M): Attr<M> =
|
|||||||
pub fn data<M>(name: String, value: String): Attr<M> =
|
pub fn data<M>(name: String, value: String): Attr<M> =
|
||||||
DataAttr(name, value)
|
DataAttr(name, value)
|
||||||
|
|
||||||
|
pub fn attr<M>(name: String, value: String): Attr<M> =
|
||||||
|
Attribute(name, value)
|
||||||
|
|
||||||
|
pub fn rawHtml<M>(content: String): Html<M> =
|
||||||
|
RawHtml(content)
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// Utility functions
|
// Utility functions
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -319,6 +349,7 @@ pub fn renderAttr<M>(attr: Attr<M>): String =
|
|||||||
Checked(false) => "",
|
Checked(false) => "",
|
||||||
Name(n) => " name=\"" + n + "\"",
|
Name(n) => " name=\"" + n + "\"",
|
||||||
DataAttr(name, value) => " data-" + name + "=\"" + value + "\"",
|
DataAttr(name, value) => " data-" + name + "=\"" + value + "\"",
|
||||||
|
Attribute(name, value) => " " + name + "=\"" + value + "\"",
|
||||||
// Event handlers are ignored in static rendering
|
// Event handlers are ignored in static rendering
|
||||||
OnClick(_) => "",
|
OnClick(_) => "",
|
||||||
OnInput(_) => "",
|
OnInput(_) => "",
|
||||||
@@ -355,6 +386,7 @@ pub fn render<M>(html: Html<M>): String =
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
Text(content) => escapeHtml(content),
|
Text(content) => escapeHtml(content),
|
||||||
|
RawHtml(content) => content,
|
||||||
Empty => ""
|
Empty => ""
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -368,15 +400,47 @@ pub fn escapeHtml(s: String): String = {
|
|||||||
s4
|
s4
|
||||||
}
|
}
|
||||||
|
|
||||||
// Render a full HTML document
|
// Render a full HTML document (basic)
|
||||||
pub fn document(title: String, headExtra: List<Html<M>>, bodyContent: List<Html<M>>): String = {
|
pub fn document(title: String, headExtra: List<Html<M>>, bodyContent: List<Html<M>>): String = {
|
||||||
let headElements = List.concat([
|
let headElements = List.concat([
|
||||||
[Element("meta", [DataAttr("charset", "UTF-8")], [])],
|
[Element("meta", [Attribute("charset", "UTF-8")], [])],
|
||||||
[Element("meta", [Name("viewport"), Value("width=device-width, initial-scale=1.0")], [])],
|
[Element("meta", [Name("viewport"), Attribute("content", "width=device-width, initial-scale=1.0")], [])],
|
||||||
[Element("title", [], [Text(title)])],
|
[Element("title", [], [Text(title)])],
|
||||||
headExtra
|
headExtra
|
||||||
])
|
])
|
||||||
let doc = Element("html", [DataAttr("lang", "en")], [
|
let doc = Element("html", [Attribute("lang", "en")], [
|
||||||
|
Element("head", [], headElements),
|
||||||
|
Element("body", [], bodyContent)
|
||||||
|
])
|
||||||
|
"<!DOCTYPE html>\n" + render(doc)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render a full HTML document with SEO meta tags
|
||||||
|
pub fn seoDocument(
|
||||||
|
title: String,
|
||||||
|
description: String,
|
||||||
|
url: String,
|
||||||
|
ogImage: String,
|
||||||
|
headExtra: List<Html<M>>,
|
||||||
|
bodyContent: List<Html<M>>
|
||||||
|
): String = {
|
||||||
|
let headElements = List.concat([
|
||||||
|
[Element("meta", [Attribute("charset", "UTF-8")], [])],
|
||||||
|
[Element("meta", [Name("viewport"), Attribute("content", "width=device-width, initial-scale=1.0")], [])],
|
||||||
|
[Element("title", [], [Text(title)])],
|
||||||
|
[Element("meta", [Name("description"), Attribute("content", description)], [])],
|
||||||
|
[Element("meta", [Attribute("property", "og:title"), Attribute("content", title)], [])],
|
||||||
|
[Element("meta", [Attribute("property", "og:description"), Attribute("content", description)], [])],
|
||||||
|
[Element("meta", [Attribute("property", "og:type"), Attribute("content", "website")], [])],
|
||||||
|
[Element("meta", [Attribute("property", "og:url"), Attribute("content", url)], [])],
|
||||||
|
[Element("meta", [Attribute("property", "og:image"), Attribute("content", ogImage)], [])],
|
||||||
|
[Element("meta", [Name("twitter:card"), Attribute("content", "summary_large_image")], [])],
|
||||||
|
[Element("meta", [Name("twitter:title"), Attribute("content", title)], [])],
|
||||||
|
[Element("meta", [Name("twitter:description"), Attribute("content", description)], [])],
|
||||||
|
[Element("link", [Attribute("rel", "canonical"), Href(url)], [])],
|
||||||
|
headExtra
|
||||||
|
])
|
||||||
|
let doc = Element("html", [Attribute("lang", "en")], [
|
||||||
Element("head", [], headElements),
|
Element("head", [], headElements),
|
||||||
Element("body", [], bodyContent)
|
Element("body", [], bodyContent)
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -625,6 +625,41 @@ pub fn router(routes: List<Route>, notFound: fn(Request): Response): Handler =
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// Static File Serving
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
// Serve a static file from disk
|
||||||
|
pub fn serveStaticFile(basePath: String, requestPath: String): Response with {File} = {
|
||||||
|
let filePath = basePath + requestPath
|
||||||
|
if File.exists(filePath) then {
|
||||||
|
let content = File.read(filePath)
|
||||||
|
let mime = getMimeType(filePath)
|
||||||
|
{ status: 200, headers: [("Content-Type", mime)], body: content }
|
||||||
|
} else
|
||||||
|
{ status: 404, headers: textHeaders(), body: "Not Found" }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// Form Body Parsing
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
// Parse URL-encoded form body (same format as query strings)
|
||||||
|
pub fn parseFormBody(body: String): List<(String, String)> =
|
||||||
|
parseQueryParams(body)
|
||||||
|
|
||||||
|
// Get a form field value by name
|
||||||
|
pub fn getFormField(fields: List<(String, String)>, name: String): Option<String> =
|
||||||
|
getParam(fields, name)
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// Response Helpers
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
// Send a Response using HttpServer effect (convenience wrapper)
|
||||||
|
pub fn sendResponse(resp: Response): Unit with {HttpServer} =
|
||||||
|
HttpServer.respondWithHeaders(resp.status, resp.body, resp.headers)
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
// Example Usage
|
// Example Usage
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|||||||
Reference in New Issue
Block a user