Files
sx/examples/32-http-server.sx
agra 29784c22a8 mem: implicit-context foundation + many compiler fixes
The session-long set of changes that lay the groundwork for the
Jai-literal implicit-Context-parameter refactor. Lots of accumulated
work; the new arrival is the implicit-ctx foundation (steps 1+2 of
the plan in current/CHECKPOINT-MEM.md):

  Step 1 — `CAllocator :: struct {}` stateless allocator in
    library/modules/allocators.sx, delegating directly to
    libc_malloc/libc_free. `ConstantValue` in src/ir/inst.zig gains a
    `func_ref: FuncId` leaf so nested aggregates can carry function
    pointers (the inline Allocator value's fn-ptr fields). Switch
    sites updated in emit_llvm.zig, print.zig, interp.zig.

  Step 2 — `emitDefaultContextGlobal` in src/ir/lower.zig synthesises
    a static `__sx_default_context` global with a nested-aggregate
    init_val pointing at the CAllocator → Allocator thunks. The
    second-pass `initVtableGlobals` in emit_llvm.zig is generalised
    to handle `.aggregate` init_vals (re-emits after func_map is
    populated so func_ref leaves resolve to real symbols).

Also folded in from earlier work this session:

  - Phase 1.1: `xx value` heap-copy in `buildProtocolValue` routes
    through `context.allocator` via the new `allocViaContext` helper.
  - interp.zig: `marshalForeignArg` double-offset bug fixed —
    `heapSlice` already adds `hp.offset` to the slice ptr, so the
    extra `+ hp.offset` was scribbling memcpy/memset into adjacent
    heap state, corrupting `heap.items[0]`. Symptom: `build_format`
    at comptime produced zero bytes, all `print` calls failed.
  - Lazy lowering: `lazyLowerFunction` now declares foreign-body
    functions as extern stubs in the local (comptime) module so
    cross-module foreign calls resolve.
  - Allocator API: all stdlib allocators on one-line `init() -> *T`
    (CAllocator/GPA: libc-backed; Arena/TrackingAllocator: parent-
    backed; BufAlloc: embeds state at head of user buffer).
  - issues 0038 (transitive #import), 0039 (chess + stdlib migration
    fallout), 0040 (generic struct method dot-dispatch), 0041
    (pointer types as type-arg), 0042 (alias name resolution) — all
    fixed; regression tests in examples/.
  - Diagnostic: `emitError` now embeds the lowering's
    `current_source_file` and enclosing function in the literal
    message; SX_TRACE_UNRESOLVED=1 dumps a Zig stack trace at the
    emit site so misattributed spans can't hide where the failure
    is.
  - tools/verify-step.sh (all-platforms gate) and tools/scratch.sh
    (interp/codegen parity tester) added.

Test suite: 152 example tests pass; chess builds + screenshots on
macOS / iOS sim / Android.
2026-05-24 22:59:20 +03:00

81 lines
1.7 KiB
Plaintext

// HTTP server example (macOS only)
#import "modules/std.sx";
#import "modules/socket.sx";
// --- Logger ---
Logger :: struct {
prefix: string;
count: s64;
}
log :: (logger: *Logger, msg: string) {
logger.count += 1;
print("[{}] {}\n", logger.prefix, msg);
}
main :: () -> s32 {
PORT :: 8080;
fd := socket(AF_INET, SOCK_STREAM, 0);
if fd < 0 {
print("error: socket()\n");
return 1;
}
opt : s32 = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, @opt, 4);
addr := SockAddr.{ sin_len = 16, sin_family = 2, sin_port = htons(PORT) };
if bind(fd, @addr, 16) < 0 {
print("error: bind()\n");
return 1;
}
if listen(fd, 10) < 0 {
print("error: listen()\n");
return 1;
}
print("listening on http://localhost:{}\n", PORT);
arena := Arena.init(context.allocator, 65536);
logger := Logger.{ prefix = "http", count = 0 };
while true {
client := accept(fd, null, null);
if client < 0 { continue; }
push Context.{ allocator = xx arena, data = xx @logger } {
handle(client);
}
arena.reset();
close(client);
}
arena.deinit();
close(fd);
0;
}
handle :: (client: s32) {
// Read request
buf : [4096]u8 = ---;
read(client, buf, buf.len);
body :: "<html><body><h1>Hello from sx!</h1></body></html>";
response :: format("HTTP/1.1 200 OK\r
Content-Type: text/html\r
Connection: close\r
Content-Length: {}\r
\r\n{}", body.len, body);
write(client, response, response.len);
logger : *Logger = xx context.data;
log(logger, format("served request #{}", logger.count + 1));
}