From 40c509626e2c9b0eb3522f9b45a92e6f3e9a227a Mon Sep 17 00:00:00 2001 From: hanez Date: Wed, 28 Jan 2026 16:42:16 +0100 Subject: [PATCH 01/39] More documentation about internals. No code changes (0.38.0) --- docs/internals.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/docs/internals.md b/docs/internals.md index 9995968..b2a9637 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -285,6 +285,50 @@ We chose isolated state (like Lua) rather than a single global lock (like Python - Per‑VM scheduler: Green threads are multiplexed within a VM. Preemption is cooperative with periodic safe points; an optional time‑slice can yield between bytecode instruction groups when `FUN_DEBUG` or tracing is enabled. - Per‑VM GC: Stop‑the‑world, per‑VM. No global stop‑the‑world across VMs. A GC in one VM does not pause others. +### Shared memory as the escape hatch + +Message passing and serialization are the defaults. When copying becomes too expensive, use shared memory — but keep it outside the tracing heaps and very constrained: + +- Off‑heap, opaque buffers: Use `fun_shared_buffer` for large blobs (e.g., images, JSON bytes, tensors). These are refcounted, live outside any VM heap, and are immutable from the VM’s perspective. +- No heap pointers inside: Shared regions must not contain pointers into any VM heap. Treat them as raw bytes plus size/stride metadata. +- Synchronization via atomics/futexes (host side): If you need concurrent producers/consumers over shared buffers, build lock‑free queues or channels on the host using atomics. The VM sees only opaque handles. +- Lifetime: Governed by explicit ownership (retain/release), epochs, or arena lifetime — not by any VM’s GC. + +This provides zero‑copy hand‑off without coupling VMs or their collectors. + +### Do per‑VM GCs need to stop‑the‑world for shared regions? + +It depends on what “shared” means. Our design keeps per‑VM GCs independent by default: + +1) Untraced shared regions (recommended) + - Contents contain no GC pointers; GCs never scan them. + - Each VM can collect independently; no cross‑VM safepoints or barriers are required. + - Lifetime is managed explicitly (refcounts/finalizers/epochs). This is how `fun_shared_buffer` works. + +2) Shared, GC‑managed objects (generally avoid) + - If objects with pointers are genuinely shared across VMs, you need one of: + - Global safepoints with coordinated stop‑the‑world across participants; or + - A concurrent/incremental GC with cross‑VM read/write barriers and either a shared heap or remembered sets; or + - Replacing tracing with atomic refcounting for the shared objects. + - Complexity, latency, and correctness risks increase substantially. Fun intentionally avoids this mode. + +3) Hybrids + - Immutable shared objects with global refcounts and no pointers back into per‑VM heaps. + - Copy‑on‑write pages or rope/cord structures backed by `fun_shared_buffer`. + - Message passing that can “adopt” an off‑heap buffer by transferring ownership instead of copying. + +### Practical guidance + +- Default to isolated VMs and message passing. +- Use `fun_shared_buffer` only for zero‑copy payloads; keep them untraced and pointer‑free relative to VM heaps. +- Clearly document and enforce what types are shareable; forbid cross‑VM heap references. +- If you ever consider sharing GC‑managed objects, budget for global safepoints or a fully barriered concurrent GC — neither is planned for Fun’s core. + +### Bottom line + +- Isolates are the sensible default; shared‑memory primitives are the performance escape hatch. +- With off‑heap, untraced shared regions, per‑VM GCs stay independent and never have to stop the world across other VMs. + ### Embedding patterns - Parallelism: Create N VMs for N cores, wire them with channels or shared buffers. No global lock contention. From 058631e11b26c8ad50b0111336c206f6f50d3403 Mon Sep 17 00:00:00 2001 From: hanez Date: Wed, 28 Jan 2026 16:55:39 +0100 Subject: [PATCH 02/39] More documentation about internals. No code changes (0.38.0) --- docs/internals.md | 112 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 110 insertions(+), 2 deletions(-) diff --git a/docs/internals.md b/docs/internals.md index b2a9637..5ce70a2 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -256,8 +256,6 @@ From vm.h defaults (tuned for simplicity; adjust if needed): ## Concurrency, isolates, and garbage collection -### Short answer - We chose isolated state (like Lua) rather than a single global lock (like Python’s GIL). Each VM has its own heap, scheduler, and GC. There are no cross‑VM pointers. Concurrency and data exchange happen via message passing and a few carefully scoped shared‑memory primitives for high‑throughput use cases. This keeps the C API simple, predictable, and safe to embed in multi‑threaded hosts. ### Concurrency model @@ -296,6 +294,116 @@ Message passing and serialization are the defaults. When copying becomes too exp This provides zero‑copy hand‑off without coupling VMs or their collectors. +### Zero-Copy Shared Buffering + +- We default to isolates for safety and scaling. +- Zero‑copy sharing is done with `fun_shared_buffer`, an off‑heap, GC‑untracked, pointer‑free block that’s immutable from the VM’s point of view. +- Lifetime is managed with plain reference counting (`retain/release`). +- For hot paths, we also support an adoption (ownership‑transfer) pattern during message passing so the sender can drop its ref without copying. + +#### How zero‑copy is kept safe + +- Off‑heap + untraced: `fun_shared_buffer` lives outside any VM heap, so per‑VM GCs never scan it and never need cross‑VM barriers. +- Immutable inside VMs: once a buffer is visible to any VM, it is treated as read‑only by that VM code. That avoids aliasing hazards and lets multiple VMs parse the same bytes concurrently. +- Pointer‑free contract: the buffer contains raw bytes only (no pointers into VM heaps), which prevents accidental cross‑heap reachability. + +#### Lifetime model + +- Global refcount on the shared object. + - `fun_shared_buffer_retain`/`fun_shared_buffer_release` drive deallocation. + - VMs just hold handles; the buffer’s memory is not traced by any VM. +- Host mutation policy: + - You may fill/mutate the buffer before publication (while only the host holds a ref). + - After passing it into any VM or port, treat it as immutable; further mutation must be done by creating a new buffer or by using host‑side synchronization and not exposing the mutated view to VMs that assume immutability. + +#### Ownership transfer (adoption) + +- Message passing can “adopt” a buffer: instead of copying, the sender passes the handle and typically `release`s its ref after send. +- The receiver `retain`s upon receipt if it needs to outlive the message scope. +- This gives you zero‑copy with a clear single‑writer → multi‑reader handoff pattern. + +#### Why not share GC‑managed objects? + +- Sharing traced objects would require global safepoints or a fully barriered concurrent GC across VMs, or switching to atomic RC for those objects. We avoid that entirely; only off‑heap `fun_shared_buffer` is shared. + +#### Minimal API (illustrative) + +```c +// Zero-copy shared buffers (immutable inside VMs) +fun_shared_buffer_t* fun_shared_buffer_new(size_t n); +void* fun_shared_buffer_data(fun_shared_buffer_t*); +void fun_shared_buffer_retain(fun_shared_buffer_t*); +void fun_shared_buffer_release(fun_shared_buffer_t*); + +// Ports/channels for inter-VM comms +fun_port_t* fun_port_create(fun_vm_t*); +int fun_send(fun_port_t*, fun_value_t value); // can carry a shared buffer handle +int fun_recv(fun_port_t*, fun_value_t* out, uint64_t timeout_ms); +``` + +#### Practical usage tips + +- Default to isolates + ports for logic; use `fun_shared_buffer` only for large payloads (images, tensors, blobs). +- If you need shared mutability from native code, keep it outside the VM and guard with `fun_mutex_t`/`fun_rwlock_t` or `fun_atomic_*`. Don’t expose mutable state to VMs. +- Document clearly when a buffer is “published” to VMs; after that point, treat it as immutable and rely on refcounts for lifetime. + +#### Bottom line + +- It’s reference counting by default, with an optional ownership‑transfer handoff in message passing to avoid copies. This keeps the host API small and predictable while preserving GC isolation and safety. + +### Immutable Buffer Sync via Ports + +We don’t expose shared mutability to VMs. The trick is: publish‑as‑immutable plus adoption via ports. Ports/queues do the synchronization; `fun_shared_buffer` is off‑heap and refcounted with atomic ops. The host doesn’t need to lock anything for the common paths. + +#### What removes the host’s synchronization burden + +- Immutable after publication + - Host fills a `fun_shared_buffer` while it’s private, then “publishes” it by sending through a port. From that point, all VM code treats it as read‑only. No data races; no host locks. +- Port/queue owns the concurrency + - `fun_send`/`fun_recv` operate on an internal MPMC queue with the necessary atomics/fences. You don’t implement a queue nor protect it; the runtime does. +- Adoption (ownership transfer) + - `fun_send` can adopt a buffer handle. Sender drops its ref after send; receiver retains if needed. Lifetime is clear without locks. +- Atomic refcounting only + - The only shared mutable state is the buffer’s global refcount, updated atomically inside the runtime. You don’t touch it. +- VM thread affinity + - You never call into a VM from arbitrary threads; use `fun_vm_post` to hop to the owning thread. This avoids host‑side marshaling races. + +#### Typical pattern (no locks needed) + +```c +fun_shared_buffer_t* b = fun_shared_buffer_new(n); +void* p = fun_shared_buffer_data(b); +memcpy(p, src, n); // fill while private + +fun_send(port, fun_wrap_shared(b)); // publish + adopt +fun_shared_buffer_release(b); // drop sender’s ref (optional if send adopts) + +// On receiver side +fun_value_t v; +if (fun_recv(port, &v, 1000) == 0) { + fun_shared_buffer_t* r = fun_unwrap_shared(v); + // r is read‑only to VMs; parse/process concurrently without locks + // Retain if it must outlive the message scope + fun_shared_buffer_retain(r); + … + fun_shared_buffer_release(r); +} +``` + +#### When would the host ever sync? + +- Only if you choose shared mutability outside the VM (e.g., a lock‑free ring buffer you manage). For that, we expose optional helpers (`fun_atomic_*`, `fun_mutex_t`, `fun_rwlock_t`), but they’re not required for the standard zero‑copy path. + +#### Guarantees provided by the runtime + +- Publication fences around `fun_send`/`fun_recv` ensure bytes written before send are visible to receivers without extra barriers. +- Buffers are pointer‑free relative to VM heaps, so no cross‑heap reachability or GC coordination is needed. +- Refcount updates are atomic; deallocation happens when the global count drops to zero. + +#### Bottom line + +- You don’t synchronize shared data: you publish immutable blobs and let ports handle concurrency and lifetime via atomic refcounting and adoption. Locks are only needed if you intentionally build shared mutable structures outside this model. + ### Do per‑VM GCs need to stop‑the‑world for shared regions? It depends on what “shared” means. Our design keeps per‑VM GCs independent by default: From 87833b0c1e09b075064297d2443080355ed2bee6 Mon Sep 17 00:00:00 2001 From: hanez Date: Wed, 28 Jan 2026 23:10:12 +0100 Subject: [PATCH 03/39] Added some documentation on how to implement opcodes in Rust. No code changes (0.38.0) --- docs/rust.md | 197 ++++++++++++++++++++++++++++++++++++++++ examples/features.fun | 0 examples/rust_hello.fun | 0 3 files changed, 197 insertions(+) create mode 100644 docs/rust.md mode change 100644 => 100755 examples/features.fun mode change 100644 => 100755 examples/rust_hello.fun diff --git a/docs/rust.md b/docs/rust.md new file mode 100644 index 0000000..9a884bc --- /dev/null +++ b/docs/rust.md @@ -0,0 +1,197 @@ +# Writing Rust-backed opcodes for Fun VM + +This guide explains how to implement VM opcodes in Rust, wire them into the C VM, and use them from Fun scripts. + +It assumes you are comfortable with basic Rust and C and have a working Fun checkout. + +## Overview + +Fun’s VM is written in C, but you can implement opcode handlers in Rust and call them via FFI. The typical flow is: + +1) Write a Rust function with a stable C ABI (extern "C", #[no_mangle]) that takes a pointer to the VM and returns an int status code. +2) Use VM stack helpers (exposed to Rust via FFI) to pop arguments and push results. +3) Expose that Rust function to the C VM by calling it from the opcode dispatch (a case in the VM’s opcode switch or a small shim under src/vm/rust/). +4) Add or reuse a Fun builtin that maps to your opcode, then call it from Fun code. + +## Project layout (relevant parts) + +- src/rust/src/lib.rs — Rust library with exported opcode functions and FFI helpers. +- src/vm/rust/ — C-side wiring examples and small opcode cases calling into Rust. +- examples/rust_hello.fun — Example Fun script using a Rust-backed opcode. +- docs/opcodes.md — General overview of many built-in opcodes (mostly C-based). + +## Enabling Rust in the build + +Rust integration is optional and gated by a CMake flag. Default builds usually have it OFF. + +Enable it for a configured profile (Debug or Release): + +- Debug example: + cmake -S . -B build_debug -DFUN_WITH_RUST=ON + cmake --build build_debug --target fun + +- Release example: + cmake -S . -B build_release -DFUN_WITH_RUST=ON + cmake --build build_release --target fun + +Useful targets in this repository include: +- fun — the main executable +- rust_ops_build — helps build/link Rust ops when enabled +- test_opcodes — test executable (if you want to extend tests) + +Note: In CLion, prefer building with one of the provided CMake profiles (Debug/Release) and avoid creating custom build directories. + +## Writing an opcode in Rust + +The Rust side is a no_std static library exposing C ABI functions that the VM can call. See src/rust/src/lib.rs for examples already in the tree. + +Key points: +- Use extern "C" and #[no_mangle] to fix the symbol name. +- Take a raw pointer to the VM as *mut Vm; return i32 status (0 for success). +- Interact with the VM stack via helper FFI functions declared as externs. +- Provide a minimal panic handler (no_std) as shown in lib.rs. + +Example: integer addition opcode implemented in Rust. + +In src/rust/src/lib.rs: + + #![no_std] + + #[repr(C)] + pub struct Vm; + + extern "C" { + fn vm_pop_i64(vm: *mut Vm) -> i64; + fn vm_push_i64(vm: *mut Vm, v: i64); + } + + #[no_mangle] + pub extern "C" fn fun_op_radd(vm: *mut Vm) -> i32 { + unsafe { + let b = vm_pop_i64(vm); + let a = vm_pop_i64(vm); + vm_push_i64(vm, a + b); + } + 0 + } + + #[panic_handler] + fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} } + +What this does: +- Pops two 64-bit integers from the VM stack. +- Pushes back their sum. +- Returns 0 to indicate success to the VM. + +You can add more extern helpers (e.g., for strings, arrays, maps) once they are exposed by the C VM. The repository already includes a simple string example returning a const char* from Rust, see fun_rust_get_string() usage below. + +## Wiring the opcode in C + +To make the VM call your Rust opcode, add a small C-side case that invokes the exported Rust symbol. A minimal pattern lives under src/vm/rust/. + +String demo wiring (already present): src/vm/rust/hello.c + + case OP_RUST_HELLO: { + #ifdef FUN_WITH_RUST + const char *s = fun_rust_get_string(); + if (!s) s = ""; + push_value(vm, make_string(s)); + #else + vm_raise_error(vm, "RUST_HELLO requires FUN_WITH_RUST=ON at build time"); + push_value(vm, make_nil()); + #endif + break; + } + +For a stack-based math opcode (like fun_op_radd), you would declare and call the Rust function similarly: + + #ifdef FUN_WITH_RUST + extern int fun_op_radd(void* vm); // or use the proper VM type if available + #endif + + case OP_RADD: { + #ifdef FUN_WITH_RUST + (void)fun_op_radd(vm); + #else + vm_raise_error(vm, "RADD requires FUN_WITH_RUST=ON at build time"); + push_value(vm, make_nil()); // or follow your opcode’s error convention + #endif + break; + } + +Notes: +- Follow the existing opcode conventions for your module (core, math, strings, etc.). +- If your build puts the Rust symbol into a static library, make sure the VM target links it when FUN_WITH_RUST is ON (the top-level CMake already does this for the examples provided). + +## Using Rust-backed opcodes from Fun + +Once wired, expose the opcode via a builtin function or directly in bytecode. The repository includes a demo builtin rust_hello() that returns a Rust-generated string. + +Run the example: + +1) Build with Rust enabled (Debug): + cmake -S . -B build_debug -DFUN_WITH_RUST=ON + cmake --build build_debug --target fun + +2) Execute the script: + build_debug/fun examples/rust_hello.fun + +Expected output: + Hello from Rust ops! + +If you build without Rust, calling rust_hello() raises a runtime error indicating that Rust integration is disabled. + +## Stack discipline and error handling + +- Always pop exactly the arguments you expect and push exactly the results your opcode promises. Mismatch leads to stack corruption and hard-to-debug failures. +- Return an int status to the VM (0 for success). If your project uses a different convention for some opcodes, match it consistently. +- Validate types where appropriate (e.g., ensure values are integers before arithmetic). If a check fails, use the VM’s error mechanism (e.g., vm_raise_error) and follow the module’s convention on what to push after errors. + +## Data types and FFI surface + +The minimal helpers shown cover 64-bit integers and simple strings. Extending the Rust<->C bridge usually involves: +- Declaring additional extern "C" functions in Rust that the C VM implements (to read/write values on the stack, construct arrays/maps/strings, etc.). +- Ensuring all pointers and lifetimes are well-defined: strings pushed to the VM should be copied or allocated using VM facilities so they remain valid after the call. +- Keeping Rust no_std unless you add an allocator and link setup to support std. + +## Troubleshooting + +- Link errors: Make sure FUN_WITH_RUST=ON for your build directory and that the Rust library is compiled before linking the VM. Use the rust_ops_build target if provided by your profile. +- Missing symbol at runtime: Confirm #[no_mangle] and extern "C" on the Rust function and that C sees the correct prototype. +- Wrong or garbled values: Double-check stack order (Fun uses a stack VM; many ops pop in reverse order: first b, then a). +- No output from rust_hello(): Ensure you run a binary built with FUN_WITH_RUST=ON; otherwise the VM deliberately raises an error and returns Nil for that call. + +## Small end-to-end checklist + +1) Write the Rust function in src/rust/src/lib.rs with extern "C", #[no_mangle]. +2) Use FFI helpers to pop arguments and push results. +3) Add a C-side case under src/vm/... (or src/vm/rust/...) that calls your Rust function when the opcode executes. +4) Ensure the build links Rust code when FUN_WITH_RUST=ON. +5) Add or reuse a builtin in the parser/runtime to surface your opcode to Fun code. +6) Build and run a small .fun example to validate behavior. + +## References in this repo + +- Rust lib with examples: src/rust/src/lib.rs +- C-side hello wiring: src/vm/rust/hello.c +- Demo script: examples/rust_hello.fun +- General opcode reference: docs/opcodes.md + +## Links + +Authoritative and practical resources on exposing Rust to C (FFI) and maintaining a C-compatible API: + +- Rustonomicon: FFI overview and best practices + https://doc.rust-lang.org/nomicon/ffi.html +- Rustonomicon: Calling Rust code from C + https://doc.rust-lang.org/nomicon/ffi.html#calling-rust-code-from-c +- The Rust Book: Unsafe and FFI (extern, #[no_mangle], calling Rust from other languages) + https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html#calling-rust-functions-from-other-languages +- Rust Reference: extern blocks, ABIs, and linkage + https://doc.rust-lang.org/reference/items/external-blocks.html +- Rust FFI Omnibus (examples for many patterns, including Rust ↔ C) + https://github.com/shepmaster/rust-ffi-omnibus +- cbindgen (generate C headers from Rust libraries) + https://cbindgen.github.io/cbindgen/ +- bindgen (generate Rust bindings to existing C headers; useful when mixing C and Rust) + https://github.com/rust-lang/rust-bindgen diff --git a/examples/features.fun b/examples/features.fun old mode 100644 new mode 100755 diff --git a/examples/rust_hello.fun b/examples/rust_hello.fun old mode 100644 new mode 100755 From 543483041b64b11e49e77c68065db9086fb2e780 Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 29 Jan 2026 00:53:34 +0100 Subject: [PATCH 04/39] Some arg Fun in Rust. (0.38.1) --- CMakeLists.txt | 2 +- cmake/Targets.cmake | 10 +++ .../{extra => blocking}/http_server_test.fun | 0 examples/extra/pcsc_demo.fun | 6 +- examples/rust_hello.fun | 4 + examples/rust_hello_args.fun | 37 ++++++++ lib/io/pcsc.fun | 85 ++++++------------- make | 23 +++++ src/bytecode.c | 1 + src/bytecode.h | 1 + src/parser.c | 8 ++ src/rust/Cargo.toml | 3 + src/rust/eh_personality.c | 2 + src/rust/src/lib.rs | 21 ++++- src/vm.h | 4 +- src/vm/rust/hello.c | 26 ++++++ 16 files changed, 167 insertions(+), 66 deletions(-) rename examples/{extra => blocking}/http_server_test.fun (100%) create mode 100755 examples/rust_hello_args.fun create mode 100644 src/rust/eh_personality.c diff --git a/CMakeLists.txt b/CMakeLists.txt index fbfca89..7d93022 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.0 LANGUAGES C) +project(fun VERSION 0.38.1 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) diff --git a/cmake/Targets.cmake b/cmake/Targets.cmake index c1db251..dbdb7da 100644 --- a/cmake/Targets.cmake +++ b/cmake/Targets.cmake @@ -90,6 +90,16 @@ if(FUN_WITH_TCLTK) target_compile_definitions(fun_core PUBLIC FUN_WITH_TCLTK=1) endif() +# Workaround: provide a dummy rust_eh_personality to satisfy linker when using +# no_std Rust staticlib with panic abort (some toolchains still reference it). +# If needed, we could add a C shim here, but the Rust crate now defines +# rust_eh_personality itself, so no extra C sources are required. +if(FUN_WITH_RUST) + if(TARGET fun) + target_sources(fun PRIVATE ${CMAKE_SOURCE_DIR}/src/rust/eh_personality.c) + endif() +endif() + # Special case for libxml2 system include path if enabled if(FUN_WITH_XML2) if(EXISTS "/usr/include/libxml2") diff --git a/examples/extra/http_server_test.fun b/examples/blocking/http_server_test.fun similarity index 100% rename from examples/extra/http_server_test.fun rename to examples/blocking/http_server_test.fun diff --git a/examples/extra/pcsc_demo.fun b/examples/extra/pcsc_demo.fun index 850ace6..47d1572 100755 --- a/examples/extra/pcsc_demo.fun +++ b/examples/extra/pcsc_demo.fun @@ -33,9 +33,9 @@ if len(readers) > 0 if h != 0 // Sample APDU: SELECT MF (00 A4 00 00 02 3F 00) - resp = pc.transmit_hex(h, "00A40000023F00") - // Print hex data and SW - print("resp.data_hex=" + resp["data_hex"]) + // Use the safe convenience transmitter which returns a map {data, sw1, sw2, code} + resp = pc.transmit("00A40000023F00") + print("resp.data.len=" + to_string(len(resp["data"])) + " bytes") print("resp.sw1=" + to_string(resp["sw1"]) + " sw2=" + to_string(resp["sw2"]) + " code=" + to_string(resp["code"])) _ = pc.disconnect(h) diff --git a/examples/rust_hello.fun b/examples/rust_hello.fun index 5cd23d2..e5455db 100755 --- a/examples/rust_hello.fun +++ b/examples/rust_hello.fun @@ -30,3 +30,7 @@ */ print(rust_hello()) + +/* Expected output: +Hello from Rust ops! +*/ diff --git a/examples/rust_hello_args.fun b/examples/rust_hello_args.fun new file mode 100755 index 0000000..9fd2e70 --- /dev/null +++ b/examples/rust_hello_args.fun @@ -0,0 +1,37 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2025 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-01-28 + */ + +/* + * Rust-backed opcode demo with argument: rust_hello_args(STRING) + * + * Build instructions: + * - Rust integration is optional. Enable via: + * cmake -S . -B build_debug -DFUN_WITH_RUST=ON + * - Then build: + * cmake --build build_debug --target fun + * + * Run: + * build_debug/fun examples/rust_hello_args.fun + * + * Expected output (with FUN_WITH_RUST=ON): + * Hello from Fun to Rust! + * + * Note: + * The opcode prints from Rust and returns Nil, so there's nothing to print afterwards. + */ + +rust_hello_args("Hello from Fun to Rust!") + +/* Expected output: +Hello from Fun to Rust! +*/ diff --git a/lib/io/pcsc.fun b/lib/io/pcsc.fun index feb9263..14cc764 100644 --- a/lib/io/pcsc.fun +++ b/lib/io/pcsc.fun @@ -17,11 +17,9 @@ include -/* +// Unified PCSC class API class PCSC() - // ---- hex helpers moved to lib/hex.fun ---- - - // ---- PCSC wrappers ---- + // ---- Context management ---- fun establish(this) // returns ctx id (>0) or 0 return pcsc_establish() @@ -36,6 +34,16 @@ class PCSC() return [] return readers + // Convenience: get readers without managing ctx externally + fun get_readers(this) + ctx = pcsc_establish() + readers = pcsc_list_readers(ctx) + _ = pcsc_release(ctx) + if readers == nil + return [] + return readers + + // ---- Connection management ---- fun connect(this, ctx, reader_name) // returns handle id (>0) or 0 return pcsc_connect(ctx, to_string(reader_name)) @@ -44,6 +52,7 @@ class PCSC() // returns 1 on success or 0 return pcsc_disconnect(handle) + // ---- Transmit helpers ---- // Transmit raw APDU bytes (array of numbers 0..255). Returns map {"data":[], "sw1":n, "sw2":n, "code":n} fun transmit_bytes(this, handle, bytes) res = pcsc_transmit(handle, bytes) @@ -77,22 +86,12 @@ class PCSC() m["sw2"] = res["sw2"] m["code"] = res["code"] return m -*/ -// This class is in a very early stage of development. -class PCSC() - fun get_readers(this) - ctx = pcsc_establish() - readers = pcsc_list_readers(ctx) - _ = pcsc_release(ctx) - return readers - - // Transmit a raw hex APDU to the first available reader and print the result map + // Convenience: Transmit a raw hex APDU to the first available reader and return the result map fun transmit(this, hex_apdu) ctx = pcsc_establish() readers = pcsc_list_readers(ctx) if (readers == nil) - print([]) _ = pcsc_release(ctx) // return a default result map instead of 0, so callers can index fields safely m = {} @@ -102,7 +101,6 @@ class PCSC() m["code"] = -2 return m if (len(readers) == 0) - print([]) _ = pcsc_release(ctx) m = {} m["data"] = [] @@ -110,50 +108,19 @@ class PCSC() m["sw2"] = -1 m["code"] = -2 return m - // Actually selecting the second reader hardcoded. + // Select the second reader (index 1) as previously used in examples handle = pcsc_connect(ctx, readers[1]) - apdu = this.hex_to_bytes(hex_apdu) - res = pcsc_transmit(handle, apdu) + apdu_bytes = hex_to_bytes(hex_apdu) + res = pcsc_transmit(handle, apdu_bytes) _ = pcsc_disconnect(handle) _ = pcsc_release(ctx) + if res == nil + m = {} + m["data"] = [] + m["sw1"] = -1 + m["sw2"] = -1 + m["code"] = -2 + return m + if res["data"] == nil + res["data"] = [] return res - - fun hex_digit(this, ch) - m = {} - m["0"] = 0 - m["1"] = 1 - m["2"] = 2 - m["3"] = 3 - m["4"] = 4 - m["5"] = 5 - m["6"] = 6 - m["7"] = 7 - m["8"] = 8 - m["9"] = 9 - m["a"] = 10 - m["A"] = 10 - m["b"] = 11 - m["B"] = 11 - m["c"] = 12 - m["C"] = 12 - m["d"] = 13 - m["D"] = 13 - m["e"] = 14 - m["E"] = 14 - m["f"] = 15 - m["F"] = 15 - v = m[ch] - if v == nil - return 0 - return v - - fun hex_to_bytes(this, hex) - s = to_string(hex) - out = [] - number i = 0 - number n = len(s) - while i + 1 < n - number b = this.hex_digit(substr(s, i, 1)) * 16 + this.hex_digit(substr(s, i + 1, 1)) - push(out, b) - i = i + 2 - return out diff --git a/make b/make index b0d587a..18c5969 100755 --- a/make +++ b/make @@ -88,6 +88,27 @@ elif [ "$target" = "repl" ]; then && cmake -S . -B build \ -DFUN_WITH_REPL=ON \ && cmake --build build --target fun +elif [ "$target" = "rust_all" ]; then + rm -rf build && rm -rf src/rust/target \ + && cmake -S . -B build \ + -DFUN_WITH_PCSC=ON \ + -DFUN_WITH_REPL=ON \ + -DFUN_WITH_LIBSQL=ON \ + -DFUN_WITH_SQLITE=ON \ + -DFUN_WITH_CURL=ON \ + -DFUN_WITH_PCRE2=ON \ + -DFUN_WITH_XML2=ON \ + -DFUN_WITH_JSON=ON \ + -DFUN_WITH_TCLTK=ON \ + -DFUN_WITH_INI=ON \ + -DFUN_WITH_RUST=ON \ + -DFUN_DEBUG=OFF \ + && cmake --build build --target fun +elif [ "$target" = "rust_minimal" ]; then + rm -rf build && rm -rf src/rust/target \ + && cmake -S . -B build \ + -DFUN_WITH_RUST=ON \ + && cmake --build build --target fun else echo "Build target $target not found... aborting!"; echo "Available targets:"; @@ -100,5 +121,7 @@ else echo " - minimal"; echo " - musl"; echo " - repl"; + echo " - rust_all"; + echo " - rust_minimal"; fi diff --git a/src/bytecode.c b/src/bytecode.c index 58b62a8..82d8ca1 100644 --- a/src/bytecode.c +++ b/src/bytecode.c @@ -207,6 +207,7 @@ static const char *opcode_name(OpCode op) { case OP_FMIN: return "FMIN"; case OP_FMAX: return "FMAX"; case OP_RUST_HELLO: return "RUST_HELLO"; + case OP_RUST_HELLO_ARGS: return "RUST_HELLO_ARGS"; default: return "???"; } } diff --git a/src/bytecode.h b/src/bytecode.h index 0cb4908..81c12c1 100644 --- a/src/bytecode.h +++ b/src/bytecode.h @@ -265,6 +265,7 @@ typedef enum { // Rust FFI demo opcode(s) OP_RUST_HELLO, // pushes string returned from Rust (hello world) + OP_RUST_HELLO_ARGS, // pops message string; prints it via Rust; pushes Nil /* Notcurses TUI (optional) */ OP_NC_INIT, // initializes Notcurses; returns 1 on success, 0 on failure diff --git a/src/parser.c b/src/parser.c index 78da293..bef13c9 100644 --- a/src/parser.c +++ b/src/parser.c @@ -793,6 +793,14 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos) free(name); return 1; } + if (strcmp(name, "rust_hello_args") == 0) { + (*pos)++; /* '(' */ + if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "rust_hello_args expects (message:string)"); free(name); return 0; } + if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "Expected ')' after rust_hello_args arg"); free(name); return 0; } + bytecode_add_instruction(bc, OP_RUST_HELLO_ARGS, 0); + free(name); + return 1; + } if (strcmp(name, "os_list_dir") == 0) { (*pos)++; /* '(' */ if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "os_list_dir expects (path)"); free(name); return 0; } diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index a6c7500..1080d9f 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -6,6 +6,9 @@ edition = "2021" [lib] crate-type = ["staticlib"] +[profile.dev] +panic = "abort" + [profile.release] panic = "abort" # Optimize for minimal size diff --git a/src/rust/eh_personality.c b/src/rust/eh_personality.c new file mode 100644 index 0000000..666aec0 --- /dev/null +++ b/src/rust/eh_personality.c @@ -0,0 +1,2 @@ +/* Workaround for linking Rust staticlib in no_std/abort mode on some toolchains */ +void rust_eh_personality(void) {} diff --git a/src/rust/src/lib.rs b/src/rust/src/lib.rs index 12121ed..115785b 100644 --- a/src/rust/src/lib.rs +++ b/src/rust/src/lib.rs @@ -11,8 +11,8 @@ #![no_std] -#[repr(C)] -pub struct Vm; +// Use an FFI-safe opaque handle for the VM pointer +pub type Vm = core::ffi::c_void; extern "C" { fn vm_pop_i64(vm: *mut Vm) -> i64; @@ -37,6 +37,23 @@ pub extern "C" fn fun_rust_get_string() -> *const core::ffi::c_char { b"Hello from Rust ops!\0".as_ptr() as *const _ } +// Print a C string via libc printf to stdout (acceptable under no_std via extern) +#[no_mangle] +pub extern "C" fn fun_rust_print_string(msg: *const core::ffi::c_char) -> i32 { + unsafe { + extern "C" { + fn printf(fmt: *const core::ffi::c_char, ...) -> i32; + } + let fmt = b"%s\n\0".as_ptr() as *const core::ffi::c_char; + printf(fmt, msg); + } + 0 +} + +// Provide personality symbol to satisfy some linkers in no_std builds +#[no_mangle] +pub extern "C" fn rust_eh_personality() {} + // Minimal panic handler for no_std; abort behavior requested via Cargo profile #[panic_handler] fn panic(_info: &core::panic::PanicInfo) -> ! { diff --git a/src/vm.h b/src/vm.h index 0e1d528..e746a96 100644 --- a/src/vm.h +++ b/src/vm.h @@ -56,7 +56,7 @@ static const char *opcode_names[] = { "TRY_PUSH","TRY_POP","THROW", "FMIN","FMAX", /* Rust FFI demo */ - "RUST_HELLO", + "RUST_HELLO","RUST_HELLO_ARGS", /* Notcurses TUI (optional) */ "NC_INIT","NC_SHUTDOWN","NC_CLEAR","NC_DRAW_TEXT","NC_GETCH" }; @@ -157,5 +157,7 @@ int fun_op_radd(VM *vm); /* Example Rust function returning a demo C string (null-terminated). */ const char *fun_rust_get_string(void); +/* Rust function that prints a passed C string, returns 0 on success. */ +int fun_rust_print_string(const char *msg); #endif diff --git a/src/vm/rust/hello.c b/src/vm/rust/hello.c index 709d8c6..6878c46 100644 --- a/src/vm/rust/hello.c +++ b/src/vm/rust/hello.c @@ -25,3 +25,29 @@ case OP_RUST_HELLO: { #endif break; } + +/* + * Rust FFI demo opcode with argument: OP_RUST_HELLO_ARGS + * Pops a string from the stack and asks Rust to print it. Pushes Nil. + */ +case OP_RUST_HELLO_ARGS: { +#ifdef FUN_WITH_RUST + Value vmsg = pop_value(vm); + char *msg = value_to_string_alloc(&vmsg); + free_value(vmsg); + if (msg) { + fun_rust_print_string(msg); + free(msg); + } else { + fun_rust_print_string(""); + } + push_value(vm, make_nil()); +#else + /* Still pop and free the arg to keep stack sane */ + Value vmsg = pop_value(vm); + free_value(vmsg); + vm_raise_error(vm, "RUST_HELLO_ARGS requires FUN_WITH_RUST=ON at build time"); + push_value(vm, make_nil()); +#endif + break; +} From c2e7f3869ea5661c91e8cd1dd40b7f095059f501 Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 29 Jan 2026 02:53:14 +0100 Subject: [PATCH 05/39] Some more Fun VM and Rust interaction. (0.38.2) --- CMakeLists.txt | 2 +- cmake/Targets.cmake | 1 - docs/rust.md | 2 ++ examples/rust_hello.fun | 2 +- examples/rust_hello_args.fun | 2 +- examples/rust_vm_access.fun | 39 ++++++++++++++++++++++++++++++++++++ src/bytecode.c | 2 ++ src/bytecode.h | 2 ++ src/parser.c | 15 ++++++++++++++ src/rust/src/lib.rs | 16 +++------------ src/rust/src/vm/mod.rs | 36 ++++++++++++++++++++++++++++++++- src/vm.c | 33 ++++++++++++++++++++++++++++++ src/vm.h | 22 +++++++++++++++++++- src/vm/rust/get_sp.c | 26 ++++++++++++++++++++++++ src/vm/rust/hello.c | 28 +------------------------- src/vm/rust/hello_args.c | 36 +++++++++++++++++++++++++++++++++ src/vm/rust/set_exit.c | 33 ++++++++++++++++++++++++++++++ 17 files changed, 251 insertions(+), 46 deletions(-) create mode 100644 examples/rust_vm_access.fun create mode 100644 src/vm/rust/get_sp.c create mode 100644 src/vm/rust/hello_args.c create mode 100644 src/vm/rust/set_exit.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 7d93022..1e619dc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.1 LANGUAGES C) +project(fun VERSION 0.38.2 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) diff --git a/cmake/Targets.cmake b/cmake/Targets.cmake index dbdb7da..99146ec 100644 --- a/cmake/Targets.cmake +++ b/cmake/Targets.cmake @@ -17,7 +17,6 @@ target_include_directories(fun_core PUBLIC # Apply options to core if(FUN_DEBUG) - message(STATUS "FUN_DEBUG enabled: building with verbose debug logging") target_compile_definitions(fun_core PUBLIC FUN_VERSION="${PROJECT_VERSION}") target_compile_definitions(fun_core PUBLIC FUN_DEBUG=1) endif() diff --git a/docs/rust.md b/docs/rust.md index 9a884bc..9657c1f 100644 --- a/docs/rust.md +++ b/docs/rust.md @@ -1,5 +1,7 @@ # Writing Rust-backed opcodes for Fun VM +!!! CAUTION !!! I am not very experienced in using Rust. This should show that it is possible to implement opcodes in Rust and integrate them with the Fun VM. + This guide explains how to implement VM opcodes in Rust, wire them into the C VM, and use them from Fun scripts. It assumes you are comfortable with basic Rust and C and have a working Fun checkout. diff --git a/examples/rust_hello.fun b/examples/rust_hello.fun index e5455db..434da0e 100755 --- a/examples/rust_hello.fun +++ b/examples/rust_hello.fun @@ -4,7 +4,7 @@ * This file is part of the Fun programming language. * https://fun-lang.xyz/ * - * Copyright 2025 Johannes Findeisen + * Copyright 2026 Johannes Findeisen * Licensed under the terms of the Apache-2.0 license. * https://opensource.org/license/apache-2-0 * diff --git a/examples/rust_hello_args.fun b/examples/rust_hello_args.fun index 9fd2e70..652ae37 100755 --- a/examples/rust_hello_args.fun +++ b/examples/rust_hello_args.fun @@ -4,7 +4,7 @@ * This file is part of the Fun programming language. * https://fun-lang.xyz/ * - * Copyright 2025 Johannes Findeisen + * Copyright 2026 Johannes Findeisen * Licensed under the terms of the Apache-2.0 license. * https://opensource.org/license/apache-2-0 * diff --git a/examples/rust_vm_access.fun b/examples/rust_vm_access.fun new file mode 100644 index 0000000..b4e2474 --- /dev/null +++ b/examples/rust_vm_access.fun @@ -0,0 +1,39 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-01-29 + */ + +/* + * Rust-backed VM access demo: + * - rust_get_sp() -> reads vm.sp (stack pointer) using raw pointer + offset from Rust + * - rust_set_exit(N) -> writes vm.exit_code = N from Rust + */ + +print("[Rust VM access demo]") + +/* Read vm.sp via Rust and print it */ +print("vm.sp (from Rust) = " + to_string(rust_get_sp())) + +/* Write vm.exit_code via Rust (not directly observable without VM inspection) */ +print("Setting vm.exit_code to 5 via Rust...") +rust_set_exit(42) + +print("Now exiting...") + +/* Expected output: +[Rust VM access demo] +vm.sp (from Rust) = 0 +Setting vm.exit_code to 42 via Rust... +Now exiting... +*/ + +// "echo $?" will show the exit code: +// 42 diff --git a/src/bytecode.c b/src/bytecode.c index 82d8ca1..ed55ff8 100644 --- a/src/bytecode.c +++ b/src/bytecode.c @@ -208,6 +208,8 @@ static const char *opcode_name(OpCode op) { case OP_FMAX: return "FMAX"; case OP_RUST_HELLO: return "RUST_HELLO"; case OP_RUST_HELLO_ARGS: return "RUST_HELLO_ARGS"; + case OP_RUST_GET_SP: return "RUST_GET_SP"; + case OP_RUST_SET_EXIT: return "RUST_SET_EXIT"; default: return "???"; } } diff --git a/src/bytecode.h b/src/bytecode.h index 81c12c1..4fbf9ef 100644 --- a/src/bytecode.h +++ b/src/bytecode.h @@ -266,6 +266,8 @@ typedef enum { // Rust FFI demo opcode(s) OP_RUST_HELLO, // pushes string returned from Rust (hello world) OP_RUST_HELLO_ARGS, // pops message string; prints it via Rust; pushes Nil + OP_RUST_GET_SP, // pushes current VM stack pointer (via Rust reading VM memory) + OP_RUST_SET_EXIT, // pops int and sets VM exit_code (via Rust writing VM memory) /* Notcurses TUI (optional) */ OP_NC_INIT, // initializes Notcurses; returns 1 on success, 0 on failure diff --git a/src/parser.c b/src/parser.c index bef13c9..78697a7 100644 --- a/src/parser.c +++ b/src/parser.c @@ -801,6 +801,21 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos) free(name); return 1; } + if (strcmp(name, "rust_get_sp") == 0) { + (*pos)++; /* '(' */ + if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "rust_get_sp expects ()"); free(name); return 0; } + bytecode_add_instruction(bc, OP_RUST_GET_SP, 0); + free(name); + return 1; + } + if (strcmp(name, "rust_set_exit") == 0) { + (*pos)++; /* '(' */ + if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "rust_set_exit expects (code:int)"); free(name); return 0; } + if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "Expected ')' after rust_set_exit arg"); free(name); return 0; } + bytecode_add_instruction(bc, OP_RUST_SET_EXIT, 0); + free(name); + return 1; + } if (strcmp(name, "os_list_dir") == 0) { (*pos)++; /* '(' */ if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "os_list_dir expects (path)"); free(name); return 0; } diff --git a/src/rust/src/lib.rs b/src/rust/src/lib.rs index 115785b..fbd9be7 100644 --- a/src/rust/src/lib.rs +++ b/src/rust/src/lib.rs @@ -2,15 +2,13 @@ * This file is part of the Fun programming language. * https://fun-lang.xyz/ * - * Copyright 2025 Johannes Findeisen + * Copyright 2026 Johannes Findeisen * Licensed under the terms of the Apache-2.0 license. * https://opensource.org/license/apache-2-0 * * Added: 2026-01-27 */ -#![no_std] - // Use an FFI-safe opaque handle for the VM pointer pub type Vm = core::ffi::c_void; @@ -37,7 +35,7 @@ pub extern "C" fn fun_rust_get_string() -> *const core::ffi::c_char { b"Hello from Rust ops!\0".as_ptr() as *const _ } -// Print a C string via libc printf to stdout (acceptable under no_std via extern) +// Print a C string via libc printf to stdout #[no_mangle] pub extern "C" fn fun_rust_print_string(msg: *const core::ffi::c_char) -> i32 { unsafe { @@ -50,12 +48,4 @@ pub extern "C" fn fun_rust_print_string(msg: *const core::ffi::c_char) -> i32 { 0 } -// Provide personality symbol to satisfy some linkers in no_std builds -#[no_mangle] -pub extern "C" fn rust_eh_personality() {} - -// Minimal panic handler for no_std; abort behavior requested via Cargo profile -#[panic_handler] -fn panic(_info: &core::panic::PanicInfo) -> ! { - loop {} -} +// No custom panic handler; use std default diff --git a/src/rust/src/vm/mod.rs b/src/rust/src/vm/mod.rs index aec43a4..2816307 100644 --- a/src/rust/src/vm/mod.rs +++ b/src/rust/src/vm/mod.rs @@ -2,7 +2,7 @@ * This file is part of the Fun programming language. * https://fun-lang.xyz/ * - * Copyright 2025 Johannes Findeisen + * Copyright 2026 Johannes Findeisen * Licensed under the terms of the Apache-2.0 license. * https://opensource.org/license/apache-2-0 * @@ -16,10 +16,18 @@ //! ABI helpers declared on the C side (`vm_pop_i64`, `vm_push_i64`). use super::Vm; +//use core::mem::size_of; +use core::ptr; extern "C" { fn vm_pop_i64(vm: *mut Vm) -> i64; fn vm_push_i64(vm: *mut Vm, v: i64); + fn vm_as_mut_ptr(vm: *mut Vm) -> *mut core::ffi::c_void; + fn vm_sizeof() -> usize; + fn vm_value_sizeof() -> usize; + fn vm_offset_of_exit_code() -> usize; + fn vm_offset_of_sp() -> usize; + fn vm_offset_of_stack() -> usize; } /// Multiply the top two integers on the VM stack. @@ -68,3 +76,29 @@ pub extern "C" fn fun_op_rdiv(vm: *mut Vm) -> i32 { } 0 } + +/// Demo: push current stack pointer (vm.sp) using raw offset access. +#[no_mangle] +pub extern "C" fn fun_op_rget_sp(vm: *mut Vm) -> i32 { + unsafe { + let base = vm_as_mut_ptr(vm) as *mut u8; + let off_sp = vm_offset_of_sp(); + let sp_ptr = base.add(off_sp) as *const i32; + let sp = ptr::read(sp_ptr); + vm_push_i64(vm, sp as i64); + } + 0 +} + +/// Demo: set vm.exit_code to a value popped from the stack (i64 -> i32 cast). +#[no_mangle] +pub extern "C" fn fun_op_rset_exit(vm: *mut Vm) -> i32 { + unsafe { + let code = vm_pop_i64(vm) as i32; + let base = vm_as_mut_ptr(vm) as *mut u8; + let off_ec = vm_offset_of_exit_code(); + let ec_ptr = base.add(off_ec) as *mut i32; + ptr::write(ec_ptr, code); + } + 0 +} diff --git a/src/vm.c b/src/vm.c index 4c78db9..46c451e 100644 --- a/src/vm.c +++ b/src/vm.c @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -488,6 +489,35 @@ void vm_push_i64(VM *vm, int64_t v) { push_value(vm, make_int(v)); } +/* --- Extended C ABI for Rust to access VM internals (unsafe) --- */ +size_t vm_sizeof(void) { + return sizeof(VM); +} + +size_t vm_value_sizeof(void) { + return sizeof(Value); +} + +void *vm_as_mut_ptr(VM *vm) { + return (void*)vm; +} + +size_t vm_offset_of_exit_code(void) { + return offsetof(VM, exit_code); +} + +size_t vm_offset_of_sp(void) { + return offsetof(VM, sp); +} + +size_t vm_offset_of_stack(void) { + return offsetof(VM, stack); +} + +size_t vm_offset_of_globals(void) { + return offsetof(VM, globals); +} + static void frame_init(Frame *f) { f->fn = NULL; f->ip = 0; @@ -758,6 +788,9 @@ void vm_run(VM *vm, Bytecode *entry) { /* Rust FFI demo opcode(s) */ #include "vm/rust/hello.c" + #include "vm/rust/hello_args.c" + #include "vm/rust/get_sp.c" + #include "vm/rust/set_exit.c" #include "vm/os/env.c" #include "vm/os/env_all.c" diff --git a/src/vm.h b/src/vm.h index e746a96..1503b0d 100644 --- a/src/vm.h +++ b/src/vm.h @@ -11,6 +11,7 @@ #define FUN_VM_H #include "bytecode.h" +#include #define MAX_FRAMES 128 #define MAX_FRAME_LOCALS 64 @@ -56,7 +57,7 @@ static const char *opcode_names[] = { "TRY_PUSH","TRY_POP","THROW", "FMIN","FMAX", /* Rust FFI demo */ - "RUST_HELLO","RUST_HELLO_ARGS", + "RUST_HELLO","RUST_HELLO_ARGS","RUST_GET_SP","RUST_SET_EXIT", /* Notcurses TUI (optional) */ "NC_INIT","NC_SHUTDOWN","NC_CLEAR","NC_DRAW_TEXT","NC_GETCH" }; @@ -160,4 +161,23 @@ const char *fun_rust_get_string(void); /* Rust function that prints a passed C string, returns 0 on success. */ int fun_rust_print_string(const char *msg); +/* --- Extended C ABI for Rust to access VM internals (unsafe) --- */ +/* Size helpers for Rust side to compute offsets and do pointer math */ +size_t vm_sizeof(void); +size_t vm_value_sizeof(void); + +/* Get a mutable byte pointer to the VM object. Extremely unsafe; intended for + * low-level FFI where Rust wants parity access with C code. */ +void *vm_as_mut_ptr(VM *vm); + +/* Offsets of commonly accessed VM fields to avoid re-declaring the struct layout in Rust */ +size_t vm_offset_of_exit_code(void); +size_t vm_offset_of_sp(void); +size_t vm_offset_of_stack(void); +size_t vm_offset_of_globals(void); + +/* Demo Rust ops using the extended ABI */ +int fun_op_rget_sp(VM *vm); +int fun_op_rset_exit(VM *vm); + #endif diff --git a/src/vm/rust/get_sp.c b/src/vm/rust/get_sp.c new file mode 100644 index 0000000..1a08b30 --- /dev/null +++ b/src/vm/rust/get_sp.c @@ -0,0 +1,26 @@ +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-01-29 + */ + +/* + * Rust FFI demo opcode: OP_RUST_GET_SP + * Calls into Rust to read vm.sp via raw pointer math and pushes it (int). + */ +case OP_RUST_GET_SP: { +#ifdef FUN_WITH_RUST + extern int fun_op_rget_sp(VM *vm); + int rc = fun_op_rget_sp(vm); + (void)rc; /* rc currently unused; 0 means OK */ +#else + vm_raise_error(vm, "RUST_GET_SP requires FUN_WITH_RUST=ON at build time"); + push_value(vm, make_int(-1)); +#endif + break; +} diff --git a/src/vm/rust/hello.c b/src/vm/rust/hello.c index 6878c46..32772ca 100644 --- a/src/vm/rust/hello.c +++ b/src/vm/rust/hello.c @@ -2,7 +2,7 @@ * This file is part of the Fun programming language. * https://fun-lang.xyz/ * - * Copyright 2025 Johannes Findeisen + * Copyright 2026 Johannes Findeisen * Licensed under the terms of the Apache-2.0 license. * https://opensource.org/license/apache-2-0 * @@ -25,29 +25,3 @@ case OP_RUST_HELLO: { #endif break; } - -/* - * Rust FFI demo opcode with argument: OP_RUST_HELLO_ARGS - * Pops a string from the stack and asks Rust to print it. Pushes Nil. - */ -case OP_RUST_HELLO_ARGS: { -#ifdef FUN_WITH_RUST - Value vmsg = pop_value(vm); - char *msg = value_to_string_alloc(&vmsg); - free_value(vmsg); - if (msg) { - fun_rust_print_string(msg); - free(msg); - } else { - fun_rust_print_string(""); - } - push_value(vm, make_nil()); -#else - /* Still pop and free the arg to keep stack sane */ - Value vmsg = pop_value(vm); - free_value(vmsg); - vm_raise_error(vm, "RUST_HELLO_ARGS requires FUN_WITH_RUST=ON at build time"); - push_value(vm, make_nil()); -#endif - break; -} diff --git a/src/vm/rust/hello_args.c b/src/vm/rust/hello_args.c new file mode 100644 index 0000000..d361907 --- /dev/null +++ b/src/vm/rust/hello_args.c @@ -0,0 +1,36 @@ +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-01-29 + */ + +/* + * Rust FFI demo opcode with argument: OP_RUST_HELLO_ARGS + * Pops a string from the stack and asks Rust to print it. Pushes Nil. + */ +case OP_RUST_HELLO_ARGS: { +#ifdef FUN_WITH_RUST + Value vmsg = pop_value(vm); + char *msg = value_to_string_alloc(&vmsg); + free_value(vmsg); + if (msg) { + fun_rust_print_string(msg); + free(msg); + } else { + fun_rust_print_string(""); + } + push_value(vm, make_nil()); +#else + /* Still pop and free the arg to keep stack sane */ + Value vmsg = pop_value(vm); + free_value(vmsg); + vm_raise_error(vm, "RUST_HELLO_ARGS requires FUN_WITH_RUST=ON at build time"); + push_value(vm, make_nil()); +#endif + break; +} diff --git a/src/vm/rust/set_exit.c b/src/vm/rust/set_exit.c new file mode 100644 index 0000000..70f4314 --- /dev/null +++ b/src/vm/rust/set_exit.c @@ -0,0 +1,33 @@ +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-01-29 + */ + +/* + * Rust FFI demo opcode: OP_RUST_SET_EXIT + * Pops an int code and asks Rust to write it into vm.exit_code. + */ +case OP_RUST_SET_EXIT: { +#ifdef FUN_WITH_RUST + extern int fun_op_rset_exit(VM *vm); + /* Expect an integer on the stack already (produced by prior ops) */ + /* fun_op_rset_exit will pop it and store into vm.exit_code */ + int rc = fun_op_rset_exit(vm); + (void)rc; + /* push Nil as a conventional result */ + push_value(vm, make_nil()); +#else + /* pop and ignore to keep stack sane */ + Value v = pop_value(vm); + free_value(v); + vm_raise_error(vm, "RUST_SET_EXIT requires FUN_WITH_RUST=ON at build time"); + push_value(vm, make_nil()); +#endif + break; +} From d39ef1a58ebad8076b5a5f69692157c770695edb Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 29 Jan 2026 03:29:14 +0100 Subject: [PATCH 06/39] Some more Rusty Fun... :) (0.38.3) --- CMakeLists.txt | 2 +- docs/rust.md | 127 ++++------------------------ examples/rust_hello_args_return.fun | 34 ++++++++ src/bytecode.c | 1 + src/bytecode.h | 1 + src/parser.c | 8 ++ src/rust/src/lib.rs | 42 +++++++++ src/vm.c | 1 + src/vm.h | 6 +- src/vm/rust/hello_args_return.c | 48 +++++++++++ 10 files changed, 157 insertions(+), 113 deletions(-) create mode 100644 examples/rust_hello_args_return.fun create mode 100644 src/vm/rust/hello_args_return.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 1e619dc..25f330e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.2 LANGUAGES C) +project(fun VERSION 0.38.3 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) diff --git a/docs/rust.md b/docs/rust.md index 9657c1f..faf6ead 100644 --- a/docs/rust.md +++ b/docs/rust.md @@ -1,114 +1,3 @@ -# Writing Rust-backed opcodes for Fun VM - -!!! CAUTION !!! I am not very experienced in using Rust. This should show that it is possible to implement opcodes in Rust and integrate them with the Fun VM. - -This guide explains how to implement VM opcodes in Rust, wire them into the C VM, and use them from Fun scripts. - -It assumes you are comfortable with basic Rust and C and have a working Fun checkout. - -## Overview - -Fun’s VM is written in C, but you can implement opcode handlers in Rust and call them via FFI. The typical flow is: - -1) Write a Rust function with a stable C ABI (extern "C", #[no_mangle]) that takes a pointer to the VM and returns an int status code. -2) Use VM stack helpers (exposed to Rust via FFI) to pop arguments and push results. -3) Expose that Rust function to the C VM by calling it from the opcode dispatch (a case in the VM’s opcode switch or a small shim under src/vm/rust/). -4) Add or reuse a Fun builtin that maps to your opcode, then call it from Fun code. - -## Project layout (relevant parts) - -- src/rust/src/lib.rs — Rust library with exported opcode functions and FFI helpers. -- src/vm/rust/ — C-side wiring examples and small opcode cases calling into Rust. -- examples/rust_hello.fun — Example Fun script using a Rust-backed opcode. -- docs/opcodes.md — General overview of many built-in opcodes (mostly C-based). - -## Enabling Rust in the build - -Rust integration is optional and gated by a CMake flag. Default builds usually have it OFF. - -Enable it for a configured profile (Debug or Release): - -- Debug example: - cmake -S . -B build_debug -DFUN_WITH_RUST=ON - cmake --build build_debug --target fun - -- Release example: - cmake -S . -B build_release -DFUN_WITH_RUST=ON - cmake --build build_release --target fun - -Useful targets in this repository include: -- fun — the main executable -- rust_ops_build — helps build/link Rust ops when enabled -- test_opcodes — test executable (if you want to extend tests) - -Note: In CLion, prefer building with one of the provided CMake profiles (Debug/Release) and avoid creating custom build directories. - -## Writing an opcode in Rust - -The Rust side is a no_std static library exposing C ABI functions that the VM can call. See src/rust/src/lib.rs for examples already in the tree. - -Key points: -- Use extern "C" and #[no_mangle] to fix the symbol name. -- Take a raw pointer to the VM as *mut Vm; return i32 status (0 for success). -- Interact with the VM stack via helper FFI functions declared as externs. -- Provide a minimal panic handler (no_std) as shown in lib.rs. - -Example: integer addition opcode implemented in Rust. - -In src/rust/src/lib.rs: - - #![no_std] - - #[repr(C)] - pub struct Vm; - - extern "C" { - fn vm_pop_i64(vm: *mut Vm) -> i64; - fn vm_push_i64(vm: *mut Vm, v: i64); - } - - #[no_mangle] - pub extern "C" fn fun_op_radd(vm: *mut Vm) -> i32 { - unsafe { - let b = vm_pop_i64(vm); - let a = vm_pop_i64(vm); - vm_push_i64(vm, a + b); - } - 0 - } - - #[panic_handler] - fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} } - -What this does: -- Pops two 64-bit integers from the VM stack. -- Pushes back their sum. -- Returns 0 to indicate success to the VM. - -You can add more extern helpers (e.g., for strings, arrays, maps) once they are exposed by the C VM. The repository already includes a simple string example returning a const char* from Rust, see fun_rust_get_string() usage below. - -## Wiring the opcode in C - -To make the VM call your Rust opcode, add a small C-side case that invokes the exported Rust symbol. A minimal pattern lives under src/vm/rust/. - -String demo wiring (already present): src/vm/rust/hello.c - - case OP_RUST_HELLO: { - #ifdef FUN_WITH_RUST - const char *s = fun_rust_get_string(); - if (!s) s = ""; - push_value(vm, make_string(s)); - #else - vm_raise_error(vm, "RUST_HELLO requires FUN_WITH_RUST=ON at build time"); - push_value(vm, make_nil()); - #endif - break; - } - -For a stack-based math opcode (like fun_op_radd), you would declare and call the Rust function similarly: - - #ifdef FUN_WITH_RUST - extern int fun_op_radd(void* vm); // or use the proper VM type if available #endif case OP_RADD: { @@ -197,3 +86,19 @@ Authoritative and practical resources on exposing Rust to C (FFI) and maintainin https://cbindgen.github.io/cbindgen/ - bindgen (generate Rust bindings to existing C headers; useful when mixing C and Rust) https://github.com/rust-lang/rust-bindgen + +## Return-only Rust string helper + +Two variants are available for passing a string to Rust and getting output: + +- rust_hello_args(msg) + - Rust side prints the message to stdout; Fun receives Nil. Use when you only want side-effect printing. +- rust_hello_args_return(msg) + - Rust side does not print; it returns the provided string to Fun (useful for assignment or chaining). + +Example: + + msg = rust_hello_args_return("Hello back from Rust (no print)!") + print(msg) + +See examples/rust_hello_args_return.fun for a complete script. diff --git a/examples/rust_hello_args_return.fun b/examples/rust_hello_args_return.fun new file mode 100644 index 0000000..2fd6c6c --- /dev/null +++ b/examples/rust_hello_args_return.fun @@ -0,0 +1,34 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-01-29 + */ + +/* + * Rust-backed opcode demo with argument: rust_hello_args_return(STRING) + * This variant does NOT print from Rust; it only returns the provided string + * back to Fun for assignment or further processing. + * + * Build instructions: + * - Enable Rust integration: + * cmake -S . -B build_debug -DFUN_WITH_RUST=ON + * - Then build: + * cmake --build build_debug --target fun + * + * Run: + * build_debug/fun examples/rust_hello_args_return.fun + */ + +msg = rust_hello_args_return("Hello back from Rust (no print)!") +print(msg) + +/* Expected output: +Hello back from Rust (no print)! +*/ diff --git a/src/bytecode.c b/src/bytecode.c index ed55ff8..793ef79 100644 --- a/src/bytecode.c +++ b/src/bytecode.c @@ -208,6 +208,7 @@ static const char *opcode_name(OpCode op) { case OP_FMAX: return "FMAX"; case OP_RUST_HELLO: return "RUST_HELLO"; case OP_RUST_HELLO_ARGS: return "RUST_HELLO_ARGS"; + case OP_RUST_HELLO_ARGS_RETURN: return "RUST_HELLO_ARGS_RETURN"; case OP_RUST_GET_SP: return "RUST_GET_SP"; case OP_RUST_SET_EXIT: return "RUST_SET_EXIT"; default: return "???"; diff --git a/src/bytecode.h b/src/bytecode.h index 4fbf9ef..9731664 100644 --- a/src/bytecode.h +++ b/src/bytecode.h @@ -266,6 +266,7 @@ typedef enum { // Rust FFI demo opcode(s) OP_RUST_HELLO, // pushes string returned from Rust (hello world) OP_RUST_HELLO_ARGS, // pops message string; prints it via Rust; pushes Nil + OP_RUST_HELLO_ARGS_RETURN, // pops message string; returns it from Rust without printing; pushes returned string OP_RUST_GET_SP, // pushes current VM stack pointer (via Rust reading VM memory) OP_RUST_SET_EXIT, // pops int and sets VM exit_code (via Rust writing VM memory) diff --git a/src/parser.c b/src/parser.c index 78697a7..14a44d5 100644 --- a/src/parser.c +++ b/src/parser.c @@ -801,6 +801,14 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos) free(name); return 1; } + if (strcmp(name, "rust_hello_args_return") == 0) { + (*pos)++; /* '(' */ + if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "rust_hello_args_return expects (message:string)"); free(name); return 0; } + if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "Expected ')' after rust_hello_args_return arg"); free(name); return 0; } + bytecode_add_instruction(bc, OP_RUST_HELLO_ARGS_RETURN, 0); + free(name); + return 1; + } if (strcmp(name, "rust_get_sp") == 0) { (*pos)++; /* '(' */ if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "rust_get_sp expects ()"); free(name); return 0; } diff --git a/src/rust/src/lib.rs b/src/rust/src/lib.rs index fbd9be7..b077762 100644 --- a/src/rust/src/lib.rs +++ b/src/rust/src/lib.rs @@ -48,4 +48,46 @@ pub extern "C" fn fun_rust_print_string(msg: *const core::ffi::c_char) -> i32 { 0 } +// Return a newly allocated duplicate of the given C string. +// Caller (C side) must free using fun_rust_string_free. +#[no_mangle] +pub extern "C" fn fun_rust_echo_string(input: *const core::ffi::c_char) -> *mut core::ffi::c_char { + use core::ffi::CStr; + unsafe { + if input.is_null() { + // allocate empty string + let v = Vec::::from([0u8]); + return v.leak().as_mut_ptr() as *mut core::ffi::c_char; + } + match CStr::from_ptr(input).to_str() { + Ok(s) => { + let mut v = s.as_bytes().to_vec(); + v.push(0); // NUL-terminate + v.leak().as_mut_ptr() as *mut core::ffi::c_char + } + Err(_) => { + // On invalid UTF-8, still duplicate bytes as-is + let c = CStr::from_ptr(input); + let mut v = c.to_bytes().to_vec(); + v.push(0); + v.leak().as_mut_ptr() as *mut core::ffi::c_char + } + } + } +} + +// Free a C string previously returned by fun_rust_echo_string +#[no_mangle] +pub extern "C" fn fun_rust_string_free(ptr: *mut core::ffi::c_char) { + if ptr.is_null() { return; } + unsafe { + // Reconstruct a Vec so Rust will free it when it drops + // Determine length by scanning for NUL + let mut len: usize = 0; + while *ptr.add(len) != 0 { len += 1; } + let slice = core::slice::from_raw_parts_mut(ptr as *mut u8, len + 1); + let _ = Vec::from_raw_parts(slice.as_mut_ptr(), len + 1, len + 1); + } +} + // No custom panic handler; use std default diff --git a/src/vm.c b/src/vm.c index 46c451e..3464f60 100644 --- a/src/vm.c +++ b/src/vm.c @@ -789,6 +789,7 @@ void vm_run(VM *vm, Bytecode *entry) { /* Rust FFI demo opcode(s) */ #include "vm/rust/hello.c" #include "vm/rust/hello_args.c" + #include "vm/rust/hello_args_return.c" #include "vm/rust/get_sp.c" #include "vm/rust/set_exit.c" diff --git a/src/vm.h b/src/vm.h index 1503b0d..05a94f2 100644 --- a/src/vm.h +++ b/src/vm.h @@ -57,7 +57,7 @@ static const char *opcode_names[] = { "TRY_PUSH","TRY_POP","THROW", "FMIN","FMAX", /* Rust FFI demo */ - "RUST_HELLO","RUST_HELLO_ARGS","RUST_GET_SP","RUST_SET_EXIT", + "RUST_HELLO","RUST_HELLO_ARGS","RUST_HELLO_ARGS_RETURN","RUST_GET_SP","RUST_SET_EXIT", /* Notcurses TUI (optional) */ "NC_INIT","NC_SHUTDOWN","NC_CLEAR","NC_DRAW_TEXT","NC_GETCH" }; @@ -160,6 +160,10 @@ int fun_op_radd(VM *vm); const char *fun_rust_get_string(void); /* Rust function that prints a passed C string, returns 0 on success. */ int fun_rust_print_string(const char *msg); +/* Rust function that returns a newly allocated duplicate of the input C string. */ +char *fun_rust_echo_string(const char *input); +/* Free a C string previously returned by fun_rust_echo_string. */ +void fun_rust_string_free(char *ptr); /* --- Extended C ABI for Rust to access VM internals (unsafe) --- */ /* Size helpers for Rust side to compute offsets and do pointer math */ diff --git a/src/vm/rust/hello_args_return.c b/src/vm/rust/hello_args_return.c new file mode 100644 index 0000000..6adf44d --- /dev/null +++ b/src/vm/rust/hello_args_return.c @@ -0,0 +1,48 @@ +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-01-29 + */ + +/* + * Rust FFI demo opcode with argument: OP_RUST_HELLO_ARGS_RETURN + * Pops a string from the stack, asks Rust to return it back (no printing). + * Pushes the returned string, or Nil on error. + */ +case OP_RUST_HELLO_ARGS_RETURN: { +#ifdef FUN_WITH_RUST + Value vmsg = pop_value(vm); + char *msg = value_to_string_alloc(&vmsg); + free_value(vmsg); + if (msg) { + char *ret = fun_rust_echo_string(msg); + free(msg); + if (ret) { + push_value(vm, make_string(ret)); + fun_rust_string_free(ret); + } else { + push_value(vm, make_nil()); + } + } else { + char *ret = fun_rust_echo_string(""); + if (ret) { + push_value(vm, make_string(ret)); + fun_rust_string_free(ret); + } else { + push_value(vm, make_nil()); + } + } +#else + /* Still pop and free the arg to keep stack sane */ + Value vmsg = pop_value(vm); + free_value(vmsg); + vm_raise_error(vm, "RUST_HELLO_ARGS_RETURN requires FUN_WITH_RUST=ON at build time"); + push_value(vm, make_nil()); +#endif + break; +} From d79815e366bc318f8fe28599e86651f4bd6e6134 Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 29 Jan 2026 05:09:15 +0100 Subject: [PATCH 07/39] What is CPP? Holy shit... (0.38.4) --- CMakeLists.txt | 45 ++++++++++++++++++++++++++--- examples/cpp_add.fun | 28 ++++++++++++++++++ examples/rust_hello_args_return.fun | 0 examples/rust_vm_access.fun | 2 +- make | 27 +++++++++++++++++ src/bytecode.h | 3 ++ src/parser.c | 10 +++++++ src/vm.c | 16 ++++++++++ src/vm.h | 5 ++++ src/vm/cpp/add.cpp | 28 ++++++++++++++++++ 10 files changed, 159 insertions(+), 5 deletions(-) create mode 100755 examples/cpp_add.fun mode change 100644 => 100755 examples/rust_hello_args_return.fun mode change 100644 => 100755 examples/rust_vm_access.fun create mode 100644 src/vm/cpp/add.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 25f330e..dbf627a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.3 LANGUAGES C) +project(fun VERSION 0.38.4 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) @@ -19,14 +19,21 @@ else() set(_FUN_DEBUG_STATE "DISABLED") endif() -if(FUN_WITH_RUST) - set(_FUN_WITH_RUST_STATE "ENABLED") +if(FUN_WITH_CPP) + set(_FUN_WITH_CPP_STATE "ENABLED") else() - set(_FUN_WITH_RUST_STATE "DISABLED") + set(_FUN_WITH_CPP_STATE "DISABLED") +endif() + +if(FUN_WITH_RUST) + set(_FUN_WITH_RUST_STATE "ENABLED") +else() + set(_FUN_WITH_RUST_STATE "DISABLED") endif() message(STATUS "==== Fun build options ====") message(STATUS " FUN_DEBUG: ${_FUN_DEBUG_STATE}") +message(STATUS " FUN_WITH_CPP: ${_FUN_WITH_CPP_STATE}") message(STATUS " FUN_WITH_RUST: ${_FUN_WITH_RUST_STATE}") message(STATUS "===========================") @@ -98,6 +105,36 @@ if(FUN_WITH_RUST) endif() endif() +# --- Optional C++ opcode demo --- +option(FUN_WITH_CPP "Build and link C++ opcode demo" OFF) +if(FUN_WITH_CPP) + enable_language(CXX) + + add_library(fun_cpp_ops STATIC + src/vm/cpp/add.cpp + ) + + # Compile definitions propagate to C targets that dispatch the opcode + target_compile_definitions(fun_cpp_ops PUBLIC FUN_WITH_CPP) + target_include_directories(fun_cpp_ops PUBLIC ${CMAKE_SOURCE_DIR}/src) + + # Link the C++ ops into the core so executables can call them + if(TARGET fun_core) + target_link_libraries(fun_core PRIVATE fun_cpp_ops) + target_compile_definitions(fun_core PRIVATE FUN_WITH_CPP) + endif() + + # Also propagate to test targets (if they might use it) + if(TARGET test_opcodes) + target_link_libraries(test_opcodes PRIVATE fun_cpp_ops) + target_compile_definitions(test_opcodes PRIVATE FUN_WITH_CPP) + endif() + + if(TARGET fun) + target_compile_definitions(fun PRIVATE FUN_WITH_CPP) + endif() +endif() + # --- Size optimization for final binaries (Release) --- # Enable function/data sectioning for better GC; safe for all configs. add_compile_options(-ffunction-sections -fdata-sections) diff --git a/examples/cpp_add.fun b/examples/cpp_add.fun new file mode 100755 index 0000000..52a5dfa --- /dev/null +++ b/examples/cpp_add.fun @@ -0,0 +1,28 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-01-29 + */ + +/* +Build: + cmake -S . -B build_debug -DFUN_WITH_CPP=ON + cmake --build build_debug --target fun +Run: + build_debug/fun examples/cpp_add.fun +*/ + +number x = cpp_add(2, 40) +//print("typeof(x): " + typeof(x)) +print(x) + +/* Expected output: +42 +*/ diff --git a/examples/rust_hello_args_return.fun b/examples/rust_hello_args_return.fun old mode 100644 new mode 100755 diff --git a/examples/rust_vm_access.fun b/examples/rust_vm_access.fun old mode 100644 new mode 100755 index b4e2474..99da016 --- a/examples/rust_vm_access.fun +++ b/examples/rust_vm_access.fun @@ -23,7 +23,7 @@ print("[Rust VM access demo]") print("vm.sp (from Rust) = " + to_string(rust_get_sp())) /* Write vm.exit_code via Rust (not directly observable without VM inspection) */ -print("Setting vm.exit_code to 5 via Rust...") +print("Setting vm.exit_code to 42 via Rust...") rust_set_exit(42) print("Now exiting...") diff --git a/make b/make index 18c5969..573ba26 100755 --- a/make +++ b/make @@ -31,6 +31,7 @@ if [ "$target" = "all" ]; then -DFUN_WITH_TCLTK=ON \ -DFUN_WITH_INI=ON \ -DFUN_WITH_NOTCURSES=ON \ + -DFUN_WITH_CPP=ON \ && cmake --build build --target fun elif [ "$target" = "all_debug" ]; then rm -rf build \ @@ -46,6 +47,7 @@ elif [ "$target" = "all_debug" ]; then -DFUN_WITH_TCLTK=ON \ -DFUN_WITH_INI=ON \ -DFUN_WITH_NOTCURSES=ON \ + -DFUN_WITH_CPP=ON \ -DFUN_DEBUG=ON \ && cmake --build build --target fun elif [ "$target" = "alpine" ]; then @@ -59,7 +61,29 @@ elif [ "$target" = "alpine" ]; then -DFUN_WITH_XML2=ON \ -DFUN_WITH_JSON=ON \ -DFUN_WITH_INI=ON \ + -DFUN_WITH_CPP=ON \ && cmake --build build --target fun +elif [ "$target" = "cpp_all" ]; then + rm -rf build \ + && cmake -S . -B build \ + -DFUN_WITH_PCSC=ON \ + -DFUN_WITH_REPL=ON \ + -DFUN_WITH_LIBSQL=ON \ + -DFUN_WITH_SQLITE=ON \ + -DFUN_WITH_CURL=ON \ + -DFUN_WITH_PCRE2=ON \ + -DFUN_WITH_XML2=ON \ + -DFUN_WITH_JSON=ON \ + -DFUN_WITH_TCLTK=ON \ + -DFUN_WITH_INI=ON \ + -DFUN_WITH_NOTCURSES=ON \ + -DFUN_WITH_CPP=ON \ + && cmake --build build --target fun + elif [ "$target" = "cpp_minimal" ]; then + rm -rf build \ + && cmake -S . -B build \ + -DFUN_WITH_CPP=ON \ + && cmake --build build --target fun elif [ "$target" = "debug" ]; then rm -rf build \ && cmake -S . -B build \ @@ -102,6 +126,7 @@ elif [ "$target" = "rust_all" ]; then -DFUN_WITH_TCLTK=ON \ -DFUN_WITH_INI=ON \ -DFUN_WITH_RUST=ON \ + -DFUN_WITH_CPP=ON \ -DFUN_DEBUG=OFF \ && cmake --build build --target fun elif [ "$target" = "rust_minimal" ]; then @@ -115,6 +140,8 @@ else echo " - all"; echo " - all_debug"; echo " - alpine"; + echo " - cpp_all"; + echo " - cpp_minimal"; echo " - debug"; echo " - freebsd"; echo " - install"; diff --git a/src/bytecode.h b/src/bytecode.h index 9731664..5eb3de4 100644 --- a/src/bytecode.h +++ b/src/bytecode.h @@ -270,6 +270,9 @@ typedef enum { OP_RUST_GET_SP, // pushes current VM stack pointer (via Rust reading VM memory) OP_RUST_SET_EXIT, // pops int and sets VM exit_code (via Rust writing VM memory) + // C++ demo opcode(s) + OP_CPP_ADD, // pops b, a; pushes (a + b) + /* Notcurses TUI (optional) */ OP_NC_INIT, // initializes Notcurses; returns 1 on success, 0 on failure OP_NC_SHUTDOWN, // shuts down Notcurses; returns 0 diff --git a/src/parser.c b/src/parser.c index 14a44d5..ad8dd1b 100644 --- a/src/parser.c +++ b/src/parser.c @@ -824,6 +824,16 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos) free(name); return 1; } + if (strcmp(name, "cpp_add") == 0) { + (*pos)++; /* '(' */ + if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "cpp_add expects (a:int, b:int)"); free(name); return 0; } + if (!consume_char(src, len, pos, ',')) { parser_fail(*pos, "cpp_add expects two arguments"); free(name); return 0; } + if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "cpp_add expects (a:int, b:int)"); free(name); return 0; } + if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "Expected ')' after cpp_add args"); free(name); return 0; } + bytecode_add_instruction(bc, OP_CPP_ADD, 0); + free(name); + return 1; + } if (strcmp(name, "os_list_dir") == 0) { (*pos)++; /* '(' */ if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "os_list_dir expects (path)"); free(name); return 0; } diff --git a/src/vm.c b/src/vm.c index 3464f60..c8f42e4 100644 --- a/src/vm.c +++ b/src/vm.c @@ -897,6 +897,22 @@ void vm_run(VM *vm, Bytecode *entry) { #include "vm/sqlite/query.c" #endif + /* C++ demo opcodes (guarded) */ + #if defined(FUN_WITH_CPP) + case OP_CPP_ADD: { + int rc = fun_op_cpp_add(vm); + if (rc != 0) { + vm_raise_error(vm, "cpp_add failed"); + } + break; + } + #else + case OP_CPP_ADD: { + vm_raise_error(vm, "CPP support is not enabled (build with -DFUN_WITH_CPP=ON)"); + break; + } + #endif + /* libsql ops (independent) */ #ifdef FUN_WITH_LIBSQL #include "vm/libsql/open.c" diff --git a/src/vm.h b/src/vm.h index 05a94f2..fdca9b6 100644 --- a/src/vm.h +++ b/src/vm.h @@ -58,6 +58,8 @@ static const char *opcode_names[] = { "FMIN","FMAX", /* Rust FFI demo */ "RUST_HELLO","RUST_HELLO_ARGS","RUST_HELLO_ARGS_RETURN","RUST_GET_SP","RUST_SET_EXIT", + /* C++ demo */ + "CPP_ADD", /* Notcurses TUI (optional) */ "NC_INIT","NC_SHUTDOWN","NC_CLEAR","NC_DRAW_TEXT","NC_GETCH" }; @@ -165,6 +167,9 @@ char *fun_rust_echo_string(const char *input); /* Free a C string previously returned by fun_rust_echo_string. */ void fun_rust_string_free(char *ptr); +/* C++ demo opcode entry point (C ABI) */ +int fun_op_cpp_add(struct VM *vm); + /* --- Extended C ABI for Rust to access VM internals (unsafe) --- */ /* Size helpers for Rust side to compute offsets and do pointer math */ size_t vm_sizeof(void); diff --git a/src/vm/cpp/add.cpp b/src/vm/cpp/add.cpp new file mode 100644 index 0000000..9f9f493 --- /dev/null +++ b/src/vm/cpp/add.cpp @@ -0,0 +1,28 @@ +/* +* This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-01-29 + */ + +/* + * Minimal C++ opcode for Fun VM — cpp_add + * Build is gated by -DFUN_WITH_CPP=ON (see CMake). + */ + +#include + +extern "C" { +#include "vm.h" // C header; provides VM, vm_pop_i64, vm_push_i64 +} + +extern "C" int fun_op_cpp_add(VM *vm) { + int64_t b = vm_pop_i64(vm); + int64_t a = vm_pop_i64(vm); + vm_push_i64(vm, a + b); + return 0; // success +} From 4e155b55a529e44dda801385f9a3d5a4b3c32111 Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 29 Jan 2026 05:37:30 +0100 Subject: [PATCH 08/39] Small test script update. (0.38.5) --- CMakeLists.txt | 2 +- scripts/run_examples.sh | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index dbf627a..a4174dc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.4 LANGUAGES C) +project(fun VERSION 0.38.5 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) diff --git a/scripts/run_examples.sh b/scripts/run_examples.sh index 183fdba..f6fced6 100755 --- a/scripts/run_examples.sh +++ b/scripts/run_examples.sh @@ -86,6 +86,7 @@ if (( ${#files[@]} == 0 )); then fi rc=0 +fail_count=0 for f in "${files[@]}"; do base_name="$(basename "$f")" # If INI support is disabled, skip INI examples to avoid expected failures @@ -100,12 +101,13 @@ for f in "${files[@]}"; do echo "FAILED: ${f#$ROOT/}" # Intentionally do not move files on failure; leave control to the user rc=1 + ((fail_count++)) fi done if (( rc == 0 )); then - echo "All examples ran successfully." + echo "All examples ran successfully. Failed: ${fail_count}" else - echo "Some examples failed." + echo "Some examples failed. Failed: ${fail_count}" fi exit $rc From 5fdd02f3a6cf3b6c0b1b0de1e32731657e198cc8 Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 29 Jan 2026 15:13:01 +0100 Subject: [PATCH 09/39] Rust doc fixes. No code changes. (0.38.5) --- docs/rust.md | 299 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 196 insertions(+), 103 deletions(-) diff --git a/docs/rust.md b/docs/rust.md index faf6ead..cb255f0 100644 --- a/docs/rust.md +++ b/docs/rust.md @@ -1,104 +1,197 @@ - #endif +# Writing Rust-backed opcodes for Fun VM - case OP_RADD: { - #ifdef FUN_WITH_RUST - (void)fun_op_radd(vm); - #else - vm_raise_error(vm, "RADD requires FUN_WITH_RUST=ON at build time"); - push_value(vm, make_nil()); // or follow your opcode’s error convention - #endif - break; - } - -Notes: -- Follow the existing opcode conventions for your module (core, math, strings, etc.). -- If your build puts the Rust symbol into a static library, make sure the VM target links it when FUN_WITH_RUST is ON (the top-level CMake already does this for the examples provided). - -## Using Rust-backed opcodes from Fun - -Once wired, expose the opcode via a builtin function or directly in bytecode. The repository includes a demo builtin rust_hello() that returns a Rust-generated string. - -Run the example: - -1) Build with Rust enabled (Debug): - cmake -S . -B build_debug -DFUN_WITH_RUST=ON - cmake --build build_debug --target fun - -2) Execute the script: - build_debug/fun examples/rust_hello.fun - -Expected output: - Hello from Rust ops! - -If you build without Rust, calling rust_hello() raises a runtime error indicating that Rust integration is disabled. - -## Stack discipline and error handling - -- Always pop exactly the arguments you expect and push exactly the results your opcode promises. Mismatch leads to stack corruption and hard-to-debug failures. -- Return an int status to the VM (0 for success). If your project uses a different convention for some opcodes, match it consistently. -- Validate types where appropriate (e.g., ensure values are integers before arithmetic). If a check fails, use the VM’s error mechanism (e.g., vm_raise_error) and follow the module’s convention on what to push after errors. - -## Data types and FFI surface - -The minimal helpers shown cover 64-bit integers and simple strings. Extending the Rust<->C bridge usually involves: -- Declaring additional extern "C" functions in Rust that the C VM implements (to read/write values on the stack, construct arrays/maps/strings, etc.). -- Ensuring all pointers and lifetimes are well-defined: strings pushed to the VM should be copied or allocated using VM facilities so they remain valid after the call. -- Keeping Rust no_std unless you add an allocator and link setup to support std. - -## Troubleshooting - -- Link errors: Make sure FUN_WITH_RUST=ON for your build directory and that the Rust library is compiled before linking the VM. Use the rust_ops_build target if provided by your profile. -- Missing symbol at runtime: Confirm #[no_mangle] and extern "C" on the Rust function and that C sees the correct prototype. -- Wrong or garbled values: Double-check stack order (Fun uses a stack VM; many ops pop in reverse order: first b, then a). -- No output from rust_hello(): Ensure you run a binary built with FUN_WITH_RUST=ON; otherwise the VM deliberately raises an error and returns Nil for that call. - -## Small end-to-end checklist - -1) Write the Rust function in src/rust/src/lib.rs with extern "C", #[no_mangle]. -2) Use FFI helpers to pop arguments and push results. -3) Add a C-side case under src/vm/... (or src/vm/rust/...) that calls your Rust function when the opcode executes. -4) Ensure the build links Rust code when FUN_WITH_RUST=ON. -5) Add or reuse a builtin in the parser/runtime to surface your opcode to Fun code. -6) Build and run a small .fun example to validate behavior. - -## References in this repo - -- Rust lib with examples: src/rust/src/lib.rs -- C-side hello wiring: src/vm/rust/hello.c -- Demo script: examples/rust_hello.fun -- General opcode reference: docs/opcodes.md - -## Links - -Authoritative and practical resources on exposing Rust to C (FFI) and maintaining a C-compatible API: - -- Rustonomicon: FFI overview and best practices - https://doc.rust-lang.org/nomicon/ffi.html -- Rustonomicon: Calling Rust code from C - https://doc.rust-lang.org/nomicon/ffi.html#calling-rust-code-from-c -- The Rust Book: Unsafe and FFI (extern, #[no_mangle], calling Rust from other languages) - https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html#calling-rust-functions-from-other-languages -- Rust Reference: extern blocks, ABIs, and linkage - https://doc.rust-lang.org/reference/items/external-blocks.html -- Rust FFI Omnibus (examples for many patterns, including Rust ↔ C) - https://github.com/shepmaster/rust-ffi-omnibus -- cbindgen (generate C headers from Rust libraries) - https://cbindgen.github.io/cbindgen/ -- bindgen (generate Rust bindings to existing C headers; useful when mixing C and Rust) - https://github.com/rust-lang/rust-bindgen - -## Return-only Rust string helper - -Two variants are available for passing a string to Rust and getting output: - -- rust_hello_args(msg) - - Rust side prints the message to stdout; Fun receives Nil. Use when you only want side-effect printing. -- rust_hello_args_return(msg) - - Rust side does not print; it returns the provided string to Fun (useful for assignment or chaining). - -Example: - - msg = rust_hello_args_return("Hello back from Rust (no print)!") - print(msg) - -See examples/rust_hello_args_return.fun for a complete script. + This guide explains how to implement VM opcodes in Rust, wire them into the C VM, and use them from Fun scripts. + + It assumes you are comfortable with basic Rust and C and have a working Fun checkout. + + ## Overview + + Fun’s VM is written in C, but you can implement opcode handlers in Rust and call them via FFI. The typical flow is: + + 1) Write a Rust function with a stable C ABI (extern "C", #[no_mangle]) that takes a pointer to the VM and returns an int status code. + 2) Use VM stack helpers (exposed to Rust via FFI) to pop arguments and push results. + 3) Expose that Rust function to the C VM by calling it from the opcode dispatch (a case in the VM’s opcode switch or a small shim under src/vm/rust/). + 4) Add or reuse a Fun builtin that maps to your opcode, then call it from Fun code. + + ## Project layout (relevant parts) + + - src/rust/src/lib.rs — Rust library with exported opcode functions and FFI helpers. + - src/vm/rust/ — C-side wiring examples and small opcode cases calling into Rust. + - examples/rust_hello.fun — Example Fun script using a Rust-backed opcode. + - docs/opcodes.md — General overview of many built-in opcodes (mostly C-based). + + ## Enabling Rust in the build + + Rust integration is optional and gated by a CMake flag. Default builds usually have it OFF. + + Enable it for a configured profile (Debug or Release): + + - Debug example: + cmake -S . -B build_debug -DFUN_WITH_RUST=ON + cmake --build build_debug --target fun + + - Release example: + cmake -S . -B build_release -DFUN_WITH_RUST=ON + cmake --build build_release --target fun + + Useful targets in this repository include: + - fun — the main executable + - rust_ops_build — helps build/link Rust ops when enabled + - test_opcodes — test executable (if you want to extend tests) + + Note: In CLion, prefer building with one of the provided CMake profiles (Debug/Release) and avoid creating custom build directories. + + ## Writing an opcode in Rust + + The Rust side is a no_std static library exposing C ABI functions that the VM can call. See src/rust/src/lib.rs for examples already in the tree. + + Key points: + - Use extern "C" and #[no_mangle] to fix the symbol name. + - Take a raw pointer to the VM as *mut Vm; return i32 status (0 for success). + - Interact with the VM stack via helper FFI functions declared as externs. + - Provide a minimal panic handler (no_std) as shown in lib.rs. + + Example: integer addition opcode implemented in Rust. + + In src/rust/src/lib.rs: + + #![no_std] + + #[repr(C)] + pub struct Vm; + + extern "C" { + fn vm_pop_i64(vm: *mut Vm) -> i64; + fn vm_push_i64(vm: *mut Vm, v: i64); + } + + #[no_mangle] + pub extern "C" fn fun_op_radd(vm: *mut Vm) -> i32 { + unsafe { + let b = vm_pop_i64(vm); + let a = vm_pop_i64(vm); + vm_push_i64(vm, a + b); + } + 0 + } + + #[panic_handler] + fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} } + + What this does: + - Pops two 64-bit integers from the VM stack. + - Pushes back their sum. + - Returns 0 to indicate success to the VM. + + You can add more extern helpers (e.g., for strings, arrays, maps) once they are exposed by the C VM. The repository already includes a simple string example returning a const char* from Rust, see fun_rust_get_string() usage below. + + ## Wiring the opcode in C + + To make the VM call your Rust opcode, add a small C-side case that invokes the exported Rust symbol. A minimal pattern lives under src/vm/rust/. + + String demo wiring (already present): src/vm/rust/hello.c + + case OP_RUST_HELLO: { + #ifdef FUN_WITH_RUST + const char *s = fun_rust_get_string(); + if (!s) s = ""; + push_value(vm, make_string(s)); + #else + vm_raise_error(vm, "RUST_HELLO requires FUN_WITH_RUST=ON at build time"); + push_value(vm, make_nil()); + #endif + break; + } + + For a stack-based math opcode (like fun_op_radd), you would declare and call the Rust function similarly: + + #ifdef FUN_WITH_RUST + extern int fun_op_radd(void* vm); // or use the proper VM type if available + #endif + + case OP_RADD: { + #ifdef FUN_WITH_RUST + (void)fun_op_radd(vm); + #else + vm_raise_error(vm, "RADD requires FUN_WITH_RUST=ON at build time"); + push_value(vm, make_nil()); // or follow your opcode’s error convention + #endif + break; + } + + Notes: + - Follow the existing opcode conventions for your module (core, math, strings, etc.). + - If your build puts the Rust symbol into a static library, make sure the VM target links it when FUN_WITH_RUST is ON (the top-level CMake already does this for the examples provided). + + ## Using Rust-backed opcodes from Fun + + Once wired, expose the opcode via a builtin function or directly in bytecode. The repository includes a demo builtin rust_hello() that returns a Rust-generated string. + + Run the example: + + 1) Build with Rust enabled (Debug): + cmake -S . -B build_debug -DFUN_WITH_RUST=ON + cmake --build build_debug --target fun + + 2) Execute the script: + build_debug/fun examples/rust_hello.fun + + Expected output: + Hello from Rust ops! + + If you build without Rust, calling rust_hello() raises a runtime error indicating that Rust integration is disabled. + + ## Stack discipline and error handling + + - Always pop exactly the arguments you expect and push exactly the results your opcode promises. Mismatch leads to stack corruption and hard-to-debug failures. + - Return an int status to the VM (0 for success). If your project uses a different convention for some opcodes, match it consistently. + - Validate types where appropriate (e.g., ensure values are integers before arithmetic). If a check fails, use the VM’s error mechanism (e.g., vm_raise_error) and follow the module’s convention on what to push after errors. + + ## Data types and FFI surface + + The minimal helpers shown cover 64-bit integers and simple strings. Extending the Rust<->C bridge usually involves: + - Declaring additional extern "C" functions in Rust that the C VM implements (to read/write values on the stack, construct arrays/maps/strings, etc.). + - Ensuring all pointers and lifetimes are well-defined: strings pushed to the VM should be copied or allocated using VM facilities so they remain valid after the call. + - Keeping Rust no_std unless you add an allocator and link setup to support std. + + ## Troubleshooting + + - Link errors: Make sure FUN_WITH_RUST=ON for your build directory and that the Rust library is compiled before linking the VM. Use the rust_ops_build target if provided by your profile. + - Missing symbol at runtime: Confirm #[no_mangle] and extern "C" on the Rust function and that C sees the correct prototype. + - Wrong or garbled values: Double-check stack order (Fun uses a stack VM; many ops pop in reverse order: first b, then a). + - No output from rust_hello(): Ensure you run a binary built with FUN_WITH_RUST=ON; otherwise the VM deliberately raises an error and returns Nil for that call. + + ## Small end-to-end checklist + + 1) Write the Rust function in src/rust/src/lib.rs with extern "C", #[no_mangle]. + 2) Use FFI helpers to pop arguments and push results. + 3) Add a C-side case under src/vm/... (or src/vm/rust/...) that calls your Rust function when the opcode executes. + 4) Ensure the build links Rust code when FUN_WITH_RUST=ON. + 5) Add or reuse a builtin in the parser/runtime to surface your opcode to Fun code. + 6) Build and run a small .fun example to validate behavior. + + ## References in this repo + + - Rust lib with examples: src/rust/src/lib.rs + - C-side hello wiring: src/vm/rust/hello.c + - Demo script: examples/rust_hello.fun + - General opcode reference: docs/opcodes.md + + ## Links + + Authoritative and practical resources on exposing Rust to C (FFI) and maintaining a C-compatible API: + + - Rustonomicon: FFI overview and best practices + https://doc.rust-lang.org/nomicon/ffi.html + - Rustonomicon: Calling Rust code from C + https://doc.rust-lang.org/nomicon/ffi.html#calling-rust-code-from-c + - The Rust Book: Unsafe and FFI (extern, #[no_mangle], calling Rust from other languages) + https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html#calling-rust-functions-from-other-languages + - Rust Reference: extern blocks, ABIs, and linkage + https://doc.rust-lang.org/reference/items/external-blocks.html + - Rust FFI Omnibus (examples for many patterns, including Rust ↔ C) + https://github.com/shepmaster/rust-ffi-omnibus + - cbindgen (generate C headers from Rust libraries) + https://cbindgen.github.io/cbindgen/ + - bindgen (generate Rust bindings to existing C headers; useful when mixing C and Rust) + https://github.com/rust-lang/rust-bindgen From c03ac29e40a679a0dd5161d1fd0a0868e40bf676 Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 29 Jan 2026 15:17:46 +0100 Subject: [PATCH 10/39] Rust doc fixes. No code changes. (0.38.5) --- docs/rust.md | 396 ++++++++++++++++++++++++++------------------------- 1 file changed, 202 insertions(+), 194 deletions(-) diff --git a/docs/rust.md b/docs/rust.md index cb255f0..71ca53b 100644 --- a/docs/rust.md +++ b/docs/rust.md @@ -1,197 +1,205 @@ # Writing Rust-backed opcodes for Fun VM - This guide explains how to implement VM opcodes in Rust, wire them into the C VM, and use them from Fun scripts. - - It assumes you are comfortable with basic Rust and C and have a working Fun checkout. - - ## Overview - - Fun’s VM is written in C, but you can implement opcode handlers in Rust and call them via FFI. The typical flow is: - - 1) Write a Rust function with a stable C ABI (extern "C", #[no_mangle]) that takes a pointer to the VM and returns an int status code. - 2) Use VM stack helpers (exposed to Rust via FFI) to pop arguments and push results. - 3) Expose that Rust function to the C VM by calling it from the opcode dispatch (a case in the VM’s opcode switch or a small shim under src/vm/rust/). - 4) Add or reuse a Fun builtin that maps to your opcode, then call it from Fun code. - - ## Project layout (relevant parts) - - - src/rust/src/lib.rs — Rust library with exported opcode functions and FFI helpers. - - src/vm/rust/ — C-side wiring examples and small opcode cases calling into Rust. - - examples/rust_hello.fun — Example Fun script using a Rust-backed opcode. - - docs/opcodes.md — General overview of many built-in opcodes (mostly C-based). - - ## Enabling Rust in the build - - Rust integration is optional and gated by a CMake flag. Default builds usually have it OFF. - - Enable it for a configured profile (Debug or Release): - - - Debug example: - cmake -S . -B build_debug -DFUN_WITH_RUST=ON - cmake --build build_debug --target fun - - - Release example: - cmake -S . -B build_release -DFUN_WITH_RUST=ON - cmake --build build_release --target fun - - Useful targets in this repository include: - - fun — the main executable - - rust_ops_build — helps build/link Rust ops when enabled - - test_opcodes — test executable (if you want to extend tests) - - Note: In CLion, prefer building with one of the provided CMake profiles (Debug/Release) and avoid creating custom build directories. - - ## Writing an opcode in Rust - +This guide explains how to implement VM opcodes in Rust, wire them into the C VM, and use them from Fun scripts. + +It assumes you are comfortable with basic Rust and C and have a working Fun checkout. + +## Overview + +Fun’s VM is written in C, but you can implement opcode handlers in Rust and call them via FFI. The typical flow is: + +1) Write a Rust function with a stable C ABI (extern "C", #[no_mangle]) that takes a pointer to the VM and returns an int status code. +2) Use VM stack helpers (exposed to Rust via FFI) to pop arguments and push results. +3) Expose that Rust function to the C VM by calling it from the opcode dispatch (a case in the VM’s opcode switch or a small shim under src/vm/rust/). +4) Add or reuse a Fun builtin that maps to your opcode, then call it from Fun code. + +## Project layout (relevant parts) + +- src/rust/src/lib.rs — Rust library with exported opcode functions and FFI helpers. +- src/vm/rust/ — C-side wiring examples and small opcode cases calling into Rust. +- examples/rust_hello.fun — Example Fun script using a Rust-backed opcode. +- docs/opcodes.md — General overview of many built-in opcodes (mostly C-based). + +## Enabling Rust in the build + +Rust integration is optional and gated by a CMake flag. Default builds usually have it OFF. + +Enable it for a configured profile (Debug or Release): + +- Debug example: + cmake -S . -B build_debug -DFUN_WITH_RUST=ON + cmake --build build_debug --target fun + +- Release example: + cmake -S . -B build_release -DFUN_WITH_RUST=ON + cmake --build build_release --target fun + +Useful targets in this repository include: +- fun — the main executable +- rust_ops_build — helps build/link Rust ops when enabled +- test_opcodes — test executable (if you want to extend tests) + +Note: In CLion, prefer building with one of the provided CMake profiles (Debug/Release) and avoid creating custom build directories. + +## Writing an opcode in Rust + The Rust side is a no_std static library exposing C ABI functions that the VM can call. See src/rust/src/lib.rs for examples already in the tree. - - Key points: - - Use extern "C" and #[no_mangle] to fix the symbol name. - - Take a raw pointer to the VM as *mut Vm; return i32 status (0 for success). - - Interact with the VM stack via helper FFI functions declared as externs. - - Provide a minimal panic handler (no_std) as shown in lib.rs. - - Example: integer addition opcode implemented in Rust. - - In src/rust/src/lib.rs: - - #![no_std] - - #[repr(C)] - pub struct Vm; - - extern "C" { - fn vm_pop_i64(vm: *mut Vm) -> i64; - fn vm_push_i64(vm: *mut Vm, v: i64); - } - - #[no_mangle] - pub extern "C" fn fun_op_radd(vm: *mut Vm) -> i32 { - unsafe { - let b = vm_pop_i64(vm); - let a = vm_pop_i64(vm); - vm_push_i64(vm, a + b); - } - 0 - } - - #[panic_handler] - fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} } - - What this does: - - Pops two 64-bit integers from the VM stack. - - Pushes back their sum. - - Returns 0 to indicate success to the VM. - - You can add more extern helpers (e.g., for strings, arrays, maps) once they are exposed by the C VM. The repository already includes a simple string example returning a const char* from Rust, see fun_rust_get_string() usage below. - - ## Wiring the opcode in C - - To make the VM call your Rust opcode, add a small C-side case that invokes the exported Rust symbol. A minimal pattern lives under src/vm/rust/. - - String demo wiring (already present): src/vm/rust/hello.c - - case OP_RUST_HELLO: { - #ifdef FUN_WITH_RUST - const char *s = fun_rust_get_string(); - if (!s) s = ""; - push_value(vm, make_string(s)); - #else - vm_raise_error(vm, "RUST_HELLO requires FUN_WITH_RUST=ON at build time"); - push_value(vm, make_nil()); - #endif - break; - } - - For a stack-based math opcode (like fun_op_radd), you would declare and call the Rust function similarly: - - #ifdef FUN_WITH_RUST - extern int fun_op_radd(void* vm); // or use the proper VM type if available - #endif - - case OP_RADD: { - #ifdef FUN_WITH_RUST - (void)fun_op_radd(vm); - #else - vm_raise_error(vm, "RADD requires FUN_WITH_RUST=ON at build time"); - push_value(vm, make_nil()); // or follow your opcode’s error convention - #endif - break; - } - - Notes: - - Follow the existing opcode conventions for your module (core, math, strings, etc.). - - If your build puts the Rust symbol into a static library, make sure the VM target links it when FUN_WITH_RUST is ON (the top-level CMake already does this for the examples provided). - - ## Using Rust-backed opcodes from Fun - - Once wired, expose the opcode via a builtin function or directly in bytecode. The repository includes a demo builtin rust_hello() that returns a Rust-generated string. - - Run the example: - - 1) Build with Rust enabled (Debug): - cmake -S . -B build_debug -DFUN_WITH_RUST=ON - cmake --build build_debug --target fun - - 2) Execute the script: - build_debug/fun examples/rust_hello.fun - - Expected output: - Hello from Rust ops! - - If you build without Rust, calling rust_hello() raises a runtime error indicating that Rust integration is disabled. - - ## Stack discipline and error handling - - - Always pop exactly the arguments you expect and push exactly the results your opcode promises. Mismatch leads to stack corruption and hard-to-debug failures. - - Return an int status to the VM (0 for success). If your project uses a different convention for some opcodes, match it consistently. - - Validate types where appropriate (e.g., ensure values are integers before arithmetic). If a check fails, use the VM’s error mechanism (e.g., vm_raise_error) and follow the module’s convention on what to push after errors. - - ## Data types and FFI surface - - The minimal helpers shown cover 64-bit integers and simple strings. Extending the Rust<->C bridge usually involves: - - Declaring additional extern "C" functions in Rust that the C VM implements (to read/write values on the stack, construct arrays/maps/strings, etc.). - - Ensuring all pointers and lifetimes are well-defined: strings pushed to the VM should be copied or allocated using VM facilities so they remain valid after the call. - - Keeping Rust no_std unless you add an allocator and link setup to support std. - - ## Troubleshooting - - - Link errors: Make sure FUN_WITH_RUST=ON for your build directory and that the Rust library is compiled before linking the VM. Use the rust_ops_build target if provided by your profile. - - Missing symbol at runtime: Confirm #[no_mangle] and extern "C" on the Rust function and that C sees the correct prototype. - - Wrong or garbled values: Double-check stack order (Fun uses a stack VM; many ops pop in reverse order: first b, then a). - - No output from rust_hello(): Ensure you run a binary built with FUN_WITH_RUST=ON; otherwise the VM deliberately raises an error and returns Nil for that call. - - ## Small end-to-end checklist - - 1) Write the Rust function in src/rust/src/lib.rs with extern "C", #[no_mangle]. - 2) Use FFI helpers to pop arguments and push results. - 3) Add a C-side case under src/vm/... (or src/vm/rust/...) that calls your Rust function when the opcode executes. - 4) Ensure the build links Rust code when FUN_WITH_RUST=ON. - 5) Add or reuse a builtin in the parser/runtime to surface your opcode to Fun code. - 6) Build and run a small .fun example to validate behavior. - - ## References in this repo - - - Rust lib with examples: src/rust/src/lib.rs - - C-side hello wiring: src/vm/rust/hello.c - - Demo script: examples/rust_hello.fun - - General opcode reference: docs/opcodes.md - - ## Links - - Authoritative and practical resources on exposing Rust to C (FFI) and maintaining a C-compatible API: - - - Rustonomicon: FFI overview and best practices - https://doc.rust-lang.org/nomicon/ffi.html - - Rustonomicon: Calling Rust code from C - https://doc.rust-lang.org/nomicon/ffi.html#calling-rust-code-from-c - - The Rust Book: Unsafe and FFI (extern, #[no_mangle], calling Rust from other languages) - https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html#calling-rust-functions-from-other-languages - - Rust Reference: extern blocks, ABIs, and linkage - https://doc.rust-lang.org/reference/items/external-blocks.html - - Rust FFI Omnibus (examples for many patterns, including Rust ↔ C) - https://github.com/shepmaster/rust-ffi-omnibus - - cbindgen (generate C headers from Rust libraries) - https://cbindgen.github.io/cbindgen/ - - bindgen (generate Rust bindings to existing C headers; useful when mixing C and Rust) - https://github.com/rust-lang/rust-bindgen + +Key points: +- Use extern "C" and #[no_mangle] to fix the symbol name. +- Take a raw pointer to the VM as *mut Vm; return i32 status (0 for success). +- Interact with the VM stack via helper FFI functions declared as externs. +- Provide a minimal panic handler (no_std) as shown in lib.rs. + +Example: integer addition opcode implemented in Rust. + +In src/rust/src/lib.rs: + +``` +#![no_std] + + #[repr(C)] + pub struct Vm; + + extern "C" { + fn vm_pop_i64(vm: *mut Vm) -> i64; + fn vm_push_i64(vm: *mut Vm, v: i64); + } + + #[no_mangle] + pub extern "C" fn fun_op_radd(vm: *mut Vm) -> i32 { + unsafe { + let b = vm_pop_i64(vm); + let a = vm_pop_i64(vm); + vm_push_i64(vm, a + b); + } + 0 + } + + #[panic_handler] + fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} } +``` + +What this does: +- Pops two 64-bit integers from the VM stack. +- Pushes back their sum. +- Returns 0 to indicate success to the VM. + +You can add more extern helpers (e.g., for strings, arrays, maps) once they are exposed by the C VM. The repository already includes a simple string example returning a const char* from Rust, see fun_rust_get_string() usage below. + +## Wiring the opcode in C + +To make the VM call your Rust opcode, add a small C-side case that invokes the exported Rust symbol. A minimal pattern lives under src/vm/rust/. + +String demo wiring (already present): src/vm/rust/hello.c + +``` +case OP_RUST_HELLO: { +#ifdef FUN_WITH_RUST + const char *s = fun_rust_get_string(); + if (!s) s = ""; + push_value(vm, make_string(s)); +#else + vm_raise_error(vm, "RUST_HELLO requires FUN_WITH_RUST=ON at build time"); + push_value(vm, make_nil()); +#endif + break; +} +``` + +For a stack-based math opcode (like fun_op_radd), you would declare and call the Rust function similarly: + +``` +#ifdef FUN_WITH_RUST +extern int fun_op_radd(void* vm); // or use the proper VM type if available +#endif + +case OP_RADD: { +#ifdef FUN_WITH_RUST + (void)fun_op_radd(vm); +#else + vm_raise_error(vm, "RADD requires FUN_WITH_RUST=ON at build time"); + push_value(vm, make_nil()); // or follow your opcode’s error convention +#endif + break; +} +``` + +Notes: + +- Follow the existing opcode conventions for your module (core, math, strings, etc.). +- If your build puts the Rust symbol into a static library, make sure the VM target links it when FUN_WITH_RUST is ON (the top-level CMake already does this for the examples provided). + +## Using Rust-backed opcodes from Fun + +Once wired, expose the opcode via a builtin function or directly in bytecode. The repository includes a demo builtin rust_hello() that returns a Rust-generated string. + +Run the example: + +1) Build with Rust enabled (Debug): + cmake -S . -B build_debug -DFUN_WITH_RUST=ON + cmake --build build_debug --target fun + +2) Execute the script: + build_debug/fun examples/rust_hello.fun + +Expected output: + Hello from Rust ops! + +If you build without Rust, calling rust_hello() raises a runtime error indicating that Rust integration is disabled. + +## Stack discipline and error handling + +- Always pop exactly the arguments you expect and push exactly the results your opcode promises. Mismatch leads to stack corruption and hard-to-debug failures. +- Return an int status to the VM (0 for success). If your project uses a different convention for some opcodes, match it consistently. +- Validate types where appropriate (e.g., ensure values are integers before arithmetic). If a check fails, use the VM’s error mechanism (e.g., vm_raise_error) and follow the module’s convention on what to push after errors. + +## Data types and FFI surface + +The minimal helpers shown cover 64-bit integers and simple strings. Extending the Rust<->C bridge usually involves: + +- Declaring additional extern "C" functions in Rust that the C VM implements (to read/write values on the stack, construct arrays/maps/strings, etc.). +- Ensuring all pointers and lifetimes are well-defined: strings pushed to the VM should be copied or allocated using VM facilities so they remain valid after the call. +- Keeping Rust no_std unless you add an allocator and link setup to support std. + +## Troubleshooting + +- Link errors: Make sure FUN_WITH_RUST=ON for your build directory and that the Rust library is compiled before linking the VM. Use the rust_ops_build target if provided by your profile. +- Missing symbol at runtime: Confirm #[no_mangle] and extern "C" on the Rust function and that C sees the correct prototype. +- Wrong or garbled values: Double-check stack order (Fun uses a stack VM; many ops pop in reverse order: first b, then a). +- No output from rust_hello(): Ensure you run a binary built with FUN_WITH_RUST=ON; otherwise the VM deliberately raises an error and returns Nil for that call. + +## Small end-to-end checklist + +1) Write the Rust function in src/rust/src/lib.rs with extern "C", #[no_mangle]. +2) Use FFI helpers to pop arguments and push results. +3) Add a C-side case under src/vm/... (or src/vm/rust/...) that calls your Rust function when the opcode executes. +4) Ensure the build links Rust code when FUN_WITH_RUST=ON. +5) Add or reuse a builtin in the parser/runtime to surface your opcode to Fun code. +6) Build and run a small .fun example to validate behavior. + +## References in this repo + +- Rust lib with examples: src/rust/src/lib.rs +- C-side hello wiring: src/vm/rust/hello.c +- Demo script: examples/rust_hello.fun +- General opcode reference: docs/opcodes.md + +## Links + +Authoritative and practical resources on exposing Rust to C (FFI) and maintaining a C-compatible API: + +- Rustonomicon: FFI overview and best practices + https://doc.rust-lang.org/nomicon/ffi.html +- Rustonomicon: Calling Rust code from C + https://doc.rust-lang.org/nomicon/ffi.html#calling-rust-code-from-c +- The Rust Book: Unsafe and FFI (extern, #[no_mangle], calling Rust from other languages) + https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html#calling-rust-functions-from-other-languages +- Rust Reference: extern blocks, ABIs, and linkage + https://doc.rust-lang.org/reference/items/external-blocks.html +- Rust FFI Omnibus (examples for many patterns, including Rust ↔ C) + https://github.com/shepmaster/rust-ffi-omnibus +- cbindgen (generate C headers from Rust libraries) + https://cbindgen.github.io/cbindgen/ +- bindgen (generate Rust bindings to existing C headers; useful when mixing C and Rust) + https://github.com/rust-lang/rust-bindgen From bc5c699a6a52542018d6afdc0d6827ed8e46d84e Mon Sep 17 00:00:00 2001 From: hanez Date: Sun, 1 Feb 2026 00:39:13 +0100 Subject: [PATCH 11/39] Some style fixes. (0.38.6) --- CMakeLists.txt | 2 +- src/vm/cpp/add.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a4174dc..e53b82b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.5 LANGUAGES C) +project(fun VERSION 0.38.6 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) diff --git a/src/vm/cpp/add.cpp b/src/vm/cpp/add.cpp index 9f9f493..4a49a5a 100644 --- a/src/vm/cpp/add.cpp +++ b/src/vm/cpp/add.cpp @@ -21,8 +21,8 @@ extern "C" { } extern "C" int fun_op_cpp_add(VM *vm) { - int64_t b = vm_pop_i64(vm); int64_t a = vm_pop_i64(vm); + int64_t b = vm_pop_i64(vm); vm_push_i64(vm, a + b); return 0; // success } From e7e1563228dee965664b0e4679f00a882abdf45a Mon Sep 17 00:00:00 2001 From: hanez Date: Sun, 1 Feb 2026 01:02:29 +0100 Subject: [PATCH 12/39] Only CMake cosmetics. No code changes. (0.38.6) --- CMakeLists.txt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index e53b82b..17b4dca 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,6 +19,12 @@ else() set(_FUN_DEBUG_STATE "DISABLED") endif() +if(FUN_USE_MUSL) + set(_FUN_USE_MUSL_STATE "ENABLED") +else() + set(_FUN_USE_MUSL_STATE "DISABLED") +endif() + if(FUN_WITH_CPP) set(_FUN_WITH_CPP_STATE "ENABLED") else() @@ -33,6 +39,7 @@ endif() message(STATUS "==== Fun build options ====") message(STATUS " FUN_DEBUG: ${_FUN_DEBUG_STATE}") +message(STATUS " FUN_USE_MUSL: ${_FUN_USE_MUSL_STATE}") message(STATUS " FUN_WITH_CPP: ${_FUN_WITH_CPP_STATE}") message(STATUS " FUN_WITH_RUST: ${_FUN_WITH_RUST_STATE}") message(STATUS "===========================") From cd35ea767d2a1c2512f4fd0d14663f7ee0df34c8 Mon Sep 17 00:00:00 2001 From: hanez Date: Sun, 1 Feb 2026 01:32:54 +0100 Subject: [PATCH 13/39] Only CMake cosmetics. No code changes. (0.38.6) --- CMakeLists.txt | 12 ++++++------ examples/{ => error}/rust_vm_access.fun | 0 2 files changed, 6 insertions(+), 6 deletions(-) rename examples/{ => error}/rust_vm_access.fun (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 17b4dca..c7c8bbb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -20,21 +20,21 @@ else() endif() if(FUN_USE_MUSL) - set(_FUN_USE_MUSL_STATE "ENABLED") + set(_FUN_USE_MUSL_STATE "ENABLED") else() - set(_FUN_USE_MUSL_STATE "DISABLED") + set(_FUN_USE_MUSL_STATE "DISABLED") endif() if(FUN_WITH_CPP) - set(_FUN_WITH_CPP_STATE "ENABLED") + set(_FUN_WITH_CPP_STATE "ENABLED") else() - set(_FUN_WITH_CPP_STATE "DISABLED") + set(_FUN_WITH_CPP_STATE "DISABLED") endif() if(FUN_WITH_RUST) - set(_FUN_WITH_RUST_STATE "ENABLED") + set(_FUN_WITH_RUST_STATE "ENABLED") else() - set(_FUN_WITH_RUST_STATE "DISABLED") + set(_FUN_WITH_RUST_STATE "DISABLED") endif() message(STATUS "==== Fun build options ====") diff --git a/examples/rust_vm_access.fun b/examples/error/rust_vm_access.fun similarity index 100% rename from examples/rust_vm_access.fun rename to examples/error/rust_vm_access.fun From e017466cc7a3304214b9a6cb5c61520f070b83fb Mon Sep 17 00:00:00 2001 From: hanez Date: Sun, 8 Feb 2026 23:56:21 +0100 Subject: [PATCH 14/39] Added AES256 support... (0.38.7) --- CMakeLists.txt | 7 +- examples/crypto/aes256.fun | 45 +++++ lib/crypt/aes256.fun | 327 +++++++++++++++++++++++++++++++++++++ 3 files changed, 373 insertions(+), 6 deletions(-) create mode 100755 examples/crypto/aes256.fun create mode 100644 lib/crypt/aes256.fun diff --git a/CMakeLists.txt b/CMakeLists.txt index c7c8bbb..8b09c23 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.6 LANGUAGES C) +project(fun VERSION 0.38.7 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) @@ -229,15 +229,10 @@ endif() # Common locations (out-of-source and legacy in-source builds) list(APPEND _candidates \"\${CMAKE_BINARY_DIR}/install_manifest.txt\" - \"\${CMAKE_SOURCE_DIR}/install_manifest.txt\" \"\${CMAKE_BINARY_DIR}/install_manifest_Debug.txt\" \"\${CMAKE_BINARY_DIR}/install_manifest_Release.txt\" \"\${CMAKE_BINARY_DIR}/install_manifest_RelWithDebInfo.txt\" \"\${CMAKE_BINARY_DIR}/install_manifest_MinSizeRel.txt\" - \"\${CMAKE_SOURCE_DIR}/install_manifest_Debug.txt\" - \"\${CMAKE_SOURCE_DIR}/install_manifest_Release.txt\" - \"\${CMAKE_SOURCE_DIR}/install_manifest_RelWithDebInfo.txt\" - \"\${CMAKE_SOURCE_DIR}/install_manifest_MinSizeRel.txt\" ) set(_manifest_file \"\") diff --git a/examples/crypto/aes256.fun b/examples/crypto/aes256.fun new file mode 100755 index 0000000..f1f9b61 --- /dev/null +++ b/examples/crypto/aes256.fun @@ -0,0 +1,45 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-04 + */ + +/* + * Example: Using AES-256 (ECB) from lib/crypt/aes256.fun + * + * Test vector (FIPS-197, AES-256): + * key: 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f + * pt : 00112233445566778899aabbccddeeff + * ct : 8ea2b7ca516745bfeafc49904b496089 + */ + +#include + +aes = AES256() + +key = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" +pt = "00112233445566778899aabbccddeeff" + +ct = aes.encrypt_block_hex(pt, key) +print(ct) + +// Multi-block ECB example (two same blocks => two same ciphertext blocks) +//pt2 = join([pt, pt], "") +//ct2 = aes.encrypt_ecb_hex(pt2, key) +//print(ct2) + +/* Expected output: +8ea2b7ca516745bfeafc49904b496089 +*/ + +/* Wanted doutput: +8ea2b7ca516745bfeafc49904b496089 +8ea2b7ca516745bfeafc49904b4960898ea2b7ca516745bfeafc49904b496089 +*/ diff --git a/lib/crypt/aes256.fun b/lib/crypt/aes256.fun new file mode 100644 index 0000000..89c7767 --- /dev/null +++ b/lib/crypt/aes256.fun @@ -0,0 +1,327 @@ +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-04 + */ + +/* + * AES-256 (ECB) encryption in pure Fun. + * + * Public API (class AES256): + * encrypt_block_hex(pt_hex32, key_hex64) -> ct_hex32 + * encrypt_ecb_hex(hexStr, key_hex64) -> ct_hex (hexStr length must be multiple of 32) + * + * Example test vector (AES-256, FIPS-197): + * key: 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f + * pt : 00112233445566778899aabbccddeeff + * ct : 8ea2b7ca516745bfeafc49904b496089 + */ + +#include + +class AES256() + // ---------- Hex helpers ---------- + fun hex_val(this, ch) + if (ch == "0") + return 0 + else if (ch == "1") + return 1 + else if (ch == "2") + return 2 + else if (ch == "3") + return 3 + else if (ch == "4") + return 4 + else if (ch == "5") + return 5 + else if (ch == "6") + return 6 + else if (ch == "7") + return 7 + else if (ch == "8") + return 8 + else if (ch == "9") + return 9 + else if (ch == "a" || ch == "A") + return 10 + else if (ch == "b" || ch == "B") + return 11 + else if (ch == "c" || ch == "C") + return 12 + else if (ch == "d" || ch == "D") + return 13 + else if (ch == "e" || ch == "E") + return 14 + else if (ch == "f" || ch == "F") + return 15 + else + return 0 + + fun byte_from_hex_pair(this, hh) + hi = this.hex_val(substr(hh, 0, 1)) + lo = this.hex_val(substr(hh, 1, 1)) + return hi * 16 + lo + + fun from_hex(this, hex) + arr = [] + i = 0 + n = len(hex) + while i + 1 < n + push(arr, this.byte_from_hex_pair(substr(hex, i, 2))) + i = i + 2 + return arr + + fun two_hex(this, n) + n = n % 256 + d = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] + hi = n / 16 + lo = n % 16 + parts = [d[hi], d[lo]] + return join(parts, "") + + fun bytes_to_hex(this, arr) + i = 0 + out = [] + while i < len(arr) + push(out, this.two_hex(arr[i])) + i = i + 1 + return join(out, "") + + // ---------- Finite field helpers (GF(2^8)) ---------- + fun b8(this, x) + // clamp to 0..255 + while x < 0 + x = x + 256 + while x >= 256 + x = x - 256 + return x + + fun xtime(this, x) + x = this.b8(x) + hi = band(x, 128) + x2 = this.b8(shl(x, 1)) + if (hi != 0) + x2 = bxor(x2, 27) + return this.b8(x2) + + fun mul2(this, x) + return this.xtime(x) + fun mul3(this, x) + return bxor(this.xtime(x), this.b8(x)) + + // ---------- S-box & Rcon ---------- + S = [ + 99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118, + 202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192, + 183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21, + 4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117, + 9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132, + 83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207, + 208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168, + 81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210, + 205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115, + 96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219, + 224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121, + 231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8, + 186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138, + 112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158, + 225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223, + 140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22 + ] + + Rcon = [ + 0, + 1,2,4,8,16,32,64,128,27,54, + 108,216,171,77,154 + ] + + // ---------- Key schedule for AES-256 ---------- + // Input key (32 bytes). Output round keys as 240 bytes (Nr=14, Nb=4 -> (Nr+1)*Nb*4 = 60*4). + fun sub_word(this, w) + // w is 4-byte array + return [ this.S[w[0]], this.S[w[1]], this.S[w[2]], this.S[w[3]] ] + + fun rot_word(this, w) + return [ w[1], w[2], w[3], w[0] ] + + fun key_expansion(this, key_bytes) + Nk = 8 + Nb = 4 + Nr = 14 + W = [] // words; each word is 4 bytes stored back-to-back in a flat array of bytes + + // copy initial key (8 words -> 32 bytes) + i = 0 + while i < 32 + push(W, key_bytes[i]) + i = i + 1 + + // Expand to 60 words (240 bytes) + // We work in 4-byte steps, keeping temporary word t (4 bytes) + bytes_len = 32 + while bytes_len < 240 + // fetch previous word + t0 = W[bytes_len - 4] + t1 = W[bytes_len - 3] + t2 = W[bytes_len - 2] + t3 = W[bytes_len - 1] + t = [t0,t1,t2,t3] + + i_words = bytes_len / 4 // word index + if (i_words % Nk == 0) + t = this.sub_word(this.rot_word(t)) + rc = this.Rcon[i_words / Nk] + t[0] = bxor(t[0], rc) + else if (i_words % Nk == 4) + t = this.sub_word(t) + + // W[i] = W[i - Nk] xor t + j = 0 + while j < 4 + prev = W[bytes_len - 32 + j] // 32 bytes == Nk*4 + push(W, bxor(prev, t[j])) + j = j + 1 + bytes_len = bytes_len + 4 + return W // 240 bytes + + // ---------- State transforms ---------- + fun add_round_key(this, state, roundKeys, round) + // state: 16 bytes, roundKeys: 240 bytes, round idx 0..14 + // Nb=4, 16 bytes per round + offset = round * 16 + i = 0 + while i < 16 + state[i] = bxor(state[i], roundKeys[offset + i]) + i = i + 1 + return state + + fun sub_bytes(this, state) + i = 0 + while i < 16 + state[i] = this.S[state[i]] + i = i + 1 + return state + + fun shift_rows(this, s) + // s is 1D [r + 4*c] (row-major within column-major indexing): r in [0..3], c in [0..3] + // Row 0: no shift + // Row 1: left by 1 + t = s[1] + s[1] = s[5] + s[5] = s[9] + s[9] = s[13] + s[13] = t + // Row 2: left by 2 + t0 = s[2] + t1 = s[6] + s[2] = s[10] + s[6] = s[14] + s[10] = t0 + s[14] = t1 + // Row 3: left by 3 (aka right by 1) + t = s[15] + s[15] = s[11] + s[11] = s[7] + s[7] = s[3] + s[3] = t + return s + + fun mix_single_column(this, a0, a1, a2, a3) + // returns [r0,r1,r2,r3] + r0 = bxor(bxor(bxor(this.mul2(a0), this.mul3(a1)), a2), a3) + r1 = bxor(bxor(bxor(a0, this.mul2(a1)), this.mul3(a2)), a3) + r2 = bxor(bxor(bxor(a0, a1), this.mul2(a2)), this.mul3(a3)) + r3 = bxor(bxor(bxor(this.mul3(a0), a1), a2), this.mul2(a3)) + return [this.b8(r0), this.b8(r1), this.b8(r2), this.b8(r3)] + + fun mix_columns(this, s) + c = 0 + while c < 4 + i = c * 4 + col = this.mix_single_column(s[i], s[i+1], s[i+2], s[i+3]) + s[i] = col[0] + s[i+1] = col[1] + s[i+2] = col[2] + s[i+3] = col[3] + c = c + 1 + return s + + // ---------- Block encryption ---------- + fun encrypt_block_bytes(this, pt16, key32) + // pt16: 16 bytes array, key32: 32 bytes array + // returns 16 bytes array (ciphertext) + Nb = 4 + Nr = 14 + rk = this.key_expansion(key32) // 240 bytes + + // copy state + s = [] + i = 0 + while i < 16 + push(s, pt16[i]) + i = i + 1 + + // round 0 + s = this.add_round_key(s, rk, 0) + + round = 1 + while round < Nr + s = this.sub_bytes(s) + s = this.shift_rows(s) + s = this.mix_columns(s) + s = this.add_round_key(s, rk, round) + round = round + 1 + + // final round (no MixColumns) + s = this.sub_bytes(s) + s = this.shift_rows(s) + s = this.add_round_key(s, rk, Nr) + return s + + fun encrypt_block_hex(this, pt_hex32, key_hex64) + // Validate lengths + if (len(pt_hex32) != 32) + // Return empty on invalid input to match common style + return "" + if (len(key_hex64) != 64) + return "" + pt = this.from_hex(pt_hex32) + key = this.from_hex(key_hex64) + ct = this.encrypt_block_bytes(pt, key) + return this.bytes_to_hex(ct) + + fun encrypt_ecb_hex(this, hexStr, key_hex64) + // Robust handling that avoids substr semantics ambiguity by working on bytes + // Validate key + if (len(key_hex64) != 64) + return "" + // Validate hexStr length: must be even and represent a whole number of 16-byte blocks + if ((len(hexStr) % 2) != 0) + return "" + bytes = this.from_hex(hexStr) + if ((len(bytes) % 16) != 0) + return "" + key = this.from_hex(key_hex64) + out_bytes = [] + off = 0 + total = len(bytes) + while off < total + // collect 16-byte block + blk = [] + j = 0 + while j < 16 + push(blk, bytes[off + j]) + j = j + 1 + ct_blk = this.encrypt_block_bytes(blk, key) + // append to output + k = 0 + while k < 16 + push(out_bytes, ct_blk[k]) + k = k + 1 + off = off + 16 + return this.bytes_to_hex(out_bytes) From 54d94a1f3d04b738626968e62173822fdac638a3 Mon Sep 17 00:00:00 2001 From: hanez Date: Mon, 9 Feb 2026 00:29:50 +0100 Subject: [PATCH 15/39] Some stdlib refactoring removing duplicate code. (0.38.8) --- CMakeLists.txt | 2 +- lib/crypt/aes256.fun | 41 ++------------------- lib/crypt/crc32.fun | 41 ++------------------- lib/crypt/crc32c.fun | 41 ++------------------- lib/crypt/md5.fun | 41 ++------------------- lib/crypt/md5_legacy.fun | 37 +------------------ lib/crypt/ripemd160.fun | 41 ++------------------- lib/crypt/ripemd160_new_try.fun | 41 ++------------------- lib/crypt/sha1.fun | 41 ++------------------- lib/crypt/sha256.fun | 41 ++------------------- lib/crypt/sha384.fun | 63 +++------------------------------ lib/crypt/sha512.fun | 41 ++------------------- 12 files changed, 34 insertions(+), 437 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8b09c23..3fa1c0b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.7 LANGUAGES C) +project(fun VERSION 0.38.8 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) diff --git a/lib/crypt/aes256.fun b/lib/crypt/aes256.fun index 89c7767..3833399 100644 --- a/lib/crypt/aes256.fun +++ b/lib/crypt/aes256.fun @@ -22,49 +22,14 @@ * ct : 8ea2b7ca516745bfeafc49904b496089 */ +#include #include class AES256() // ---------- Hex helpers ---------- - fun hex_val(this, ch) - if (ch == "0") - return 0 - else if (ch == "1") - return 1 - else if (ch == "2") - return 2 - else if (ch == "3") - return 3 - else if (ch == "4") - return 4 - else if (ch == "5") - return 5 - else if (ch == "6") - return 6 - else if (ch == "7") - return 7 - else if (ch == "8") - return 8 - else if (ch == "9") - return 9 - else if (ch == "a" || ch == "A") - return 10 - else if (ch == "b" || ch == "B") - return 11 - else if (ch == "c" || ch == "C") - return 12 - else if (ch == "d" || ch == "D") - return 13 - else if (ch == "e" || ch == "E") - return 14 - else if (ch == "f" || ch == "F") - return 15 - else - return 0 - fun byte_from_hex_pair(this, hh) - hi = this.hex_val(substr(hh, 0, 1)) - lo = this.hex_val(substr(hh, 1, 1)) + hi = hex_val(substr(hh, 0, 1)) + lo = hex_val(substr(hh, 1, 1)) return hi * 16 + lo fun from_hex(this, hex) diff --git a/lib/crypt/crc32.fun b/lib/crypt/crc32.fun index 0759a90..c581b9c 100644 --- a/lib/crypt/crc32.fun +++ b/lib/crypt/crc32.fun @@ -23,6 +23,7 @@ // c = CRC32() // print(c.crc32_str("123456789")) +#include #include class CRC32() @@ -48,45 +49,9 @@ class CRC32() return band(this.u32(a), this.u32(b)) // hex helpers (mirroring style from lib/crypt/md5.fun) - fun hex_val(this, ch) - if (ch == "0") - return 0 - else if (ch == "1") - return 1 - else if (ch == "2") - return 2 - else if (ch == "3") - return 3 - else if (ch == "4") - return 4 - else if (ch == "5") - return 5 - else if (ch == "6") - return 6 - else if (ch == "7") - return 7 - else if (ch == "8") - return 8 - else if (ch == "9") - return 9 - else if (ch == "a" || ch == "A") - return 10 - else if (ch == "b" || ch == "B") - return 11 - else if (ch == "c" || ch == "C") - return 12 - else if (ch == "d" || ch == "D") - return 13 - else if (ch == "e" || ch == "E") - return 14 - else if (ch == "f" || ch == "F") - return 15 - else - return 0 - fun byte_from_hex_pair(this, hh) - hi = this.hex_val(substr(hh, 0, 1)) - lo = this.hex_val(substr(hh, 1, 1)) + hi = hex_val(substr(hh, 0, 1)) + lo = hex_val(substr(hh, 1, 1)) return hi * 16 + lo fun from_hex(this, hex) diff --git a/lib/crypt/crc32c.fun b/lib/crypt/crc32c.fun index 8a9cbd0..458c597 100644 --- a/lib/crypt/crc32c.fun +++ b/lib/crypt/crc32c.fun @@ -23,6 +23,7 @@ // c = CRC32C() // print(c.crc32c_hex("313233343536373839")) +#include #include class CRC32C() @@ -48,45 +49,9 @@ class CRC32C() return band(this.u32(a), this.u32(b)) // hex helpers (mirroring style from lib/crypt/md5.fun) - fun hex_val(this, ch) - if (ch == "0") - return 0 - else if (ch == "1") - return 1 - else if (ch == "2") - return 2 - else if (ch == "3") - return 3 - else if (ch == "4") - return 4 - else if (ch == "5") - return 5 - else if (ch == "6") - return 6 - else if (ch == "7") - return 7 - else if (ch == "8") - return 8 - else if (ch == "9") - return 9 - else if (ch == "a" || ch == "A") - return 10 - else if (ch == "b" || ch == "B") - return 11 - else if (ch == "c" || ch == "C") - return 12 - else if (ch == "d" || ch == "D") - return 13 - else if (ch == "e" || ch == "E") - return 14 - else if (ch == "f" || ch == "F") - return 15 - else - return 0 - fun byte_from_hex_pair(this, hh) - hi = this.hex_val(substr(hh, 0, 1)) - lo = this.hex_val(substr(hh, 1, 1)) + hi = hex_val(substr(hh, 0, 1)) + lo = hex_val(substr(hh, 1, 1)) return hi * 16 + lo fun from_hex(this, hex) diff --git a/lib/crypt/md5.fun b/lib/crypt/md5.fun index 41ab461..717b27a 100644 --- a/lib/crypt/md5.fun +++ b/lib/crypt/md5.fun @@ -20,6 +20,7 @@ // Class wrapper to avoid global name collisions and show class usage +#include #include class MD5() @@ -79,45 +80,9 @@ class MD5() return this.u32(this.u32(this.u32(a + b) + c) + d) // hex helpers - fun hex_val(this, ch) - if (ch == "0") - return 0 - else if (ch == "1") - return 1 - else if (ch == "2") - return 2 - else if (ch == "3") - return 3 - else if (ch == "4") - return 4 - else if (ch == "5") - return 5 - else if (ch == "6") - return 6 - else if (ch == "7") - return 7 - else if (ch == "8") - return 8 - else if (ch == "9") - return 9 - else if (ch == "a" || ch == "A") - return 10 - else if (ch == "b" || ch == "B") - return 11 - else if (ch == "c" || ch == "C") - return 12 - else if (ch == "d" || ch == "D") - return 13 - else if (ch == "e" || ch == "E") - return 14 - else if (ch == "f" || ch == "F") - return 15 - else - return 0 - fun byte_from_hex_pair(this, hh) - hi = this.hex_val(substr(hh, 0, 1)) - lo = this.hex_val(substr(hh, 1, 1)) + hi = hex_val(substr(hh, 0, 1)) + lo = hex_val(substr(hh, 1, 1)) return hi * 16 + lo fun from_hex(this, hex) diff --git a/lib/crypt/md5_legacy.fun b/lib/crypt/md5_legacy.fun index dd27ddc..9565430 100644 --- a/lib/crypt/md5_legacy.fun +++ b/lib/crypt/md5_legacy.fun @@ -9,6 +9,7 @@ * Added: 2025-10-01 */ +#include #include // Legacy global API and helpers. Please use the MD5 class (see lib/crypt/md5.fun). @@ -48,42 +49,6 @@ fun add32(a, b) fun add32_4(a, b, c, d) return u32(u32(u32(a + b) + c) + d) -fun hex_val(ch) - if (ch == "0") - return 0 - else if (ch == "1") - return 1 - else if (ch == "2") - return 2 - else if (ch == "3") - return 3 - else if (ch == "4") - return 4 - else if (ch == "5") - return 5 - else if (ch == "6") - return 6 - else if (ch == "7") - return 7 - else if (ch == "8") - return 8 - else if (ch == "9") - return 9 - else if (ch == "a" || ch == "A") - return 10 - else if (ch == "b" || ch == "B") - return 11 - else if (ch == "c" || ch == "C") - return 12 - else if (ch == "d" || ch == "D") - return 13 - else if (ch == "e" || ch == "E") - return 14 - else if (ch == "f" || ch == "F") - return 15 - else - return 0 - fun byte_from_hex_pair(hh) // hh is 2-char string hi = hex_val(substr(hh, 0, 1)) diff --git a/lib/crypt/ripemd160.fun b/lib/crypt/ripemd160.fun index bfb4d8b..773aed7 100644 --- a/lib/crypt/ripemd160.fun +++ b/lib/crypt/ripemd160.fun @@ -11,6 +11,7 @@ // THIS IS BROKEN ACTUALLY! IT DOES NOT CALCULATE THE EXPECTED HASHES! +#include #include class RIPEMD160() @@ -79,45 +80,9 @@ class RIPEMD160() else return this.u32(bxor(x, bor(y, bnot(z)))) - fun hex_val(this, ch) - if ch == "0" - return 0 - else if ch == "1" - return 1 - else if ch == "2" - return 2 - else if ch == "3" - return 3 - else if ch == "4" - return 4 - else if ch == "5" - return 5 - else if ch == "6" - return 6 - else if ch == "7" - return 7 - else if ch == "8" - return 8 - else if ch == "9" - return 9 - else if ch == "a" || ch == "A" - return 10 - else if ch == "b" || ch == "B" - return 11 - else if ch == "c" || ch == "C" - return 12 - else if ch == "d" || ch == "D" - return 13 - else if ch == "e" || ch == "E" - return 14 - else if ch == "f" || ch == "F" - return 15 - else - return 0 - fun byte_from_hex_pair(this, hh) - hi = this.hex_val(substr(hh, 0, 1)) - lo = this.hex_val(substr(hh, 1, 1)) + hi = hex_val(substr(hh, 0, 1)) + lo = hex_val(substr(hh, 1, 1)) return hi * 16 + lo fun from_hex(this, hex) diff --git a/lib/crypt/ripemd160_new_try.fun b/lib/crypt/ripemd160_new_try.fun index 41ba167..9489f17 100644 --- a/lib/crypt/ripemd160_new_try.fun +++ b/lib/crypt/ripemd160_new_try.fun @@ -19,6 +19,7 @@ // rip.ripemd160_hex(hexStr) -> digest hex string (lowercase) // rip.ripemd160_str("abc") -> digest hex string of ASCII bytes +#include #include class RIPEMD160() @@ -53,45 +54,9 @@ class RIPEMD160() return bnot(this.u32(x)) // hex helpers (same as md5/sha files) - fun hex_val(this, ch) - if (ch == "0") - return 0 - else if (ch == "1") - return 1 - else if (ch == "2") - return 2 - else if (ch == "3") - return 3 - else if (ch == "4") - return 4 - else if (ch == "5") - return 5 - else if (ch == "6") - return 6 - else if (ch == "7") - return 7 - else if (ch == "8") - return 8 - else if (ch == "9") - return 9 - else if (ch == "a" || ch == "A") - return 10 - else if (ch == "b" || ch == "B") - return 11 - else if (ch == "c" || ch == "C") - return 12 - else if (ch == "d" || ch == "D") - return 13 - else if (ch == "e" || ch == "E") - return 14 - else if (ch == "f" || ch == "F") - return 15 - else - return 0 - fun byte_from_hex_pair(this, hh) - hi = this.hex_val(substr(hh, 0, 1)) - lo = this.hex_val(substr(hh, 1, 1)) + hi = hex_val(substr(hh, 0, 1)) + lo = hex_val(substr(hh, 1, 1)) return hi * 16 + lo fun from_hex(this, hex) diff --git a/lib/crypt/sha1.fun b/lib/crypt/sha1.fun index 41a048a..398a3a9 100644 --- a/lib/crypt/sha1.fun +++ b/lib/crypt/sha1.fun @@ -17,6 +17,7 @@ // sha.sha1_hex(hexStr) -> digest hex string (lowercase) // sha.sha1_str("abc") -> digest hex string of ASCII bytes +#include #include class SHA1() @@ -37,45 +38,9 @@ class SHA1() return rol(x, s) // hex helpers - fun hex_val(this, ch) - if (ch == "0") - return 0 - else if (ch == "1") - return 1 - else if (ch == "2") - return 2 - else if (ch == "3") - return 3 - else if (ch == "4") - return 4 - else if (ch == "5") - return 5 - else if (ch == "6") - return 6 - else if (ch == "7") - return 7 - else if (ch == "8") - return 8 - else if (ch == "9") - return 9 - else if (ch == "a" || ch == "A") - return 10 - else if (ch == "b" || ch == "B") - return 11 - else if (ch == "c" || ch == "C") - return 12 - else if (ch == "d" || ch == "D") - return 13 - else if (ch == "e" || ch == "E") - return 14 - else if (ch == "f" || ch == "F") - return 15 - else - return 0 - fun byte_from_hex_pair(this, hh) - hi = this.hex_val(substr(hh, 0, 1)) - lo = this.hex_val(substr(hh, 1, 1)) + hi = hex_val(substr(hh, 0, 1)) + lo = hex_val(substr(hh, 1, 1)) return hi * 16 + lo fun from_hex(this, hex) diff --git a/lib/crypt/sha256.fun b/lib/crypt/sha256.fun index f9743d5..04f102b 100644 --- a/lib/crypt/sha256.fun +++ b/lib/crypt/sha256.fun @@ -19,6 +19,7 @@ // Example: // print(SHA256().sha256_hex("616263")) // "abc" => ba7816bf... +#include #include class SHA256() @@ -86,45 +87,9 @@ class SHA256() ] // hex helpers - fun hex_val(this, ch) - if (ch == "0") - return 0 - else if (ch == "1") - return 1 - else if (ch == "2") - return 2 - else if (ch == "3") - return 3 - else if (ch == "4") - return 4 - else if (ch == "5") - return 5 - else if (ch == "6") - return 6 - else if (ch == "7") - return 7 - else if (ch == "8") - return 8 - else if (ch == "9") - return 9 - else if (ch == "a" || ch == "A") - return 10 - else if (ch == "b" || ch == "B") - return 11 - else if (ch == "c" || ch == "C") - return 12 - else if (ch == "d" || ch == "D") - return 13 - else if (ch == "e" || ch == "E") - return 14 - else if (ch == "f" || ch == "F") - return 15 - else - return 0 - fun byte_from_hex_pair(this, hh) - hi = this.hex_val(substr(hh, 0, 1)) - lo = this.hex_val(substr(hh, 1, 1)) + hi = hex_val(substr(hh, 0, 1)) + lo = hex_val(substr(hh, 1, 1)) return hi * 16 + lo fun from_hex(this, hex) diff --git a/lib/crypt/sha384.fun b/lib/crypt/sha384.fun index 2373a30..7696160 100644 --- a/lib/crypt/sha384.fun +++ b/lib/crypt/sha384.fun @@ -23,49 +23,14 @@ // cb00753f45a35e8bb5a03d699ac65007272c32ab0eded163 // 1a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7 +#include #include class SHA384() // -------- hex helpers -------- - fun hex_val(this, ch) - if (ch == "0") - return 0 - else if (ch == "1") - return 1 - else if (ch == "2") - return 2 - else if (ch == "3") - return 3 - else if (ch == "4") - return 4 - else if (ch == "5") - return 5 - else if (ch == "6") - return 6 - else if (ch == "7") - return 7 - else if (ch == "8") - return 8 - else if (ch == "9") - return 9 - else if (ch == "a" || ch == "A") - return 10 - else if (ch == "b" || ch == "B") - return 11 - else if (ch == "c" || ch == "C") - return 12 - else if (ch == "d" || ch == "D") - return 13 - else if (ch == "e" || ch == "E") - return 14 - else if (ch == "f" || ch == "F") - return 15 - else - return 0 - fun byte_from_hex_pair(this, hh) - number hi = this.hex_val(substr(hh, 0, 1)) - number lo = this.hex_val(substr(hh, 1, 1)) + number hi = hex_val(substr(hh, 0, 1)) + number lo = hex_val(substr(hh, 1, 1)) return hi * 16 + lo fun from_hex(this, hex) @@ -79,24 +44,6 @@ class SHA384() i = i + 2 return arr - fun two_hex(this, n) - n = n % 256 - hexd = "0123456789abcdef" - number hi = (n / 16) % 16 - number lo = n % 16 - c1 = substr(hexd, hi, 1) - c2 = substr(hexd, lo, 1) - return join([c1, c2], "") - - fun bytes_to_hex(this, arr) - out = [] - number i = 0 - number L = len(arr) - while i < L - push(out, this.two_hex(arr[i])) - i = i + 1 - return join(out, "") - // -------- 32/64 helpers -------- fun u32(this, x) m = 4294967296 @@ -359,10 +306,10 @@ class SHA384() fun sha384_hex(this, hexStr) bytes = this.from_hex(hexStr) digest = this.sha384_bytes(bytes) - return this.bytes_to_hex(digest) + return bytes_to_hex(digest) // Hash raw string bytes (printable ASCII) fun sha384_str(this, str) bytes = string_to_bytes_ascii(str) digest = this.sha384_bytes(bytes) - return this.bytes_to_hex(digest) + return bytes_to_hex(digest) diff --git a/lib/crypt/sha512.fun b/lib/crypt/sha512.fun index eda388f..5401c0a 100644 --- a/lib/crypt/sha512.fun +++ b/lib/crypt/sha512.fun @@ -24,49 +24,14 @@ // ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a // 2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f +#include #include class SHA512() // -------- hex helpers -------- - fun hex_val(this, ch) - if (ch == "0") - return 0 - else if (ch == "1") - return 1 - else if (ch == "2") - return 2 - else if (ch == "3") - return 3 - else if (ch == "4") - return 4 - else if (ch == "5") - return 5 - else if (ch == "6") - return 6 - else if (ch == "7") - return 7 - else if (ch == "8") - return 8 - else if (ch == "9") - return 9 - else if (ch == "a" || ch == "A") - return 10 - else if (ch == "b" || ch == "B") - return 11 - else if (ch == "c" || ch == "C") - return 12 - else if (ch == "d" || ch == "D") - return 13 - else if (ch == "e" || ch == "E") - return 14 - else if (ch == "f" || ch == "F") - return 15 - else - return 0 - fun byte_from_hex_pair(this, hh) - number hi = this.hex_val(substr(hh, 0, 1)) - number lo = this.hex_val(substr(hh, 1, 1)) + number hi = hex_val(substr(hh, 0, 1)) + number lo = hex_val(substr(hh, 1, 1)) return hi * 16 + lo fun from_hex(this, hex) From 794a2354d6e279676ff5fd660730dd981db984a9 Mon Sep 17 00:00:00 2001 From: hanez Date: Mon, 9 Feb 2026 01:02:49 +0100 Subject: [PATCH 16/39] Some more stdlib refactoring removing duplicate code. (0.38.9) --- CMakeLists.txt | 2 +- lib/crypt/aes256.fun | 17 ++--------------- lib/crypt/crc32.fun | 17 ++--------------- lib/crypt/crc32c.fun | 25 ++----------------------- lib/crypt/md5.fun | 17 ++--------------- lib/crypt/ripemd160.fun | 7 +------ lib/crypt/ripemd160_new_try.fun | 10 +--------- lib/crypt/sha1.fun | 10 +--------- lib/crypt/sha256.fun | 10 +--------- lib/crypt/sha512.fun | 11 +---------- lib/hex.fun | 4 ++++ 11 files changed, 18 insertions(+), 112 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3fa1c0b..247d09f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.8 LANGUAGES C) +project(fun VERSION 0.38.9 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) diff --git a/lib/crypt/aes256.fun b/lib/crypt/aes256.fun index 3833399..3afd93e 100644 --- a/lib/crypt/aes256.fun +++ b/lib/crypt/aes256.fun @@ -27,33 +27,20 @@ class AES256() // ---------- Hex helpers ---------- - fun byte_from_hex_pair(this, hh) - hi = hex_val(substr(hh, 0, 1)) - lo = hex_val(substr(hh, 1, 1)) - return hi * 16 + lo - fun from_hex(this, hex) arr = [] i = 0 n = len(hex) while i + 1 < n - push(arr, this.byte_from_hex_pair(substr(hex, i, 2))) + push(arr, byte_from_hex_pair(substr(hex, i, 2))) i = i + 2 return arr - fun two_hex(this, n) - n = n % 256 - d = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] - hi = n / 16 - lo = n % 16 - parts = [d[hi], d[lo]] - return join(parts, "") - fun bytes_to_hex(this, arr) i = 0 out = [] while i < len(arr) - push(out, this.two_hex(arr[i])) + push(out, two_hex(arr[i])) i = i + 1 return join(out, "") diff --git a/lib/crypt/crc32.fun b/lib/crypt/crc32.fun index c581b9c..81cb7d2 100644 --- a/lib/crypt/crc32.fun +++ b/lib/crypt/crc32.fun @@ -49,34 +49,21 @@ class CRC32() return band(this.u32(a), this.u32(b)) // hex helpers (mirroring style from lib/crypt/md5.fun) - fun byte_from_hex_pair(this, hh) - hi = hex_val(substr(hh, 0, 1)) - lo = hex_val(substr(hh, 1, 1)) - return hi * 16 + lo - fun from_hex(this, hex) arr = [] i = 0 n = len(hex) while i + 1 < n - b = this.byte_from_hex_pair(substr(hex, i, 2)) + b = byte_from_hex_pair(substr(hex, i, 2)) push(arr, b) i = i + 2 return arr - fun two_hex(this, n) - n = n % 256 - d = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] - hi = n / 16 - lo = n % 16 - parts = [d[hi], d[lo]] - return join(parts, "") - fun bytes_to_hex(this, arr) i = 0 out = [] while i < len(arr) - push(out, this.two_hex(arr[i])) + push(out, two_hex(arr[i])) i = i + 1 return join(out, "") diff --git a/lib/crypt/crc32c.fun b/lib/crypt/crc32c.fun index 458c597..87840d4 100644 --- a/lib/crypt/crc32c.fun +++ b/lib/crypt/crc32c.fun @@ -49,44 +49,23 @@ class CRC32C() return band(this.u32(a), this.u32(b)) // hex helpers (mirroring style from lib/crypt/md5.fun) - fun byte_from_hex_pair(this, hh) - hi = hex_val(substr(hh, 0, 1)) - lo = hex_val(substr(hh, 1, 1)) - return hi * 16 + lo - fun from_hex(this, hex) arr = [] i = 0 n = len(hex) while i + 1 < n - b = this.byte_from_hex_pair(substr(hex, i, 2)) + b = byte_from_hex_pair(substr(hex, i, 2)) push(arr, b) i = i + 2 return arr - fun two_hex(this, n) - n = n % 256 - d = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] - hi = n / 16 - lo = n % 16 - parts = [d[hi], d[lo]] - return join(parts, "") - - fun bytes_to_hex(this, arr) - i = 0 - out = [] - while i < len(arr) - push(out, this.two_hex(arr[i])) - i = i + 1 - return join(out, "") - fun u32_to_hex8(this, n) // big-endian printing (MSB first), common for CRC displays b3 = this.and32(this.shr32(n, 24), 255) b2 = this.and32(this.shr32(n, 16), 255) b1 = this.and32(this.shr32(n, 8), 255) b0 = this.and32(n, 255) - return this.bytes_to_hex([b3, b2, b1, b0]) + return bytes_to_hex([b3, b2, b1, b0]) // Bitwise update (no table needed) using reflected polynomial 0x82F63B78 POLY = 2197175160 // 0x82F63B78 diff --git a/lib/crypt/md5.fun b/lib/crypt/md5.fun index 717b27a..36ae7bd 100644 --- a/lib/crypt/md5.fun +++ b/lib/crypt/md5.fun @@ -80,34 +80,21 @@ class MD5() return this.u32(this.u32(this.u32(a + b) + c) + d) // hex helpers - fun byte_from_hex_pair(this, hh) - hi = hex_val(substr(hh, 0, 1)) - lo = hex_val(substr(hh, 1, 1)) - return hi * 16 + lo - fun from_hex(this, hex) arr = [] i = 0 n = len(hex) while i + 1 < n - b = this.byte_from_hex_pair(substr(hex, i, 2)) + b = byte_from_hex_pair(substr(hex, i, 2)) push(arr, b) i = i + 2 return arr - fun two_hex(this, n) - n = n % 256 - d = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] - hi = n / 16 - lo = n % 16 - parts = [d[hi], d[lo]] - return join(parts, "") - fun bytes_to_hex(this, arr) i = 0 out = [] while i < len(arr) - push(out, this.two_hex(arr[i])) + push(out, two_hex(arr[i])) i = i + 1 return join(out, "") diff --git a/lib/crypt/ripemd160.fun b/lib/crypt/ripemd160.fun index 773aed7..2958f86 100644 --- a/lib/crypt/ripemd160.fun +++ b/lib/crypt/ripemd160.fun @@ -94,16 +94,11 @@ class RIPEMD160() i = i + 2 return arr - fun two_hex(this, n) - n = band(n, 0xFF) - d = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] - return join([d[shr(n, 4)], d[band(n, 0xF)]], "") - fun bytes_to_hex(this, arr) i = 0 out = [] while i < len(arr) - push(out, this.two_hex(arr[i])) + push(out, two_hex(arr[i])) i = i + 1 return join(out, "") diff --git a/lib/crypt/ripemd160_new_try.fun b/lib/crypt/ripemd160_new_try.fun index 9489f17..5e1addd 100644 --- a/lib/crypt/ripemd160_new_try.fun +++ b/lib/crypt/ripemd160_new_try.fun @@ -69,19 +69,11 @@ class RIPEMD160() i = i + 2 return arr - fun two_hex(this, n) - n = n % 256 - d = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] - hi = n / 16 - lo = n % 16 - parts = [d[hi], d[lo]] - return join(parts, "") - fun bytes_to_hex(this, arr) i = 0 out = [] while i < len(arr) - push(out, this.two_hex(arr[i])) + push(out, two_hex(arr[i])) i = i + 1 return join(out, "") diff --git a/lib/crypt/sha1.fun b/lib/crypt/sha1.fun index 398a3a9..6611f1c 100644 --- a/lib/crypt/sha1.fun +++ b/lib/crypt/sha1.fun @@ -53,19 +53,11 @@ class SHA1() i = i + 2 return arr - fun two_hex(this, n) - n = n % 256 - d = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] - hi = n / 16 - lo = n % 16 - parts = [d[hi], d[lo]] - return join(parts, "") - fun bytes_to_hex(this, arr) i = 0 out = [] while i < len(arr) - push(out, this.two_hex(arr[i])) + push(out, two_hex(arr[i])) i = i + 1 return join(out, "") diff --git a/lib/crypt/sha256.fun b/lib/crypt/sha256.fun index 04f102b..6d6c113 100644 --- a/lib/crypt/sha256.fun +++ b/lib/crypt/sha256.fun @@ -102,19 +102,11 @@ class SHA256() i = i + 2 return arr - fun two_hex(this, n) - n = n % 256 - d = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] - hi = n / 16 - lo = n % 16 - parts = [d[hi], d[lo]] - return join(parts, "") - fun bytes_to_hex(this, arr) i = 0 out = [] while i < len(arr) - push(out, this.two_hex(arr[i])) + push(out, two_hex(arr[i])) i = i + 1 return join(out, "") diff --git a/lib/crypt/sha512.fun b/lib/crypt/sha512.fun index 5401c0a..b9b2095 100644 --- a/lib/crypt/sha512.fun +++ b/lib/crypt/sha512.fun @@ -45,21 +45,12 @@ class SHA512() i = i + 2 return arr - fun two_hex(this, n) - n = n % 256 - hexd = "0123456789abcdef" - number hi = (n / 16) % 16 - number lo = n % 16 - c1 = substr(hexd, hi, 1) - c2 = substr(hexd, lo, 1) - return join([c1, c2], "") - fun bytes_to_hex(this, arr) out = [] number i = 0 number L = len(arr) while i < L - push(out, this.two_hex(arr[i])) + push(out, two_hex(arr[i])) i = i + 1 return join(out, "") diff --git a/lib/hex.fun b/lib/hex.fun index 819ce3f..913466c 100644 --- a/lib/hex.fun +++ b/lib/hex.fun @@ -12,6 +12,10 @@ */ // Hex utility functions +fun byte_from_hex_pair(hh) + hi = hex_val(substr(hh, 0, 1)) + lo = hex_val(substr(hh, 1, 1)) + return hi * 16 + lo fun hex_val(ch) if (ch == "0") From 8a1afc2aa1d8fa7810e53e2e91bf099da3cb5a0e Mon Sep 17 00:00:00 2001 From: hanez Date: Mon, 9 Feb 2026 01:43:06 +0100 Subject: [PATCH 17/39] Some more stdlib refactoring removing duplicate code. (0.38.10) --- CMakeLists.txt | 2 +- lib/crypt/aes256.fun | 12 ++---------- lib/crypt/crc32.fun | 10 +--------- lib/crypt/md5.fun | 12 ++---------- lib/crypt/sha1.fun | 12 ++---------- lib/crypt/sha256.fun | 12 ++---------- lib/crypt/sha512.fun | 13 ++----------- 7 files changed, 12 insertions(+), 61 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 247d09f..7287827 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.9 LANGUAGES C) +project(fun VERSION 0.38.10 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) diff --git a/lib/crypt/aes256.fun b/lib/crypt/aes256.fun index 3afd93e..9b0eaca 100644 --- a/lib/crypt/aes256.fun +++ b/lib/crypt/aes256.fun @@ -36,14 +36,6 @@ class AES256() i = i + 2 return arr - fun bytes_to_hex(this, arr) - i = 0 - out = [] - while i < len(arr) - push(out, two_hex(arr[i])) - i = i + 1 - return join(out, "") - // ---------- Finite field helpers (GF(2^8)) ---------- fun b8(this, x) // clamp to 0..255 @@ -245,7 +237,7 @@ class AES256() pt = this.from_hex(pt_hex32) key = this.from_hex(key_hex64) ct = this.encrypt_block_bytes(pt, key) - return this.bytes_to_hex(ct) + return bytes_to_hex(ct) fun encrypt_ecb_hex(this, hexStr, key_hex64) // Robust handling that avoids substr semantics ambiguity by working on bytes @@ -276,4 +268,4 @@ class AES256() push(out_bytes, ct_blk[k]) k = k + 1 off = off + 16 - return this.bytes_to_hex(out_bytes) + return bytes_to_hex(out_bytes) diff --git a/lib/crypt/crc32.fun b/lib/crypt/crc32.fun index 81cb7d2..f9ff6cc 100644 --- a/lib/crypt/crc32.fun +++ b/lib/crypt/crc32.fun @@ -59,21 +59,13 @@ class CRC32() i = i + 2 return arr - fun bytes_to_hex(this, arr) - i = 0 - out = [] - while i < len(arr) - push(out, two_hex(arr[i])) - i = i + 1 - return join(out, "") - fun u32_to_hex8(this, n) // big-endian printing (MSB first), common for CRC displays b3 = this.and32(this.shr32(n, 24), 255) b2 = this.and32(this.shr32(n, 16), 255) b1 = this.and32(this.shr32(n, 8), 255) b0 = this.and32(n, 255) - return this.bytes_to_hex([b3, b2, b1, b0]) + return bytes_to_hex([b3, b2, b1, b0]) // Bitwise update (no table needed) using reflected polynomial 0xEDB88320 POLY = 3988292384 // 0xEDB88320 diff --git a/lib/crypt/md5.fun b/lib/crypt/md5.fun index 36ae7bd..c8ff709 100644 --- a/lib/crypt/md5.fun +++ b/lib/crypt/md5.fun @@ -90,14 +90,6 @@ class MD5() i = i + 2 return arr - fun bytes_to_hex(this, arr) - i = 0 - out = [] - while i < len(arr) - push(out, two_hex(arr[i])) - i = i + 1 - return join(out, "") - // MD5 aux fun F(this, x, y, z) return this.or32(this.and32(x, y), this.and32(this.not32(x), z)) @@ -213,9 +205,9 @@ class MD5() fun md5_hex(this, hexStr) bytes = this.from_hex(hexStr) digest = this.md5_bytes(bytes) - return this.bytes_to_hex(digest) + return bytes_to_hex(digest) fun md5_str(this, str) bytes = string_to_bytes_ascii(str) digest = this.md5_bytes(bytes) - return this.bytes_to_hex(digest) + return bytes_to_hex(digest) diff --git a/lib/crypt/sha1.fun b/lib/crypt/sha1.fun index 6611f1c..e2ad3d4 100644 --- a/lib/crypt/sha1.fun +++ b/lib/crypt/sha1.fun @@ -53,14 +53,6 @@ class SHA1() i = i + 2 return arr - fun bytes_to_hex(this, arr) - i = 0 - out = [] - while i < len(arr) - push(out, two_hex(arr[i])) - i = i + 1 - return join(out, "") - // padding (SHA-1): append 0x80, then zeros until length ≡ 56 (mod 64), then 64-bit length big-endian fun pad_bytes(this, bytes) L = len(bytes) @@ -164,9 +156,9 @@ class SHA1() fun sha1_hex(this, hexStr) bytes = this.from_hex(hexStr) digest = this.sha1_bytes(bytes) - return this.bytes_to_hex(digest) + return bytes_to_hex(digest) fun sha1_str(this, str) bytes = string_to_bytes_ascii(str) digest = this.sha1_bytes(bytes) - return this.bytes_to_hex(digest) + return bytes_to_hex(digest) diff --git a/lib/crypt/sha256.fun b/lib/crypt/sha256.fun index 6d6c113..92d6432 100644 --- a/lib/crypt/sha256.fun +++ b/lib/crypt/sha256.fun @@ -102,14 +102,6 @@ class SHA256() i = i + 2 return arr - fun bytes_to_hex(this, arr) - i = 0 - out = [] - while i < len(arr) - push(out, two_hex(arr[i])) - i = i + 1 - return join(out, "") - // padding (SHA-256) fun pad_bytes(this, bytes) L = len(bytes) @@ -217,10 +209,10 @@ class SHA256() fun sha256_hex(this, hexStr) bytes = this.from_hex(hexStr) digest = this.sha256_bytes(bytes) - return this.bytes_to_hex(digest) + return bytes_to_hex(digest) // Hash raw string bytes (printable ASCII). Example: sha256_str("616263") -> ee2109... fun sha256_str(this, str) bytes = string_to_bytes_ascii(str) digest = this.sha256_bytes(bytes) - return this.bytes_to_hex(digest) + return bytes_to_hex(digest) diff --git a/lib/crypt/sha512.fun b/lib/crypt/sha512.fun index b9b2095..e66aa0f 100644 --- a/lib/crypt/sha512.fun +++ b/lib/crypt/sha512.fun @@ -45,15 +45,6 @@ class SHA512() i = i + 2 return arr - fun bytes_to_hex(this, arr) - out = [] - number i = 0 - number L = len(arr) - while i < L - push(out, two_hex(arr[i])) - i = i + 1 - return join(out, "") - // -------- 32/64 helpers -------- fun u32(this, x) m = 4294967296 @@ -316,10 +307,10 @@ class SHA512() fun sha512_hex(this, hexStr) bytes = this.from_hex(hexStr) digest = this.sha512_bytes(bytes) - return this.bytes_to_hex(digest) + return bytes_to_hex(digest) // Hash raw string bytes (printable ASCII). Example: sha512_str("616263") -> ee2109... fun sha512_str(this, str) bytes = string_to_bytes_ascii(str) digest = this.sha512_bytes(bytes) - return this.bytes_to_hex(digest) + return bytes_to_hex(digest) From 494f47a9a509dab92b169fd3bc8dd34fde247260 Mon Sep 17 00:00:00 2001 From: hanez Date: Mon, 9 Feb 2026 02:28:19 +0100 Subject: [PATCH 18/39] Added some ctest stuff. No code changes. (0.38.11) --- CMakeLists.txt | 41 ++++++++++++++++++++++++++++++++++++++++- make | 8 +++++++- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7287827..8aef879 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.10 LANGUAGES C) +project(fun VERSION 0.38.11 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) @@ -355,6 +355,45 @@ endfunction() # Define the uninstall target fun_add_uninstall_target() +# --- CTest integration: run crypto examples as self-tests --- +# These examples print results and exit non-zero on mismatch, so we can +# wire them into CTest to have CI verify cryptographic correctness. +include(CTest) +if(BUILD_TESTING) + enable_testing() + + # Helper to register a Fun example as a CTest test + function(fun_add_example_test TEST_NAME SCRIPT_REL) + # Absolute path to the example script in source tree + set(_script "${CMAKE_SOURCE_DIR}/${SCRIPT_REL}") + if(NOT EXISTS "${_script}") + message(FATAL_ERROR "fun_add_example_test: script not found: ${_script}") + endif() + + add_test(NAME ${TEST_NAME} + COMMAND $ "${_script}" + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + ) + # Ensure the interpreter can find standard library (*.fun) + # The examples were authored to respect FUN_LIB_DIR. + set_tests_properties(${TEST_NAME} PROPERTIES + ENVIRONMENT "FUN_LIB_DIR=${CMAKE_SOURCE_DIR}/lib" + ) + endfunction() + + # Crypto example self-tests + fun_add_example_test(crypto_md5 examples/crypto/md5_demo.fun) + fun_add_example_test(crypto_sha1 examples/crypto/sha1_demo.fun) + fun_add_example_test(crypto_sha256_hex examples/crypto/sha256_demo.fun) + fun_add_example_test(crypto_sha256_str examples/crypto/sha256_str_demo.fun) + fun_add_example_test(crypto_sha512_hex examples/crypto/sha512_demo.fun) + fun_add_example_test(crypto_sha512_str examples/crypto/sha512_str_demo.fun) + fun_add_example_test(crypto_sha384 examples/crypto/sha384_example.fun) + fun_add_example_test(crypto_crc32 examples/crypto/crc32_example.fun) + fun_add_example_test(crypto_crc32c examples/crypto/crc32c_example.fun) + fun_add_example_test(crypto_aes256 examples/crypto/aes256.fun) +endif() + # Install rules # Binary install(TARGETS fun diff --git a/make b/make index 573ba26..4f7dd8d 100755 --- a/make +++ b/make @@ -79,11 +79,17 @@ elif [ "$target" = "cpp_all" ]; then -DFUN_WITH_NOTCURSES=ON \ -DFUN_WITH_CPP=ON \ && cmake --build build --target fun - elif [ "$target" = "cpp_minimal" ]; then + elif [ "$target" = "cpp_minimal" ]; then rm -rf build \ && cmake -S . -B build \ -DFUN_WITH_CPP=ON \ && cmake --build build --target fun + elif [ "$target" = "ctest" ]; then + rm -rf build \ + && cmake -S . -B build \ + && cmake --build build --target fun \ + && (cd ./build/ \ + && ctest --output-on-failure -R crypto) elif [ "$target" = "debug" ]; then rm -rf build \ && cmake -S . -B build \ From 55c32952ecf971d1bc614519308f25b8919ce892 Mon Sep 17 00:00:00 2001 From: hanez Date: Wed, 11 Feb 2026 03:02:29 +0100 Subject: [PATCH 19/39] Some more documentation fun about includes. No code changes. (0.38.11) --- docs/includes.md | 137 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 docs/includes.md diff --git a/docs/includes.md b/docs/includes.md new file mode 100644 index 0000000..b56cd01 --- /dev/null +++ b/docs/includes.md @@ -0,0 +1,137 @@ +# Includes in Fun: local vs. system and the FUN_LIB_DIR environment variable + +This document explains how to use local and system includes in Fun source files and how `FUN_LIB_DIR` controls where system includes are resolved from. It also covers namespaced includes with `as`. + +## Quick summary + +- Local includes: `#include "relative/path/to/file.fun"` + - Resolved relative to the current working directory (`$PWD`) where you run `fun`. +- System includes: `#include ` + - Resolved using: + 1) `FUN_LIB_DIR` (if set) + 2) `DEFAULT_LIB_DIR` (compile-time default; typically `/usr/share/fun/lib/` after install) + 3) Fallback to `lib/` under the current working directory (developer convenience) +- Optional namespacing: `#include <...> as ns` or `#include "..." as ns` + +## Local includes (quoted) + +Use double quotes to include files relative to the directory you execute `fun` from. + +Example: +``` +#include "examples/include_local_util.fun" + +print("== include local demo ==") +greet("Fun") + +number a = 2 +number b = 3 +print("sum(" + to_string(a) + ", " + to_string(b) + ") = " + to_string(sum(a, b))) +``` + +- Resolution rule: quoted includes are read directly from the given path relative to `$PWD`. +- Typical use: including helper modules that live within your project tree. + +## System includes (angle brackets) + +Use angle brackets to include modules from the Fun standard library or any library directory you point `FUN_LIB_DIR` to. + +Example: +``` +#include +#include + +print("== include lib demo ==") +hello_lib() + +number x = 10 +number y = 32 +print("add(" + to_string(x) + ", " + to_string(y) + ") = " + to_string(add(x, y))) +print("times(" + to_string(x) + ", " + to_string(y) + ") = " + to_string(times(x, y))) +``` + +Resolution order for `#include <...>`: + +1) `FUN_LIB_DIR` (environment variable), with automatic handling of trailing `/` or `\` +2) `DEFAULT_LIB_DIR` (compile-time define) +3) `lib/` under the current working directory (developer fallback) + +If the file cannot be read from any location, an "Include error" is printed with the last attempted path. + +## Namespaced includes with `as` + +You can import a module into a namespace to avoid symbol collisions or to make intent explicit. + +Examples: +``` +// Import stdlib helpers under alias 'm' +#include as m +print("m.add(2, 3) = " + to_string(m.add(2, 3))) +print("m.times(4, 5) = " + to_string(m.times(4, 5))) + +// Import a local module into alias 'mod' +#include "examples/namespaced_mod.fun" as mod +print(mod.hello("Fun")) +g = mod.Greeter("Hi") +g.say("World") +``` + +Rules: +- `as` must be followed by a valid identifier (letters, digits, underscore, starting with a letter or underscore). +- Works for both local (`"..."`) and system (`<...>`) includes. + +## The FUN_LIB_DIR environment variable + +`FUN_LIB_DIR` overrides where the interpreter looks for angle-bracket includes. It is the first location checked when resolving `#include <...>`. + +- When running directly from the repository without installing: + - Linux/macOS/FreeBSD: + ``` + FUN_LIB_DIR="$(pwd)/lib" ./build/fun examples/include_namespace.fun + ``` + - Windows (CMD): + ``` + set FUN_LIB_DIR=%CD%\lib && build-debug\fun.exe examples\include_namespace.fun + ``` + - Windows (PowerShell): + ``` + $env:FUN_LIB_DIR="$PWD\lib"; .\build\fun.exe examples\include_namespace.fun + ``` + +- After installation: + - You usually do not need `FUN_LIB_DIR` because `DEFAULT_LIB_DIR` points to the installed stdlib (e.g., `/usr/share/fun/lib/` on Linux). You can still set `FUN_LIB_DIR` to test custom or alternate library trees. + +- Interaction with `DEFAULT_LIB_DIR`: + - If `FUN_LIB_DIR` is not set or is empty, the interpreter tries `DEFAULT_LIB_DIR` (a compile-time value). Build systems may set this via `-DDEFAULT_LIB_DIR=...`. The project’s CMake sets sensible OS-specific defaults. + +- Developer fallback: + - If neither `FUN_LIB_DIR` nor `DEFAULT_LIB_DIR` resolves the include, the interpreter finally tries `lib/` relative to `$PWD`. + +Tips: +- To verify which stdlib is being used, temporarily include a file you control and log from it. +- Mind your current directory: running `fun` from a different folder changes how quoted includes resolve and can change the `lib/` fallback for angle-bracket includes. + +## Common patterns and best practices + +- Prefer quoted includes for project-internal modules: `#include "src/mods/foo.fun"` +- Prefer angle brackets for stdlib and external libs: `#include ` +- Use `as` for clarity and to avoid name clashes: `#include as math` +- When developing against the repo without installing, export `FUN_LIB_DIR=$(pwd)/lib` before running examples or your app. +- Keep paths portable: avoid OS-specific separators inside include paths; the resolver handles path joining. + +## Troubleshooting include errors + +- Error: `Include error: cannot read '...'` + - Check if the path exists in the intended location: + - For `"..."`: is the path correct relative to your current working directory? + - For `<...>`: does the file exist under `FUN_LIB_DIR/<...>` or `DEFAULT_LIB_DIR/<...>` or `./lib/<...>`? + - Ensure `FUN_LIB_DIR` is exported in the same shell session where you run `fun`. + - On Windows, verify you used the correct syntax for setting environment variables in CMD vs. PowerShell. + +## See also + +- Examples in this repository: + - `examples/include_local.fun` + - `examples/include_lib.fun` + - `examples/include_namespace.fun` +- REPL notes: `docs/repl.md` (explains completion that also scans `FUN_LIB_DIR`) From ed0d30078bc873321c63d9bf3599b67137291947 Mon Sep 17 00:00:00 2001 From: hanez Date: Wed, 11 Feb 2026 08:45:10 +0100 Subject: [PATCH 20/39] Some more documentation fun about types. No code changes. (0.38.11) --- docs/types.md | 198 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 198 insertions(+) create mode 100644 docs/types.md diff --git a/docs/types.md b/docs/types.md new file mode 100644 index 0000000..057d088 --- /dev/null +++ b/docs/types.md @@ -0,0 +1,198 @@ +# Core datatypes in Fun: arrays, maps, strings, numbers, booleans and nil + +This guide shows how to create and use the most common Fun datatypes with practical examples. It focuses on arrays and maps, and also recaps numbers, floats, strings, booleans and nil so examples are self‑contained. + +## Quick overview + +- number: signed integer (use uclamp/sclamp for width handling) +- float: 64‑bit floating point +- string: immutable text/bytes +- array: ordered, zero‑indexed sequence +- map: associative dictionary (usually string keys) +- boolean: 1 (true) or 0 (false) +- nil: absence of a value + +Helpers used throughout: +- typeof(x) → string type name +- to_string(x), to_number(x), cast(x, typeName) +- len(x) works for strings and arrays + +## Arrays + +Create arrays with square brackets and comma‑separated elements. + +``` +// creation +a = [1, 2, 3] +b = ["alpha", "beta"] +c = [] // empty array + +print(typeof(a)) // "array" +print(len(a)) // 3 + +// indexing (0-based) +print(a[0]) // 1 +print(a[2]) // 3 + +// set by index +a[1] = 42 +print(a) // [1, 42, 3] + +// push/pop (append and pop-last) +push(a, 7) // returns new length (4) +v = apop(a) // removes and returns last element (7) + +// insert/remove at index +insert(a, 1, 99) // a becomes [1, 99, 42, 3] +remove(a, 2) // a becomes [1, 99, 3] + +// slicing (start inclusive, end exclusive) +print(slice(a, 0, 2)) // [1, 99] + +// iteration +for i = 0; i < len(a); i = i + 1 { + print("a[" + to_string(i) + "] = " + to_string(a[i])) +} + +// enumerate helper yields index/value pairs +#include as it // typical place for helpers; adjust to your setup +for pair in it.enumerate(["x", "y"]) { + idx = pair[0] + val = pair[1] + print(idx + ":" + val) +} +``` + +Notes: +- Indexing is bounds‑checked; invalid indices cause a runtime error that you can inspect with --trace or REPL‑on‑error. +- Arrays are mutable; operations modify in place unless documented otherwise. + +## Maps + +Create maps with curly braces. Keys are typically strings; values can be any type. + +``` +// creation +user = { "name": "Ada", "age": 37 } +cfg = {} + +print(typeof(user)) // "map" + +// get/set by key +print(user["name"]) // Ada +user["lang"] = "en" + +// overwrite existing key +user["age"] = 38 + +// nested access +book = { "title": "Fun Handbook", "meta": { "pages": 120 } } +print(book["meta"]["pages"]) // 120 + +// check presence via nil comparison (common pattern) +val = user["missing"] +if val == nil { print("no such key") } + +// iterate known keys (maps are not ordered) +keys = ["name", "age", "lang"] +for i = 0; i < len(keys); i = i + 1 { + k = keys[i] + print(k + " = " + to_string(user[k])) +} +``` + +Notes: +- Accessing a non‑existing key returns nil; write a guard before using it as another type. +- Maps are mutable; assigning with map["k"] = v updates in place. + +## Strings (brief) + +``` +s = "hello, world" +print(len(s)) // 12 +print(substr(s, 7, 5)) // world +print(find(s, ",")) // 5 (index) or -1 if not found + +parts = split("a,b,c", ",") // ["a","b","c"] +print(join(parts, ";")) // a;b;c +``` + +## Numbers and floats (brief) + +``` +n = 10 +f = 3.14 +print(n + 2) // 12 +print(f * 2) // 6.28 + +// clamp to widths when needed +print(uclamp(300, 8)) // 44 (300 mod 256) +``` + +## Booleans and nil + +``` +ok = 1 // true +no = 0 // false +none = nil + +if ok && !no { print("yay") } +if none == nil { print("is nil") } +``` + +## Conversions and typing + +``` +x = "42" +print(to_number(x) + 1) // 43 + +print(typeof([1,2,3])) // "array" +print(typeof({})) // "map" +``` + +## Common patterns + +- Accumulate values: + `` + acc = [] + for i = 0; i < 5; i = i + 1 { push(acc, i*i) } + print(acc) // [0,1,4,9,16] + `` + +- Group related data with a map: + `` + person = { "name": "Lin", "skills": ["C", "Fun"] } + print(person["skills"][1]) // Fun + ``` + +- Safe map read: + `` + v = person["twitter"] + handle = v != nil ? v : "(none)" + print(handle) + ``` + +## Interop highlights + +- JSON (optional module) maps JSON arrays to Fun arrays and JSON objects to Fun maps. + `` + #include + data = json_parse("{\"a\":[1,2]} ") + print(typeof(data)) // map + print(typeof(data["a"])) // array + ``` + +## Troubleshooting + +- Index errors on arrays typically mean you used a negative index or >= len(a). +- Map lookups that return nil: ensure the key exists and is spelled exactly. +- Converting types: prefer to_number/to_string; cast(x, "string") is also available for certain conversions. + +## See also + +- docs/handbook.md — “Core types and operations”, arrays/maps helpers +- docs/includes.md — how to include modules and use namespaces +- Examples in this repo: + - examples/arrays.fun, examples/arrays_advanced.fun, examples/arrays_iter.fun + - examples/maps.fun + - examples/json/* (when JSON is enabled) From 988e9e4c27596cf8d886659b2e4d3c92791211c6 Mon Sep 17 00:00:00 2001 From: hanez Date: Wed, 11 Feb 2026 08:46:43 +0100 Subject: [PATCH 21/39] Some more documentation fun about types. No code changes. (0.38.11) --- docs/types.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/types.md b/docs/types.md index 057d088..a4ffc66 100644 --- a/docs/types.md +++ b/docs/types.md @@ -153,20 +153,23 @@ print(typeof({})) // "map" ## Common patterns - Accumulate values: - `` +- + ``` acc = [] for i = 0; i < 5; i = i + 1 { push(acc, i*i) } print(acc) // [0,1,4,9,16] - `` + ``` - Group related data with a map: - `` +- + ``` person = { "name": "Lin", "skills": ["C", "Fun"] } print(person["skills"][1]) // Fun ``` - Safe map read: - `` +- + ``` v = person["twitter"] handle = v != nil ? v : "(none)" print(handle) @@ -175,7 +178,8 @@ print(typeof({})) // "map" ## Interop highlights - JSON (optional module) maps JSON arrays to Fun arrays and JSON objects to Fun maps. - `` + + ``` #include data = json_parse("{\"a\":[1,2]} ") print(typeof(data)) // map From b558af3a5f8ac6e90c05e6c79d35c4339202bd31 Mon Sep 17 00:00:00 2001 From: hanez Date: Wed, 11 Feb 2026 08:53:18 +0100 Subject: [PATCH 22/39] Some more documentation fun. No code changes. (0.38.11) --- docs/README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 docs/README.md diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..5e2d09b --- /dev/null +++ b/docs/README.md @@ -0,0 +1,18 @@ +# Fun Documentation Index + +This file serves as an index of the documents in this directory. Links are relative and can be opened directly on Git hosting or locally. + +## Overview + +- [handbook.md](./handbook.md) — Comprehensive handbook for the Fun language and VM: install/build, configuration flags, usage, and full feature overview. +- [types.md](./types.md) — Core types (numbers, strings, arrays, maps, nil/bool), common operations, patterns, and interop notes. +- [includes.md](./includes.md) — Using local vs. system includes, FUN_LIB_DIR, DEFAULT_LIB_DIR, and namespaced includes with `as`. +- [repl.md](./repl.md) — REPL guide: how to build/launch, editing and history, completions, REPL‑on‑error, and tips. +- [opcodes.md](./opcodes.md) — VM opcodes overview grouped by domain with brief behavior/stack notes. +- [internals.md](./internals.md) — Implementation details: bytecode format, VM architecture, stacks/frames, parser, and dispatch. +- [rust.md](./rust.md) — Writing Rust‑backed opcodes and wiring them into the C VM; build/setup notes. + +## Tips + +- When building from the repo without installing, set `FUN_LIB_DIR` to the local `./lib` directory so examples and the REPL can locate the stdlib. +- For a broader project overview and quickstart, see the repository root [README.md](../README.md). From 41ebd59187edc29e2a0db40b5aa4480494af0b3d Mon Sep 17 00:00:00 2001 From: hanez Date: Wed, 11 Feb 2026 17:34:24 +0100 Subject: [PATCH 23/39] Some more documentation fun. No code changes. (0.38.11) --- docs/README.md | 3 + docs/examples.md | 62 ++++++++++++++++ docs/testing.md | 59 +++++++++++++++ docs/troubleshooting.md | 91 +++++++++++++++++++++++ play.fun | 156 ---------------------------------------- 5 files changed, 215 insertions(+), 156 deletions(-) create mode 100644 docs/examples.md create mode 100644 docs/testing.md create mode 100644 docs/troubleshooting.md delete mode 100755 play.fun diff --git a/docs/README.md b/docs/README.md index 5e2d09b..3f027a9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -11,6 +11,9 @@ This file serves as an index of the documents in this directory. Links are relat - [opcodes.md](./opcodes.md) — VM opcodes overview grouped by domain with brief behavior/stack notes. - [internals.md](./internals.md) — Implementation details: bytecode format, VM architecture, stacks/frames, parser, and dispatch. - [rust.md](./rust.md) — Writing Rust‑backed opcodes and wiring them into the C VM; build/setup notes. +- [examples.md](./examples.md) — How to run the examples and the interactive showcase script, with environment tips. +- [testing.md](./testing.md) — How to build and run tests/targets with CMake/CTest, and where to add new tests. +- [troubleshooting.md](./troubleshooting.md) — Common issues and quick fixes for build, includes, and REPL usage. ## Tips diff --git a/docs/examples.md b/docs/examples.md new file mode 100644 index 0000000..ab18e0e --- /dev/null +++ b/docs/examples.md @@ -0,0 +1,62 @@ +# Running the Examples + +This page shows how to run the example programs included with the repository and how to use the interactive showcase script. + +All commands assume you are in the repository root. + +## Prerequisites + +- Build the interpreter (see handbook.md). You’ll have `build_debug/fun` or `build_release/fun` (paths may vary by your setup/IDE). +- Set FUN_LIB_DIR to the repo’s lib directory when running without installation so `#include <...>` can find the standard library. + +Example (Linux/macOS/BSD): + +``` +FUN_LIB_DIR="$(pwd)/lib" ./build_debug/fun examples/include_lib.fun +``` + +Windows (PowerShell): + +``` +$env:FUN_LIB_DIR = "$PWD/lib" +./build_release/fun.exe .\examples\include_lib.fun +``` + +## Interactive showcase: play.fun + +The script `./play.fun` discovers all `.fun` files under `./examples` and offers to run them one by one: + +``` +./play.fun +``` + +Notes: +- The script auto-picks your interpreter (FUN_BIN env or `fun` in PATH) and ensures `FUN_LIB_DIR=./lib` so examples resolve includes correctly. +- It shows the exit code for each run and summarizes failures at the end. + +Tip: you can run specific examples directly too: + +``` +FUN_LIB_DIR="$(pwd)/lib" fun examples/crypto/aes256.fun +``` + +## Example categories + +Browse the `examples/` tree for areas of interest: + +- crypto — crypto demonstrations (e.g., AES) +- blocking / interactive — I/O or user-interactive patterns +- error / broken — negative tests and error showcases +- math — numeric operations +- sqlited / data — data access and HTTP/CGI-style samples (platform dependent) + +## Creating your own examples + +Place your `.fun` files anywhere under `examples/` to have them picked up by `play.fun`. Use quoted includes for project-local helpers and angle brackets for stdlib modules: + +``` +#include "examples/my_lib/common.fun" +#include +``` + +If you add an example showcasing a new feature, also consider adding a brief note to the relevant doc (types.md, includes.md, opcodes.md, etc.). diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..6176b70 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,59 @@ +# Building and Running Tests + +This page explains how to build and run Fun’s tests using the existing CMake targets. It also points to where opcode and language tests typically live and how to add new ones. + +## Test-related targets + +Depending on your generator/profile, you may see the following targets in your IDE or via `cmake --build`: + +- fun_test (executable) — main test runner/binary (where present) +- test_opcodes (executable) — opcode-focused tests/demos +- Continuous*/Experimental*/Nightly* — CTest dashboards (optional; mostly for CI) +- build / run / repl — convenience targets for local development + +To list targets with CMake directly, consult your IDE or run the build system’s metadata commands. In CLion, targets are shown in the Build tool window. + +## Running tests from the command line + +Debug profile example: + +``` +cmake --build build_debug --target test_opcodes && ./build_debug/test_opcodes +``` + +Release profile example: + +``` +cmake --build build_release --target test_opcodes && ./build_release/test_opcodes +``> + +If `fun_test` exists in your configuration: + +``` +cmake --build build_debug --target fun_test && ./build_debug/fun_test +``` + +You can also invoke CTest to run any tests registered with `add_test()`: + +``` +cmake --build build_debug --target test +ctest --test-dir build_debug -j +``` + +## Adding new tests + +- C/C++/VM-side tests: look for existing tests under `src` or `spec` and mirror the structure. Add a new source and register it in CMake with an executable or via `add_test()`. +- Fun-level examples as tests: minimal scripts under `examples/` can act as smoke tests and are runnable via `./play.fun`. Consider adding a new example for new features and have CI invoke a subset. + +Guidelines: +- Keep each test focused; prefer several small tests over one monolith. +- Avoid nondeterminism; set seeds where randomness is involved. +- Make tests independent of the working directory unless the behavior under test is precisely path resolution. + +## Debugging failing tests + +- Use `--trace` when running the interpreter to follow execution. +- Enable `--repl-on-error` to inspect state interactively on failure. +- Print intermediate values with `print()` and convert with `to_string()` when needed. + +See repl.md and internals.md for deeper debugging tips. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..9835e04 --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,91 @@ +# Troubleshooting Guide + +This page lists common issues when building and running Fun from a source checkout and how to fix them quickly. + +## Includes cannot be found + +Error example: + +``` +Include error: cannot read '' +``` + +Fix: +- When running from the repository without installing, set `FUN_LIB_DIR` to the local `./lib` directory so angle‑bracket includes resolve correctly. + +Linux/macOS/BSD: + +``` +export FUN_LIB_DIR="$(pwd)/lib" +./build_debug/fun examples/include_lib.fun +``` + +Windows (PowerShell): + +``` +$env:FUN_LIB_DIR = "$PWD/lib" +./build_release/fun.exe .\examples\include_lib.fun +``` + +If `FUN_LIB_DIR` is not set, the interpreter tries a compile‑time `DEFAULT_LIB_DIR`, and finally falls back to `./lib` relative to the current working directory. Be mindful of where you run the `fun` binary from. + +See includes.md for more details. + +## REPL does not start + +Symptoms: +- Running the executable just exits, or `--repl-on-error` is not recognized. + +Fix: +- Build with `-DFUN_WITH_REPL=ON` and rebuild the `fun` target. Then launch without arguments: + +``` +cmake -S . -B build_debug -DFUN_WITH_REPL=ON +cmake --build build_debug --target fun +FUN_LIB_DIR="$(pwd)/lib" ./build_debug/fun +``` + +See repl.md for usage tips and features. + +## Linker errors for optional libraries (JSON, PCRE2, CURL, SQLite, etc.) + +Symptoms: +- Build fails when enabling an optional feature. + +Fix: +- Ensure the development packages for the chosen library are installed (headers + libs). +- Toggle features individually with `-DFUN_WITH_JSON=ON`, `-DFUN_WITH_PCRE2=ON`, etc., and verify your system provides them. + +## Bytecode or opcode mismatch errors after refactors + +Symptoms: +- Crashes or incorrect behavior after editing src/vm or src/bytecode.h. + +Fix: +- Rebuild cleanly to ensure all amalgamated C units are recompiled. +- Verify opcode_names[] in src/vm.h matches enum ordering in src/bytecode.h. +- Re-run with `--trace` and (optionally) `--dump-bytecode` to inspect control flow. + +## Paths differ when running from IDE vs. shell + +Symptoms: +- Includes resolve in one environment but not the other; `./lib` fallback behaves differently. + +Fix: +- Always set `FUN_LIB_DIR` explicitly in the run configuration of your IDE and in your shell session. +- Confirm the working directory of the launch configuration; relative includes use `$PWD`. + +## Windows-specific quoting issues + +Symptoms: +- Setting environment variables has no effect; include paths remain unresolved. + +Fix: +- In CMD use: `set FUN_LIB_DIR=%CD%\lib && build-debug\fun.exe examples\include_lib.fun` +- In PowerShell use: `$env:FUN_LIB_DIR = "$PWD\lib"; .\build\fun.exe .\examples\include_lib.fun` + +## Getting help + +- Run the interpreter with `--help` to see supported flags. +- Explore docs/handbook.md and docs/repl.md. +- Check the examples under `examples/` and try `./play.fun` for an interactive tour. diff --git a/play.fun b/play.fun deleted file mode 100755 index 3801b78..0000000 --- a/play.fun +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/env fun - -/* - * Interactive demo runner for all examples in ./examples - * - Asks y/n before running each feature demo - * - Executes each example as a subprocess - */ - -#include - -#include -#include - -fun pick_fun_bin() - // Prefer an explicit FUN_BIN override; otherwise rely on PATH - b = env("FUN_BIN") - if b != "" - return b - return "fun" - -fun run_example(bin, path) - // Ensure examples can locate stdlib when run from repo root. - // We execute via the shell so env assignment + redirection works. - cmd = join(["sh -c '\nFUN_LIB_DIR=./lib ", bin, " ", path, " 2>&1\n'"], "") - print("-- output begin --") - code = system(cmd) - print("-- output end --") - print(join(["exit code: ", to_string(code)], "")) - return code - -fun main() - c = Console() - bin = pick_fun_bin() - - print("=== Fun language feature showcase (interactive) ===") - print(join(["Using interpreter: ", bin], "")) - print("Tip: set FUN_BIN=/path/to/fun to override. Stdlib is passed via FUN_LIB_DIR=./lib\n") - - // List of example scripts. Keep paths relative to repo root where this demo resides. - // If you add/remove examples, update this list. - files = [ - "examples/arrays.fun", - "examples/arrays_advanced.fun", - "examples/arrays_iter.fun", - "examples/boolean_decl.fun", - "examples/booleans.fun", - "examples/builtins_conversions.fun", - "examples/builtins_extended.fun", - "examples/builtins_maps_and_more.fun", - "examples/byte_for_demo.fun", - "examples/byte_overflow_try_catch.fun", - "examples/cast_demo.fun", - "examples/class_constructor.fun", - "examples/classes_demo.fun", - "examples/crypto/crc32_example.fun", - "examples/crypto/crc32c_example.fun", - "examples/crypto/md5_demo.fun", - "examples/crypto/sha1_demo.fun", - "examples/crypto/sha256_demo.fun", - "examples/crypto/sha256_str_demo.fun", - "examples/crypto/sha384_example.fun", - "examples/crypto/sha512_demo.fun", - "examples/crypto/sha512_str_demo.fun", - "examples/datetime_basic.fun", - "examples/datetime_extended.fun", - "examples/datetime_timer.fun", - "examples/echo_example.fun", - "examples/error/debug_reporting.fun", - "examples/error/exit_example.fun", - "examples/error/repl_on_error.fun", - "examples/expressions_test.fun", - "examples/extra/curl_download.fun", - "examples/extra/curl_get_json.fun", - "examples/extra/curl_post.fun", - "examples/extra/ini_class_demo.fun", - "examples/extra/ini_complex.fun", - "examples/extra/ini_demo.fun", - "examples/extra/ini_subsections.fun", - "examples/extra/json_showcase.fun", - "examples/extra/libsql_example.fun", - "examples/extra/pcre2_opcodes.fun", - "examples/extra/pcre2_showcase.fun", - "examples/extra/pcsc_example.fun", - "examples/extra/sqlite_example.fun", - "examples/extra/tk_hello.fun", - "examples/extra/xml_access_catalog.fun", - "examples/extra/xml_access_employees.fun", - "examples/extra/xml_access_ns.fun", - "examples/extra/xml_class_example.fun", - "examples/extra/xml_minimal.fun", - "examples/fail.fun", - "examples/file_io.fun", - "examples/file_print_for_file_line_by_line.fun", - "examples/floats.fun", - "examples/for_range_test.fun", - "examples/functions_test.fun", - "examples/have_fun.fun", - "examples/have_fun_function.fun", - "examples/if_else_test.fun", - "examples/include_lib.fun", - "examples/include_local.fun", - "examples/include_local_util.fun", - "examples/include_namespace.fun", - "examples/inheritance_demo.fun", - "examples/interactive/input_example.fun", - "examples/loops_break_continue.fun", - "examples/namespaced_mod.fun", - "examples/nested_loops.fun", - "examples/objects_basic.fun", - "examples/objects_more.fun", - "examples/os_env.fun", - "examples/process_example.fun", - "examples/regex_demo.fun", - "examples/regex_procedural.fun", - "examples/short_circuit_test.fun", - "examples/signed_ints.fun", - "examples/stdlib_showcase.fun", - "examples/strings_test.fun", - "examples/tcp_http_get.fun", - "examples/tcp_http_get_class.fun", - "examples/thread_class_example.fun", - "examples/threads_demo.fun", - "examples/try_catch_finally.fun", - "examples/try_catch_with_error.fun", - "examples/type_safety.fun", - "examples/type_safety_fails.fun", - "examples/types_integers.fun", - "examples/types_overview.fun", - "examples/typeof.fun", - "examples/typeof_features.fun", - "examples/uint_types.fun", - "examples/unix_socket_echo.fun", - "examples/while_test.fun" - ] - - failures = [] - - for f in files - q = join(["Run ", f, "?"], "") - if c.ask_yes_no(q) - print(join(["=== Running: ", f, " ==="], "")) - code = run_example(bin, f) - if code != 0 - failures.push(f) - print("") - else - print(join(["Skipped: ", f], "")) - - if len(failures) == 0 - print("All selected examples completed successfully.") - else - print("Some selected examples failed:") - for ff in failures - print(join([" - ", ff], "")) - -main() From 6ee78cc4fb0d770e9a674664a96568a6f7bf69dd Mon Sep 17 00:00:00 2001 From: hanez Date: Wed, 11 Feb 2026 17:55:04 +0100 Subject: [PATCH 24/39] Some more documentation fun. No code changes. (0.38.11) --- docs/examples.md | 6 +++--- docs/testing.md | 6 +++--- docs/troubleshooting.md | 10 +++++----- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/examples.md b/docs/examples.md index ab18e0e..358ef0f 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -6,20 +6,20 @@ All commands assume you are in the repository root. ## Prerequisites -- Build the interpreter (see handbook.md). You’ll have `build_debug/fun` or `build_release/fun` (paths may vary by your setup/IDE). +- Build the interpreter (see handbook.md). You’ll have `build/fun` (paths may vary by your setup/IDE). - Set FUN_LIB_DIR to the repo’s lib directory when running without installation so `#include <...>` can find the standard library. Example (Linux/macOS/BSD): ``` -FUN_LIB_DIR="$(pwd)/lib" ./build_debug/fun examples/include_lib.fun +FUN_LIB_DIR="$(pwd)/lib" ./build/fun examples/include_lib.fun ``` Windows (PowerShell): ``` $env:FUN_LIB_DIR = "$PWD/lib" -./build_release/fun.exe .\examples\include_lib.fun +./build/fun.exe .\examples\include_lib.fun ``` ## Interactive showcase: play.fun diff --git a/docs/testing.md b/docs/testing.md index 6176b70..410e18a 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -18,19 +18,19 @@ To list targets with CMake directly, consult your IDE or run the build system’ Debug profile example: ``` -cmake --build build_debug --target test_opcodes && ./build_debug/test_opcodes +cmake --build build_debug --target test_opcodes && ./build/test_opcodes ``` Release profile example: ``` -cmake --build build_release --target test_opcodes && ./build_release/test_opcodes +cmake --build build_release --target test_opcodes && ./build/test_opcodes ``> If `fun_test` exists in your configuration: ``` -cmake --build build_debug --target fun_test && ./build_debug/fun_test +cmake --build build_debug --target fun_test && ./build/fun_test ``` You can also invoke CTest to run any tests registered with `add_test()`: diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 9835e04..e8dfec0 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -17,14 +17,14 @@ Linux/macOS/BSD: ``` export FUN_LIB_DIR="$(pwd)/lib" -./build_debug/fun examples/include_lib.fun +./build/fun examples/include_lib.fun ``` Windows (PowerShell): ``` $env:FUN_LIB_DIR = "$PWD/lib" -./build_release/fun.exe .\examples\include_lib.fun +./build/fun.exe .\examples\include_lib.fun ``` If `FUN_LIB_DIR` is not set, the interpreter tries a compile‑time `DEFAULT_LIB_DIR`, and finally falls back to `./lib` relative to the current working directory. Be mindful of where you run the `fun` binary from. @@ -42,7 +42,7 @@ Fix: ``` cmake -S . -B build_debug -DFUN_WITH_REPL=ON cmake --build build_debug --target fun -FUN_LIB_DIR="$(pwd)/lib" ./build_debug/fun +FUN_LIB_DIR="$(pwd)/lib" ./build/fun ``` See repl.md for usage tips and features. @@ -81,11 +81,11 @@ Symptoms: - Setting environment variables has no effect; include paths remain unresolved. Fix: -- In CMD use: `set FUN_LIB_DIR=%CD%\lib && build-debug\fun.exe examples\include_lib.fun` +- In CMD use: `set FUN_LIB_DIR=%CD%\lib && build\fun.exe examples\include_lib.fun` - In PowerShell use: `$env:FUN_LIB_DIR = "$PWD\lib"; .\build\fun.exe .\examples\include_lib.fun` ## Getting help - Run the interpreter with `--help` to see supported flags. - Explore docs/handbook.md and docs/repl.md. -- Check the examples under `examples/` and try `./play.fun` for an interactive tour. +- Check the examples under `examples/` for an interactive tour. From c44eba681c0382c740d23f7fcaa75749dbf88cf3 Mon Sep 17 00:00:00 2001 From: hanez Date: Tue, 17 Feb 2026 14:34:57 +0100 Subject: [PATCH 25/39] Holiday is over, now I have fun again. No code changes. (0.38.11) --- docs/arrays.md | 197 +++++++++++++++++++++++++++++++++++++++++++++++ docs/maps.md | 203 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 400 insertions(+) create mode 100644 docs/arrays.md create mode 100644 docs/maps.md diff --git a/docs/arrays.md b/docs/arrays.md new file mode 100644 index 0000000..76c0306 --- /dev/null +++ b/docs/arrays.md @@ -0,0 +1,197 @@ +# Arrays in Fun + +This guide focuses on arrays: creation, indexing, mutation, iteration, slicing, and common gotchas. It complements the quick overview in types.md with a deeper, example‑driven treatment. + +## What is an array? + +- Ordered, zero‑indexed, mutable sequence of values. +- Can hold mixed types (numbers, strings, maps, arrays, …) in the same array. +- Bounds‑checked indexing; out‑of‑range access is a runtime error. + +## Creating arrays + +``` +// literals +a = [1, 2, 3] +b = ["alpha", "beta"] +empty = [] + +// nested +grid = [[1,2], [3,4]] + +print(typeof(a)) // "array" +print(len(a)) // 3 +``` + +Tip: Prefer square‑bracket literals for clarity and performance versus building via repeated push in a hot loop. + +## Indexing (0‑based) and assignment + +``` +a = [10, 20, 30] +print(a[0]) // 10 +print(a[2]) // 30 + +// update in place +a[1] = 42 +print(a) // [10, 42, 30] +``` + +Notes: +- Valid indices are 0..len(a)-1. Using an invalid index raises a runtime error. +- Assignment updates the existing array; references pointing to it observe the change. + +## Appending, popping, inserting, removing + +``` +a = [1] + +// append to end; returns new length +push(a, 7) // => 2, a is now [1, 7] + +// pop last element; returns the removed value +v = apop(a) // v = 7, a is now [1] + +// insert at index (shifts elements to the right) +a = [1, 2, 3] +insert(a, 1, 99) // a => [1, 99, 2, 3] + +// remove at index (shifts left) +remove(a, 2) // a => [1, 99, 3] +``` + +## Slicing and concatenation + +``` +a = [0,1,2,3,4] + +// slice(startInclusive, endExclusive) +head = slice(a, 0, 3) // [0,1,2] +mid = slice(a, 1, 4) // [1,2,3] + +// concat: join two arrays +b = ["x", "y"] +ab = concat(a, b) // [0,1,2,3,4,"x","y"] +``` + +Slicing returns a new array. The original is unchanged. + +## Iteration patterns + +``` +a = ["a", "b", "c"] + +// index‑based loop +for i = 0; i < len(a); i = i + 1 { + print(a[i]) +} + +// enumerate helper (if available in your stdlib setup) +#include as it +for pair in it.enumerate(a) { + idx = pair[0] + val = pair[1] + print(to_string(idx) + ":" + val) +} +``` + +## Copying vs. referencing + +Arrays are reference types. Assigning just copies the reference, not the contents: + +``` +orig = [1, 2] +alias = orig // points to the same array +alias[0] = 9 +print(orig) // [9, 2] + +// create a shallow copy via slice +copy = slice(orig, 0, len(orig)) +copy[1] = 7 +print(orig) // [9, 2] +print(copy) // [9, 7] +``` + +Shallow copies duplicate the top‑level array but not nested structures. + +## Equality + +``` +print([1,2] == [1,2]) // true +print([1,2] == [2,1]) // false +``` + +Array equality compares length and element‑wise equality recursively. + +## Common utilities + +Depending on your build/stdlib configuration, these helpers may be available: + +- len(a): number of elements +- push(a, v), apop(a) +- insert(a, idx, v), remove(a, idx) +- slice(a, start, end) +- concat(a, b) +- find(a, v): index or -1 +- contains(a, v): 1 or 0 + +Check your lib directory (e.g., lib/utils) for additional helpers. + +## Error handling and bounds + +``` +a = [0] +// a[1] is out of range → runtime error +``` + +Tips: +- Guard indices: if i < 0 or i >= len(a) { /* handle */ } +- Use remove/insert carefully inside loops; indices of following items change. + +## Interop with maps and strings + +``` +// arrays of maps +users = [ {"name":"Ada"}, {"name":"Lin"} ] +print(users[1]["name"]) // Lin + +// split/join patterns depend on your stdlib +#include as su // adjust if present in your tree +parts = su.split("a,b,c", ",") // ["a","b","c"] +csv = su.join(parts, ",") // "a,b,c" +``` + +## Performance tips + +- Preallocate by building from literals or chunked appends rather than one‑by‑one in very tight loops. +- Prefer index loops over repeated remove/insert in the middle of large arrays. +- Use slice to copy only when necessary; keep references for read‑only sharing. + +## Examples + +``` +// filter even numbers +src = [0,1,2,3,4,5] +dst = [] +for i = 0; i < len(src); i = i + 1 { + v = src[i] + if v % 2 == 0 { push(dst, v) } +} +print(dst) // [0,2,4] + +// flatten one level +nested = [[1,2], [3], [], [4,5]] +flat = [] +for i = 0; i < len(nested); i = i + 1 { + row = nested[i] + for j = 0; j < len(row); j = j + 1 { + push(flat, row[j]) + } +} +print(flat) // [1,2,3,4,5] +``` + +## See also + +- types.md — broader overview of core types with quick array examples. +- examples/ — many scripts operate on arrays; try play.fun to explore. diff --git a/docs/maps.md b/docs/maps.md new file mode 100644 index 0000000..316984d --- /dev/null +++ b/docs/maps.md @@ -0,0 +1,203 @@ +# Maps in Fun + +This guide focuses on maps: creation, reading/writing by key, checking key presence, iterating keys/values, nesting, and common gotchas. It complements the quick overview in types.md with a deeper, example‑driven treatment. + +## What is a map? + +- Associative container of key → value pairs. +- Keys are typically strings; values can be any type (numbers, strings, arrays, maps, …). +- Mutable: assigning with m["k"] = v updates the map in place. +- Accessing a missing key yields nil (not an error). Use guards or has(m, key). +- Maps are not ordered; rely on keys(m) if you need a concrete list of keys. + +## Creating maps + +``` +// literals +user = { "name": "Ada", "age": 37 } +empty = {} + +print(typeof(user)) // "map" +``` + +Nested structures are natural and common: + +``` +book = { + "title": "Fun Handbook", + "meta": { "pages": 120, "isbn": "123-456" }, + "tags": ["lang", "vm"] +} +print(book["meta"]["pages"]) // 120 +``` + +## Getting and setting by key + +``` +profile = { "name": "Lin" } + +// read existing key +print(profile["name"]) // Lin + +// read missing key → nil +print(profile["email"]) // nil + +// write / overwrite +profile["email"] = "lin@example.org" +profile["name"] = "Linus" +print(profile) // {"name":"Linus","email":"lin@example.org"} +``` + +Notes: +- Using a non‑string key is allowed only if your build/runtime supports it; most code uses string keys for portability. +- Missing keys produce nil. Compare against nil before converting or indexing: + +``` +v = profile["phone"] +if v == nil { print("no phone on file") } +``` + +## Checking key existence + +Use has(m, key) to check if a key is present (returns 1 or 0): + +``` +cfg = { "debug": 1 } +print(has(cfg, "debug")) // 1 +print(has(cfg, "port")) // 0 + +if has(cfg, "port") { print(cfg["port"]) } else { print("using default port") } +``` + +## Iterating maps + +Maps are not inherently ordered. To iterate, first obtain an array of keys or values. + +``` +user = { "name": "Ada", "age": 38 } + +// iterate known keys (explicit order you choose) +order = ["name", "age"] +for i = 0; i < len(order); i = i + 1 { + k = order[i] + print(k + " = " + to_string(user[k])) +} + +// discover keys from the map (order may depend on implementation) +ks = keys(user) // -> ["name", "age"] (example) +for i = 0; i < len(ks); i = i + 1 { + k = ks[i] + print(k + ": " + to_string(user[k])) +} + +// values only +vs = values(user) // -> ["Ada", 38] +for i = 0; i < len(vs); i = i + 1 { print(to_string(vs[i])) } +``` + +Tip: +- If you need deterministic output, either define the order array explicitly or sort the result of keys(user) using your available utilities before looping. + +## Copying vs. referencing + +Maps are reference types. Assigning copies the reference, not the contents: + +``` +orig = { "a": 1 } +alias = orig +alias["a"] = 9 +print(orig["a"]) // 9 + +// To make a shallow copy, rebuild from keys/values +src = { "x": 1, "y": 2 } +dst = {} +ks = keys(src) +for i = 0; i < len(ks); i = i + 1 { k = ks[i]; dst[k] = src[k] } + +dst["x"] = 7 +print(src["x"]) // 1 +print(dst["x"]) // 7 +``` + +Shallow copies duplicate only the top‑level mapping; nested arrays/maps inside are still shared unless you clone them manually. + +## Equality + +``` +print({"a":1,"b":2} == {"b":2,"a":1}) // true +print({"a":1} == {"a":2}) // false +``` + +Map equality compares sets of keys and their corresponding values for equality (order does not matter). + +## Common utilities + +Depending on your build/stdlib configuration, these helpers are commonly available: + +- has(m, key): 1 if present, 0 otherwise +- keys(m): array of keys +- values(m): array of values (parallel to keys(m) order) +- len(a) works on arrays; for maps, prefer keys(m) then len(keys(m)) if you need a count + +Check your lib or VM docs (e.g., src/vm/maps) and docs/types.md for availability and details. + +## Interop with arrays and strings + +``` +// maps inside arrays +users = [ {"name":"Ada"}, {"name":"Lin"} ] +for i = 0; i < len(users); i = i + 1 { + print(users[i]["name"]) // Ada, Lin +} + +// arrays inside maps +m = { "nums": [1,2,3] } +arr = m["nums"] +push(arr, 4) +print(m["nums"]) // [1,2,3,4] + +// JSON interop is typically via lib/io/json.fun (if enabled in your build) +#include as json // adjust to your tree and build flags +s = json.stringify({"ok":1}) // "{"ok":1}" +``` + +## Error handling and edge cases + +- Accessing a missing key returns nil. Guard before arithmetic or nested indexing. +- Mutating a map while iterating over keys you computed earlier is safe, but remember the keys array won’t update automatically; recompute if needed. +- Treat map iteration order as unspecified unless your build guarantees stability. For user‑facing output, specify/derive an order explicitly. + +## Performance tips + +- If you will access many keys, cache ks = keys(m) once and index that array in a loop rather than calling keys(m) repeatedly. +- Prefer direct writes (m["k"]=v) over repeatedly rebuilding maps in tight loops. +- When copying, copy only required keys instead of cloning the entire map if you only need a subset. + +## Examples + +``` +// merge defaults into config (without overwriting explicit keys) +defaults = { "host":"127.0.0.1", "port":8080, "debug":0 } +cfg = { "port": 9000 } + +ks = keys(defaults) +for i = 0; i < len(ks); i = i + 1 { + k = ks[i] + if !has(cfg, k) { cfg[k] = defaults[k] } +} +print(cfg) // {"port":9000,"host":"127.0.0.1","debug":0} + +// index users by id +rows = [ {"id":"u1","name":"Ada"}, {"id":"u2","name":"Lin"} ] +by_id = {} +for i = 0; i < len(rows); i = i + 1 { + r = rows[i] + by_id[r["id"]] = r +} +print(by_id["u2"]["name"]) // Lin +``` + +## See also + +- types.md — broader overview of core types with quick map examples. +- examples/ — there are example scripts involving maps; try play.fun to explore. From 16c36a6b8a619d26b6ba2acbaacb96a6920195db Mon Sep 17 00:00:00 2001 From: hanez Date: Tue, 17 Feb 2026 14:46:35 +0100 Subject: [PATCH 26/39] Holiday is over, now I have fun again. No code changes. (0.38.11) --- docs/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/README.md b/docs/README.md index 3f027a9..97ca9d0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,6 +6,8 @@ This file serves as an index of the documents in this directory. Links are relat - [handbook.md](./handbook.md) — Comprehensive handbook for the Fun language and VM: install/build, configuration flags, usage, and full feature overview. - [types.md](./types.md) — Core types (numbers, strings, arrays, maps, nil/bool), common operations, patterns, and interop notes. +- [arrays.md](./arrays.md) — Working with arrays: creation, indexing/slicing, iteration patterns, helpers, and idioms. +- [maps.md](./maps.md) — Working with maps: construction, lookup/update, merging, iteration, and common patterns. - [includes.md](./includes.md) — Using local vs. system includes, FUN_LIB_DIR, DEFAULT_LIB_DIR, and namespaced includes with `as`. - [repl.md](./repl.md) — REPL guide: how to build/launch, editing and history, completions, REPL‑on‑error, and tips. - [opcodes.md](./opcodes.md) — VM opcodes overview grouped by domain with brief behavior/stack notes. From eaf5f88dc05e9efc314922f679753ac5751e4e0c Mon Sep 17 00:00:00 2001 From: hanez Date: Tue, 17 Feb 2026 14:59:39 +0100 Subject: [PATCH 27/39] Holiday is over, now I have fun again. No code changes. (0.38.11) --- docs/README.md | 2 + docs/numbers.md | 162 ++++++++++++++++++++++++++++++++++++++++++++++++ docs/strings.md | 99 +++++++++++++++++++++++++++++ docs/types.md | 7 +++ 4 files changed, 270 insertions(+) create mode 100644 docs/numbers.md create mode 100644 docs/strings.md diff --git a/docs/README.md b/docs/README.md index 97ca9d0..b9abdd8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,6 +6,8 @@ This file serves as an index of the documents in this directory. Links are relat - [handbook.md](./handbook.md) — Comprehensive handbook for the Fun language and VM: install/build, configuration flags, usage, and full feature overview. - [types.md](./types.md) — Core types (numbers, strings, arrays, maps, nil/bool), common operations, patterns, and interop notes. +- [numbers.md](./numbers.md) — Working with integers and floats: arithmetic, conversions, clamping, bitwise ops, and patterns. +- [strings.md](./strings.md) — Working with strings: literals/escaping, concatenation, substr/find, split, and conversions. - [arrays.md](./arrays.md) — Working with arrays: creation, indexing/slicing, iteration patterns, helpers, and idioms. - [maps.md](./maps.md) — Working with maps: construction, lookup/update, merging, iteration, and common patterns. - [includes.md](./includes.md) — Using local vs. system includes, FUN_LIB_DIR, DEFAULT_LIB_DIR, and namespaced includes with `as`. diff --git a/docs/numbers.md b/docs/numbers.md new file mode 100644 index 0000000..a3092ea --- /dev/null +++ b/docs/numbers.md @@ -0,0 +1,162 @@ +# Working with numbers and floats in Fun + +This guide covers the numeric types in Fun, with a focus on the integer "number" type and the 64‑bit floating point "float" type. You’ll find creation, arithmetic, conversion, clamping, bitwise operations, and common patterns. + +## TL;DR + +- number = signed integer; float = 64‑bit floating point. +- Use +, -, *, / for arithmetic. If you need fractional results, make at least one operand a float. +- Modulo: a % b. Integer division with / may discard the fractional part; cast to float to preserve it. +- Convert/parse: to_number("123"), to_string(x), cast(x, "float"), cast(x, "number"). +- Clamp to widths when interfacing with external code: uclamp(n, bits), sclamp(n, bits). +- Bitwise (numbers only): &, |, ^, ~, <<, >>. + +## Numeric types at a glance + +- number: signed integer (implementation‑defined width; use uclamp/sclamp for fixed‑width interop) +- float: IEEE‑754 double precision (64‑bit) + +``` +an = 42 // number +af = 3.14159 // float +print(typeof(an)) // "number" +print(typeof(af)) // "float" +``` + +## Literals + +- Integer (number): 0, 1, -7, 120 +- Floating point (float): 0.0, 1.5, -2.75, 1e3, -4.2e-1 + +``` +x = 10 +y = 2.5 +z = -3 +``` + +## Arithmetic + +Basic arithmetic works as you’d expect: + +``` +a = 7 +b = 2 +print(a + b) // 9 +print(a - b) // 5 +print(a * b) // 14 +print(a % b) // 1 (modulo) +``` + +Division and result type: + +``` +// If you need a fractional result, ensure a float is involved +print(7 / 2) // implementation may yield 3 or 3.5 depending on numeric rules +print(cast(7, "float") / 2) // 3.5 (recommended when you need fractions) +print(7 / 2.0) // 3.5 +``` + +Mixing numbers and floats promotes the operation to float semantics: + +``` +print(2 + 0.5) // 2.5 +``` + +## Comparisons + +``` +print(3 < 5) // 1 (true) +print(3 == 3) // 1 +print(3 != 4) // 1 + +// Be explicit when comparing ints vs floats if types matter +print(1 == 1.0) // may be true, but types differ +print(cast(1.0, "number") == 1) // 1 (true) with explicit cast +``` + +## Conversions and parsing + +``` +n = to_number("123") // 123 (number) +f = cast(n, "float") // 123.0 (float) +n2 = cast(3.9, "number") // 3 (truncation semantics) +print(to_string(f)) // "123" +``` + +If parsing fails (e.g., to_number("abc")), expect a runtime error; guard accordingly. + +## Clamping to fixed widths + +When interoperating with bytecode, C APIs, or binary formats, clamp integers to a specific bit width. + +``` +// Unsigned clamp to N bits +u8 = uclamp(300, 8) // 44 +u16 = uclamp(70000, 16) + +// Signed clamp to N bits +s8 = sclamp(-130, 8) // wraps into signed 8‑bit range +``` + +Choose the bits according to the target field (8, 16, 32, 64). See your interop API docs for exact ranges. + +## Bitwise operations (numbers) + +Bitwise operators apply to the integer number type. + +``` +a = 0b0110 // if binary literals aren’t supported in your setup, use decimals: a = 6 +b = 0b0011 // or b = 3 + +print(a & b) // 0b0010 -> 2 +print(a | b) // 0b0111 -> 7 +print(a ^ b) // 0b0101 -> 5 +print(~a) // bitwise NOT (two’s complement rules) +print(a << 1) // 12 +print(a >> 1) // 3 +``` + +Note: Bitwise ops are defined for numbers, not floats. Cast floats to numbers first when needed. + +## Common patterns + +Ensuring float math to avoid unintended truncation: + +``` +avg = cast(sum, "float") / cast(count, "float") +``` + +Safe division with guard against zero: + +``` +num = 10 +den = 0 +if den == 0 { + print("division by zero") +} else { + print(num / den) +} +``` + +Parsing user input with fallback: + +``` +raw = "not-a-number" +val = 0 +// simplistic guard pattern; adapt to your error handling style +if find(raw, "0") >= 0 || find(raw, "1") >= 0 { // crude pre-check + val = to_number(raw) +} +``` + +## Gotchas + +- Integer division vs float division: promote to float when you need fractional results. +- Overflow/underflow: clamp explicitly when targeting fixed‑width fields; otherwise values follow the VM’s integer semantics. +- Bitwise with negatives uses two’s complement; ~x equals -(x+1). + +## See also + +- Core overview: [types.md](./types.md) +- Math helpers and advanced ops: check [math/opcodes](./opcodes.md) and the vm/math sources for available functions. +- Strings: [strings.md](./strings.md) diff --git a/docs/strings.md b/docs/strings.md new file mode 100644 index 0000000..e5c198b --- /dev/null +++ b/docs/strings.md @@ -0,0 +1,99 @@ +# Working with strings in Fun + +This guide covers string literals, common operations (length, concatenation, substring, search, split), and interop patterns. Strings in Fun are immutable sequences of bytes/text. + +## TL;DR + +- Create with quotes: s = "hello". Escape with \n, \t, \", \\. +- Concatenate with +. Convert non-strings with to_string(x). +- Length: len(s). Substring: substr(s, start, length). +- Find index: find(s, needle) → 0-based index or -1 if not found. +- Split CSV: split("a,b,c", ",") → ["a","b","c"]. + +## Literals and escaping + +``` +s1 = "hello" +s2 = "line1\nline2" // newline +s3 = "quote: \" and backslash: \\" // escaped quote and backslash + +print(s1) // hello +``` + +Notes: +- Strings are immutable; operations return new strings rather than modifying in place. +- Use to_string(x) when concatenating non-string values. + +## Basic operations + +Length and concatenation: + +``` +name = "Ada" +greet = "Hello, " + name + "!" // "Hello, Ada!" +print(len(greet)) // 12 +``` + +Substring (start, length) and search: + +``` +s = "hello, world" +print(substr(s, 7, 5)) // world +idx = find(s, ",") // 5, or -1 if not found +if idx >= 0 { print("comma at index " + to_string(idx)) } +``` + +Splitting into arrays: + +``` +parts = split("a,b,c", ",") // ["a","b","c"] +for i = 0; i < len(parts); i = i + 1 { + print(parts[i]) +} +``` + +## Conversions and formatting + +``` +n = 42 +pi = 3.14 +msg = "n=" + to_string(n) + ", pi=" + to_string(pi) +print(msg) + +// parsing (may error if the string is not numeric) +n2 = to_number("123") // 123 +``` + +If you need a specific type, you can use cast for advanced cases, e.g. cast("123", "number"). + +## Common patterns + +- Guard on find results before slicing: + +``` +email = "user@example.org" +at = find(email, "@") +if at >= 0 { + user = substr(email, 0, at) + host = substr(email, at + 1, len(email) - at - 1) + print(user + " on " + host) +} +``` + +- Building paths or messages: + +``` +base = "/tmp" +file = "log.txt" +path = base + "/" + file +``` + +## Gotchas + +- Strings are immutable: repeated concatenation in big loops can be costly; consider collecting pieces in an array and joining at the end if you have a helper for that in your setup. +- len(s) counts bytes/code units; be mindful when working with multi-byte encodings. + +## See also + +- Core overview: [types.md](./types.md) +- Arrays guide (useful when splitting/collecting text): [arrays.md](./arrays.md) diff --git a/docs/types.md b/docs/types.md index a4ffc66..759c820 100644 --- a/docs/types.md +++ b/docs/types.md @@ -2,6 +2,13 @@ This guide shows how to create and use the most common Fun datatypes with practical examples. It focuses on arrays and maps, and also recaps numbers, floats, strings, booleans and nil so examples are self‑contained. +See also: + +- [arrays.md](./arrays.md) — Deeper dive into array creation, indexing/slicing, iteration, and helpers. +- [strings.md](./strings.md) — Practical guide to string literals, concatenation, substr/find, split, and conversions. +- [maps.md](./maps.md) — Detailed guide to map construction, lookup/update, merging, and patterns. +- [numbers.md](./numbers.md) — Numbers vs floats, arithmetic, conversions, clamping, bitwise ops, and common patterns. + ## Quick overview - number: signed integer (use uclamp/sclamp for width handling) From bd2d619cb955143799d3d0700329b9788904543f Mon Sep 17 00:00:00 2001 From: hanez Date: Wed, 18 Feb 2026 16:12:41 +0100 Subject: [PATCH 28/39] Holiday is over, now I have fun again. No code changes. (0.38.11) --- README.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index bd30bf4..8a540ba 100644 --- a/README.md +++ b/README.md @@ -105,17 +105,22 @@ There are some libs written in Fun available in the [./lib/](https://git.xw3.org ## Documentation -This is actually a work in progress... +Looking for docs? Start here: -Current documentation is only found in the [Fun Handbook](https://git.xw3.org/fun/fun/src/branch/main/docs/handbook.md) and the [specification](https://git.xw3.org/fun/fun/src/branch/main/spec/v0.3.md). +- Local documentation index: [docs/README.md](./docs/README.md) + - Handbook: [docs/handbook.md](./docs/handbook.md) + - Types overview: [docs/types.md](./docs/types.md) + - REPL guide: [docs/repl.md](./docs/repl.md) + - Testing: [docs/testing.md](./docs/testing.md) + - Troubleshooting: [docs/troubleshooting.md](./docs/troubleshooting.md) -In the [./examples/](https://git.xw3.org/fun/fun/src/branch/main/examples) directory should be an example of most Fun features. +Additional references: -Fun internals are found directly in the [./src/](https://git.xw3.org/fun/fun/src/branch/main/src) diretory. Fun [Opcodes](https://en.wikipedia.org/wiki/Opcode) are found in [./src/vm/](https://git.xw3.org/fun/fun/src/branch/main/src/vm). +- Specification: [spec/v0.3.md](./spec/v0.3.md) (work in progress) +- Examples demonstrating most features: [examples/](./examples/) +- Internals and VM opcodes live in [src/](./src/) (see [src/vm/](./src/vm) for opcode implementations) -Since things are actually changing sometimes, I will not write the documentation for this as of now. - -Complete API documentation will follow. +Note: The project is evolving; some documents may lag behind. The docs index in `./docs/README.md` is the most up‑to‑date entry point. ## Author From f896e1d3bfdf2e05a61d57fd024946e68e5ff9ac Mon Sep 17 00:00:00 2001 From: hanez Date: Wed, 18 Feb 2026 17:39:10 +0100 Subject: [PATCH 29/39] Holiday is over, now I have fun again. No code changes. (0.38.11) --- docs/README.md | 16 +++++++++++++ docs/bytecode-format.md | 29 ++++++++++++++++++++++++ docs/cli.md | 38 +++++++++++++++++++++++++++++++ docs/contributing.md | 40 +++++++++++++++++++++++++++++++++ docs/embedding.md | 29 ++++++++++++++++++++++++ docs/errors-and-diagnostics.md | 21 +++++++++++++++++ docs/faq.md | 22 ++++++++++++++++++ docs/performance.md | 21 +++++++++++++++++ docs/roadmap.md | 21 +++++++++++++++++ docs/security-and-sandboxing.md | 17 ++++++++++++++ docs/stdlib.md | 26 +++++++++++++++++++++ docs/style-guide.md | 25 +++++++++++++++++++++ docs/writing-tests.md | 24 ++++++++++++++++++++ 13 files changed, 329 insertions(+) create mode 100644 docs/bytecode-format.md create mode 100644 docs/cli.md create mode 100644 docs/contributing.md create mode 100644 docs/embedding.md create mode 100644 docs/errors-and-diagnostics.md create mode 100644 docs/faq.md create mode 100644 docs/performance.md create mode 100644 docs/roadmap.md create mode 100644 docs/security-and-sandboxing.md create mode 100644 docs/stdlib.md create mode 100644 docs/style-guide.md create mode 100644 docs/writing-tests.md diff --git a/docs/README.md b/docs/README.md index b9abdd8..eb01ea2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,6 +19,22 @@ This file serves as an index of the documents in this directory. Links are relat - [testing.md](./testing.md) — How to build and run tests/targets with CMake/CTest, and where to add new tests. - [troubleshooting.md](./troubleshooting.md) — Common issues and quick fixes for build, includes, and REPL usage. +## New and supplemental guides + +- [build.md](./build.md) — How to build Fun with CMake, available targets, and build options (FUN_DEBUG, FUN_USE_MUSL, FUN_WITH_CPP, FUN_WITH_RUST). +- [cli.md](./cli.md) — Command‑line usage of the `fun` executable: synopsis, options, exit codes, includes and library paths. +- [contributing.md](./contributing.md) — How to contribute: project structure, coding style, running tests, and PR guidelines. +- [style-guide.md](./style-guide.md) — Coding conventions for C and Fun (indentation, naming, idioms). +- [stdlib.md](./stdlib.md) — Overview of the standard library modules under ./lib with one‑line summaries. +- [embedding.md](./embedding.md) — Embedding the VM from C/Rust, lifecycle, and host integration tips. +- [errors-and-diagnostics.md](./errors-and-diagnostics.md) — Understanding parser/runtime errors and enabling diagnostics. +- [performance.md](./performance.md) — Build/runtime tuning tips and patterns for better performance. +- [security-and-sandboxing.md](./security-and-sandboxing.md) — Trust boundaries, I/O expectations, and capability restrictions. +- [faq.md](./faq.md) — Frequently asked questions and quick answers. +- [writing-tests.md](./writing-tests.md) — How to author new tests for Fun and opcode components. +- [bytecode-format.md](./bytecode-format.md) — Reference for the bytecode format (split out from internals for convenience). +- [roadmap.md](./roadmap.md) — High‑level direction, planned features, and pointers to issues. + ## Tips - When building from the repo without installing, set `FUN_LIB_DIR` to the local `./lib` directory so examples and the REPL can locate the stdlib. diff --git a/docs/bytecode-format.md b/docs/bytecode-format.md new file mode 100644 index 0000000..6d58d76 --- /dev/null +++ b/docs/bytecode-format.md @@ -0,0 +1,29 @@ +# Bytecode Format (Overview) + +This document summarizes the Fun bytecode format. For deep VM details, see `docs/internals.md`. + +## Goals +- Compact representation for fast loading and dispatch +- Stable header with room for versioning + +## File layout (typical) +1. Header + - Magic number / signature + - Format version + - Flags (endianness, feature bits) + - Offsets to sections +2. Constants table + - Literals: numbers, strings, compound constants +3. Code section + - Functions/procedures with instruction streams + - Line/column mapping (optional for debugging) +4. Auxiliary tables + - Imports/exports, names, debug info (optional) + +## Instructions +- Fixed-size or small-variant opcodes grouped by domain (math, logic, stack, call, control flow, etc.). +- Operands encoded inline following the opcode (width varies by instruction). + +## Versioning and compatibility +- The header’s version field allows the VM to refuse or translate older/newer formats. +- Keep additions backward-compatible when possible by appending sections or flags. diff --git a/docs/cli.md b/docs/cli.md new file mode 100644 index 0000000..ff036fa --- /dev/null +++ b/docs/cli.md @@ -0,0 +1,38 @@ +# Fun CLI + +Reference for the `fun` command-line interface. + +## Synopsis +``` +fun [options] [-- args...] +``` + +If no script is supplied and interactive mode is available, `fun` starts a REPL (see `docs/repl.md`). + +## Common options +- `-i`, `--repl` — start an interactive REPL +- `-v`, `--version` — print version and exit +- `-h`, `--help` — show help and exit + +Options may vary between versions; run `fun --help` to see what your build supports. + +## Exit codes +- `0` — success +- non-zero — error during parse, compile, or runtime + +## Includes and library paths +- `FUN_LIB_DIR` — environment variable that points to the stdlib location; when running from the repo, set this to `./lib`. +- `DEFAULT_LIB_DIR` — compiled-in fallback path determined at build/install time. + +See also: `docs/includes.md` for namespaced includes and search order. + +## Examples +Run a script: +``` +FUN_LIB_DIR=./lib ./build_debug/fun examples/hello.fun +``` + +Start the REPL: +``` +./build_debug/fun -i +``` diff --git a/docs/contributing.md b/docs/contributing.md new file mode 100644 index 0000000..806c833 --- /dev/null +++ b/docs/contributing.md @@ -0,0 +1,40 @@ +# Contributing to Fun + +Thanks for your interest in contributing! This guide covers the basics to get you productive quickly. + +## Getting started +- Clone the repo and build (see `docs/build.md`). +- Run tests locally (see `docs/testing.md`). +- Explore examples (see `docs/examples.md`). + +## Project structure +- `src/` — C core, VM, and opcode implementations (`src/vm/*`). +- `lib/` — Standard library written in Fun. +- `examples/` — Example programs and showcases. +- `docs/` — Documentation. +- `spec/` — Language specification drafts. + +## Code style +- C: C99, two-space indent, no tabs. Keep functions short and focused. +- Fun: two-space indent, snake_case for functions, PascalCase for classes/constructors. +- Prefer clear names over abbreviations. See `docs/style-guide.md`. + +## Development workflow +1. Create a small, focused branch. +2. Add/adjust tests for behavior changes (see `docs/writing-tests.md`). +3. Update docs if user-visible behavior changes. +4. Submit a PR with a clear description and rationale. + +## Commit/PR guidelines +- Keep commits atomic; include test updates with the change. +- Reference related issues. +- Include benchmarks only when meaningful and reproducible. + +## Reporting bugs +Please include: +- Reproducer script (minimal), expected vs. actual behavior +- Build options and platform +- `fun --version` output + +## Code of Conduct +Be respectful and inclusive. See `CODE_OF_CONDUCT.md` in the repository root. diff --git a/docs/embedding.md b/docs/embedding.md new file mode 100644 index 0000000..f603250 --- /dev/null +++ b/docs/embedding.md @@ -0,0 +1,29 @@ +# Embedding Fun + +This guide outlines how to embed the Fun VM in a host application and extend it from C/Rust. + +## Overview +- The VM is implemented in C (see `src/vm/`). +- Optional Rust-based opcodes can be enabled via `FUN_WITH_RUST` (see `docs/rust.md`). + +## Embedding from C +While the exact API surface may evolve, a typical embedding flow looks like: +1. Initialize the VM/runtime and allocate a context. +2. Load/compile Fun source or bytecode. +3. Push arguments or set globals as needed. +4. Execute entry function or script body. +5. Retrieve results and clean up. + +See `src/vm/core` and related headers for public entry points and value types. + +### Hosting considerations +- Threading: share VM state cautiously or create one VM per thread. +- Memory: clarify ownership of strings/buffers crossing the boundary. +- Errors: propagate parse/runtime errors back to the host with useful messages. + +## Extending with Rust +When `FUN_WITH_RUST=ON`, a Rust static library from `src/rust/` is built and linked. You can: +- Implement new opcodes/functions in Rust. +- Expose a C ABI for the VM to call into. + +See `docs/rust.md` for details and example code. diff --git a/docs/errors-and-diagnostics.md b/docs/errors-and-diagnostics.md new file mode 100644 index 0000000..f2b5757 --- /dev/null +++ b/docs/errors-and-diagnostics.md @@ -0,0 +1,21 @@ +# Errors and Diagnostics + +This guide helps you understand common error messages and how to collect useful diagnostics. + +## Common error classes +- Parse errors: syntax/indentation problems detected before execution. +- Name/lookup errors: missing variables, functions, or modules. +- Runtime errors: type mismatches, out-of-range access, invalid operations. + +## Enabling diagnostics +- Build with `-DFUN_DEBUG=ON` to enable additional assertions and debug messages (see `docs/build.md`). +- Run with smaller, focused scripts to isolate issues. + +## Getting useful reports +- Capture the minimal script that reproduces the issue. +- Note your build options and platform. +- Record the full error output from the CLI (`fun`), including line/column if present. + +## Tips +- Use prints or logging sparingly to narrow down failing code. +- Start from a passing simple case and add complexity until it breaks. diff --git a/docs/faq.md b/docs/faq.md new file mode 100644 index 0000000..82947b4 --- /dev/null +++ b/docs/faq.md @@ -0,0 +1,22 @@ +# FAQ + +Answers to common questions. + +## I built Fun but includes aren’t found +Set `FUN_LIB_DIR` to the repository’s `./lib` directory when running without installation: +``` +FUN_LIB_DIR=./lib ./build_debug/fun examples/hello.fun +``` +See `docs/includes.md`. + +## How do I start the REPL? +Run `fun -i` (or run `fun` without a script, depending on version). See `docs/repl.md`. + +## Which build target should I use? +Use the aggregate `build` target to build `fun`, `fun_test`, and `test_opcodes`. See `docs/build.md`. + +## Where are the standard libraries? +Under `./lib/`. See `docs/stdlib.md` for an overview. + +## Where can I find internals and opcodes? +Browse `src/vm/` and `docs/internals.md` / `docs/opcodes.md`. diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 0000000..ed926cc --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,21 @@ +# Performance Guide + +Tips for getting good performance from Fun programs and builds. + +## Build configuration +- Use `-DCMAKE_BUILD_TYPE=Release` for production binaries. +- Consider `FUN_DEBUG=OFF` to remove extra checks in hot paths. +- `FUN_USE_MUSL=ON` can help with static/portable builds; measure performance for your use case. + +## Language-level tips +- Prefer pre-sized arrays/maps when possible to reduce reallocations. +- Avoid unnecessary string concatenations in loops; accumulate in arrays and `join`. +- Push work to native ops where available (e.g., regex, JSON, math helpers). + +## Algorithmic choices +- Choose appropriate data structures (arrays for ordered scans, maps for key lookups). +- Cache repeated computations or lookups when safe. + +## Measuring +- Create small, representative benchmarks. +- Compare Debug vs. Release to ensure changes are meaningful. diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..4792b8f --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,21 @@ +# Roadmap + +This page outlines high-level areas of focus and points to places where you can help. + +## Themes +- Developer experience: docs, examples, REPL polish +- Optional extensions: stabilize and document supported integrations +- Performance: steady improvements in hot paths and data structures +- Safety: clearer error messages, diagnostics, and sandboxing guidance + +## Near-term +- Expand CLI reference and examples (`docs/cli.md`) +- Improve testing docs and coverage (`docs/writing-tests.md`) +- Fill gaps in stdlib documentation (`docs/stdlib.md`) + +## Medium-term +- Bytecode/reference updates as internals evolve (`docs/bytecode-format.md`, `docs/internals.md`) +- Embedding guides and host API stability (`docs/embedding.md`, `docs/rust.md`) + +## Contributing +See `docs/contributing.md` for how to propose and implement items. Track concrete tasks via repository issues and PRs. diff --git a/docs/security-and-sandboxing.md b/docs/security-and-sandboxing.md new file mode 100644 index 0000000..9bdf970 --- /dev/null +++ b/docs/security-and-sandboxing.md @@ -0,0 +1,17 @@ +# Security and Sandboxing + +Understand the trust boundaries and how to run Fun code safely. + +## Trust model +- By default, Fun code can access functionality exposed by the stdlib and any enabled extensions. +- File and network access depend on available modules and host configuration. + +## Running untrusted code +- Prefer running in a container/VM with restricted filesystem and network. +- Limit available stdlib/modules by controlling `FUN_LIB_DIR` contents. +- Use OS-level sandboxing (seccomp, AppArmor, SELinux, chroot) where applicable. + +## Best practices +- Avoid running as root. +- Validate and sanitize inputs at module boundaries. +- Keep your build minimal; disable unneeded extensions at compile time. diff --git a/docs/stdlib.md b/docs/stdlib.md new file mode 100644 index 0000000..a075823 --- /dev/null +++ b/docs/stdlib.md @@ -0,0 +1,26 @@ +# Standard Library Overview + +This page provides a quick orientation to the standard library located under `./lib/`. + +The stdlib is written in Fun and organized by domain. Below are top-level modules and what they generally cover. Refer to the source for full APIs and examples. + +## Module index (selected) +- `crypt/` — cryptographic helpers (hashing, encoding helpers). See also `lib/crypt`. +- `encoding/` — text/binary encodings and conversions. +- `io/` — file and stream utilities. +- `net/` — basic networking helpers. +- `regex/` — regular expression utilities (PCRE2 when available). +- `ui/` — UI helpers (e.g., Tk if enabled at build time). +- `utils/` — small reusable helpers and utilities. + +Note: Availability of some modules can depend on optional extensions selected at build time (see `docs/build.md`). + +## Using modules +```fun +include "utils/strings.fun" as strings + +let s = strings.trim(" hello ") +print(s) +``` + +For search paths and namespacing details, see `docs/includes.md` and `docs/cli.md` (FUN_LIB_DIR and DEFAULT_LIB_DIR). diff --git a/docs/style-guide.md b/docs/style-guide.md new file mode 100644 index 0000000..5c97cc9 --- /dev/null +++ b/docs/style-guide.md @@ -0,0 +1,25 @@ +# Fun Style Guide + +Conventions for writing C and Fun code in this repository. + +## General principles +- Two-space indentation. No tabs. +- Keep lines reasonably short (~100 cols). Wrap thoughtfully. +- Prefer explicit over implicit; favor clarity. + +## C (C99) +- Indentation: two spaces, K&R-ish braces. +- Naming: `snake_case` for functions and variables; `CAPS_SNAKE` for macros. +- Error handling: return error codes or booleans; avoid hidden globals. +- Headers: minimize includes in headers; forward-declare where practical. +- Memory: clearly document ownership; free what you allocate. + +## Fun language +- Indentation: two spaces. +- Naming: `snake_case` for functions/variables; `PascalCase` for classes/constructors. +- Modules: one primary concept per file; export a minimal, cohesive API. +- Idioms: prefer arrays and maps over ad-hoc structures; keep functions small. + +## Formatting and tools +- No auto-formatters required; follow these simple rules. +- Keep diffs small and focused; avoid reformat-only commits. diff --git a/docs/writing-tests.md b/docs/writing-tests.md new file mode 100644 index 0000000..a371aed --- /dev/null +++ b/docs/writing-tests.md @@ -0,0 +1,24 @@ +# Writing Tests + +How to author tests for Fun and its opcode implementations. + +## Test kinds +- VM/opcode tests: exercise bytecode operations and VM behavior (target: `test_opcodes`). +- Language/runtime tests: exercise user-visible features and stdlib behavior (target: `fun_test`). + +See `docs/testing.md` for how to build and run these targets with CTest. + +## Adding new tests +The exact layout may evolve; generally: +- Add new test sources alongside existing ones used by `fun_test`. +- For opcode-focused tests, add cases where `test_opcodes` discovers them. + +Aim for: +- Small, isolated test cases with clear assertions +- One behavior per test; descriptive names +- Minimal fixtures and setup + +## Guidelines +- Prefer black-box testing via public APIs. +- When adding features, include both positive and negative cases. +- Keep tests deterministic; avoid non-deterministic timers or random sources unless seeded. From 15082bdc3ed26a03621556ef9aabf3a1beb7b774 Mon Sep 17 00:00:00 2001 From: hanez Date: Wed, 18 Feb 2026 18:11:21 +0100 Subject: [PATCH 30/39] Holiday is over, now I have fun again. No code changes. (0.38.11) --- docs/README.md | 54 +++++++++++++++++----------------- docs/bytecode-format.md | 4 +-- docs/cli.md | 18 ++++++------ docs/contributing.md | 22 +++++++------- docs/embedding.md | 10 +++---- docs/errors-and-diagnostics.md | 2 +- docs/faq.md | 14 ++++----- docs/roadmap.md | 12 ++++---- docs/stdlib.md | 20 ++++++------- 9 files changed, 78 insertions(+), 78 deletions(-) diff --git a/docs/README.md b/docs/README.md index eb01ea2..75e488f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,36 +4,36 @@ This file serves as an index of the documents in this directory. Links are relat ## Overview -- [handbook.md](./handbook.md) — Comprehensive handbook for the Fun language and VM: install/build, configuration flags, usage, and full feature overview. -- [types.md](./types.md) — Core types (numbers, strings, arrays, maps, nil/bool), common operations, patterns, and interop notes. -- [numbers.md](./numbers.md) — Working with integers and floats: arithmetic, conversions, clamping, bitwise ops, and patterns. -- [strings.md](./strings.md) — Working with strings: literals/escaping, concatenation, substr/find, split, and conversions. -- [arrays.md](./arrays.md) — Working with arrays: creation, indexing/slicing, iteration patterns, helpers, and idioms. -- [maps.md](./maps.md) — Working with maps: construction, lookup/update, merging, iteration, and common patterns. -- [includes.md](./includes.md) — Using local vs. system includes, FUN_LIB_DIR, DEFAULT_LIB_DIR, and namespaced includes with `as`. -- [repl.md](./repl.md) — REPL guide: how to build/launch, editing and history, completions, REPL‑on‑error, and tips. -- [opcodes.md](./opcodes.md) — VM opcodes overview grouped by domain with brief behavior/stack notes. -- [internals.md](./internals.md) — Implementation details: bytecode format, VM architecture, stacks/frames, parser, and dispatch. -- [rust.md](./rust.md) — Writing Rust‑backed opcodes and wiring them into the C VM; build/setup notes. -- [examples.md](./examples.md) — How to run the examples and the interactive showcase script, with environment tips. -- [testing.md](./testing.md) — How to build and run tests/targets with CMake/CTest, and where to add new tests. -- [troubleshooting.md](./troubleshooting.md) — Common issues and quick fixes for build, includes, and REPL usage. +- [handbook.md](./handbook.md) - Comprehensive handbook for the Fun language and VM: install/build, configuration flags, usage, and full feature overview. +- [types.md](./types.md) - Core types (numbers, strings, arrays, maps, nil/bool), common operations, patterns, and interop notes. +- [numbers.md](./numbers.md) - Working with integers and floats: arithmetic, conversions, clamping, bitwise ops, and patterns. +- [strings.md](./strings.md) - Working with strings: literals/escaping, concatenation, substr/find, split, and conversions. +- [arrays.md](./arrays.md) - Working with arrays: creation, indexing/slicing, iteration patterns, helpers, and idioms. +- [maps.md](./maps.md) - Working with maps: construction, lookup/update, merging, iteration, and common patterns. +- [includes.md](./includes.md) - Using local vs. system includes, FUN_LIB_DIR, DEFAULT_LIB_DIR, and namespaced includes with `as`. +- [repl.md](./repl.md) - REPL guide: how to build/launch, editing and history, completions, REPL-on-error, and tips. +- [opcodes.md](./opcodes.md) - VM opcodes overview grouped by domain with brief behavior/stack notes. +- [internals.md](./internals.md) - Implementation details: bytecode format, VM architecture, stacks/frames, parser, and dispatch. +- [rust.md](./rust.md) - Writing Rust-backed opcodes and wiring them into the C VM; build/setup notes. +- [examples.md](./examples.md) - How to run the examples and the interactive showcase script, with environment tips. +- [testing.md](./testing.md) - How to build and run tests/targets with CMake/CTest, and where to add new tests. +- [troubleshooting.md](./troubleshooting.md) - Common issues and quick fixes for build, includes, and REPL usage. ## New and supplemental guides -- [build.md](./build.md) — How to build Fun with CMake, available targets, and build options (FUN_DEBUG, FUN_USE_MUSL, FUN_WITH_CPP, FUN_WITH_RUST). -- [cli.md](./cli.md) — Command‑line usage of the `fun` executable: synopsis, options, exit codes, includes and library paths. -- [contributing.md](./contributing.md) — How to contribute: project structure, coding style, running tests, and PR guidelines. -- [style-guide.md](./style-guide.md) — Coding conventions for C and Fun (indentation, naming, idioms). -- [stdlib.md](./stdlib.md) — Overview of the standard library modules under ./lib with one‑line summaries. -- [embedding.md](./embedding.md) — Embedding the VM from C/Rust, lifecycle, and host integration tips. -- [errors-and-diagnostics.md](./errors-and-diagnostics.md) — Understanding parser/runtime errors and enabling diagnostics. -- [performance.md](./performance.md) — Build/runtime tuning tips and patterns for better performance. -- [security-and-sandboxing.md](./security-and-sandboxing.md) — Trust boundaries, I/O expectations, and capability restrictions. -- [faq.md](./faq.md) — Frequently asked questions and quick answers. -- [writing-tests.md](./writing-tests.md) — How to author new tests for Fun and opcode components. -- [bytecode-format.md](./bytecode-format.md) — Reference for the bytecode format (split out from internals for convenience). -- [roadmap.md](./roadmap.md) — High‑level direction, planned features, and pointers to issues. +- [build.md](./build.md) - How to build Fun with CMake, available targets, and build options (FUN_DEBUG, FUN_USE_MUSL, FUN_WITH_CPP, FUN_WITH_RUST). +- [cli.md](./cli.md) - Command-line usage of the `fun` executable: synopsis, options, exit codes, includes and library paths. +- [contributing.md](./contributing.md) - How to contribute: project structure, coding style, running tests, and PR guidelines. +- [style-guide.md](./style-guide.md) - Coding conventions for C and Fun (indentation, naming, idioms). +- [stdlib.md](./stdlib.md) - Overview of the standard library modules under ./lib with one-line summaries. +- [embedding.md](./embedding.md) - Embedding the VM from C/Rust, lifecycle, and host integration tips. +- [errors-and-diagnostics.md](./errors-and-diagnostics.md) - Understanding parser/runtime errors and enabling diagnostics. +- [performance.md](./performance.md) - Build/runtime tuning tips and patterns for better performance. +- [security-and-sandboxing.md](./security-and-sandboxing.md) - Trust boundaries, I/O expectations, and capability restrictions. +- [faq.md](./faq.md) - Frequently asked questions and quick answers. +- [writing-tests.md](./writing-tests.md) - How to author new tests for Fun and opcode components. +- [bytecode-format.md](./bytecode-format.md) - Reference for the bytecode format (split out from internals for convenience). +- [roadmap.md](./roadmap.md) - High-level direction, planned features, and pointers to issues. ## Tips diff --git a/docs/bytecode-format.md b/docs/bytecode-format.md index 6d58d76..762188f 100644 --- a/docs/bytecode-format.md +++ b/docs/bytecode-format.md @@ -1,6 +1,6 @@ # Bytecode Format (Overview) -This document summarizes the Fun bytecode format. For deep VM details, see `docs/internals.md`. +This document summarizes the Fun bytecode format. For deep VM details, see [internals.md](./internals.md). ## Goals - Compact representation for fast loading and dispatch @@ -25,5 +25,5 @@ This document summarizes the Fun bytecode format. For deep VM details, see `docs - Operands encoded inline following the opcode (width varies by instruction). ## Versioning and compatibility -- The header’s version field allows the VM to refuse or translate older/newer formats. +- The header's version field allows the VM to refuse or translate older/newer formats. - Keep additions backward-compatible when possible by appending sections or flags. diff --git a/docs/cli.md b/docs/cli.md index ff036fa..0874569 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -7,24 +7,24 @@ Reference for the `fun` command-line interface. fun [options] [-- args...] ``` -If no script is supplied and interactive mode is available, `fun` starts a REPL (see `docs/repl.md`). +If no script is supplied and interactive mode is available, `fun` starts a REPL (see [repl.md](./repl.md)). ## Common options -- `-i`, `--repl` — start an interactive REPL -- `-v`, `--version` — print version and exit -- `-h`, `--help` — show help and exit +- `-i`, `--repl` - start an interactive REPL +- `-v`, `--version` - print version and exit +- `-h`, `--help` - show help and exit Options may vary between versions; run `fun --help` to see what your build supports. ## Exit codes -- `0` — success -- non-zero — error during parse, compile, or runtime +- `0` - success +- non-zero - error during parse, compile, or runtime ## Includes and library paths -- `FUN_LIB_DIR` — environment variable that points to the stdlib location; when running from the repo, set this to `./lib`. -- `DEFAULT_LIB_DIR` — compiled-in fallback path determined at build/install time. +- `FUN_LIB_DIR` - environment variable that points to the stdlib location; when running from the repo, set this to `./lib`. +- `DEFAULT_LIB_DIR` - compiled-in fallback path determined at build/install time. -See also: `docs/includes.md` for namespaced includes and search order. +See also: [includes.md](./includes.md) for namespaced includes and search order. ## Examples Run a script: diff --git a/docs/contributing.md b/docs/contributing.md index 806c833..04191e0 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -3,25 +3,25 @@ Thanks for your interest in contributing! This guide covers the basics to get you productive quickly. ## Getting started -- Clone the repo and build (see `docs/build.md`). -- Run tests locally (see `docs/testing.md`). -- Explore examples (see `docs/examples.md`). +- Clone the repo and build (see [build.md](./build.md)). +- Run tests locally (see [testing.md](./testing.md)). +- Explore examples (see [examples.md](./examples.md)). ## Project structure -- `src/` — C core, VM, and opcode implementations (`src/vm/*`). -- `lib/` — Standard library written in Fun. -- `examples/` — Example programs and showcases. -- `docs/` — Documentation. -- `spec/` — Language specification drafts. +- `src/` - C core, VM, and opcode implementations ([src/vm](../src/vm/)). +- `lib/` - Standard library written in Fun. +- `examples/` - Example programs and showcases. +- `docs/` - Documentation. +- `spec/` - Language specification drafts. ## Code style - C: C99, two-space indent, no tabs. Keep functions short and focused. - Fun: two-space indent, snake_case for functions, PascalCase for classes/constructors. -- Prefer clear names over abbreviations. See `docs/style-guide.md`. +- Prefer clear names over abbreviations. See [style-guide.md](./style-guide.md). ## Development workflow 1. Create a small, focused branch. -2. Add/adjust tests for behavior changes (see `docs/writing-tests.md`). +2. Add/adjust tests for behavior changes (see [writing-tests.md](./writing-tests.md)). 3. Update docs if user-visible behavior changes. 4. Submit a PR with a clear description and rationale. @@ -37,4 +37,4 @@ Please include: - `fun --version` output ## Code of Conduct -Be respectful and inclusive. See `CODE_OF_CONDUCT.md` in the repository root. +Be respectful and inclusive. See [CODE_OF_CONDUCT.md](../CODE_OF_CONDUCT.md) in the repository root. diff --git a/docs/embedding.md b/docs/embedding.md index f603250..321f9fb 100644 --- a/docs/embedding.md +++ b/docs/embedding.md @@ -3,8 +3,8 @@ This guide outlines how to embed the Fun VM in a host application and extend it from C/Rust. ## Overview -- The VM is implemented in C (see `src/vm/`). -- Optional Rust-based opcodes can be enabled via `FUN_WITH_RUST` (see `docs/rust.md`). +- The VM is implemented in C (see [src/vm](../src/vm/)). +- Optional Rust-based opcodes can be enabled via `FUN_WITH_RUST` (see [rust.md](./rust.md)). ## Embedding from C While the exact API surface may evolve, a typical embedding flow looks like: @@ -14,7 +14,7 @@ While the exact API surface may evolve, a typical embedding flow looks like: 4. Execute entry function or script body. 5. Retrieve results and clean up. -See `src/vm/core` and related headers for public entry points and value types. +See [src/vm/core](../src/vm/core/) and related headers for public entry points and value types. ### Hosting considerations - Threading: share VM state cautiously or create one VM per thread. @@ -22,8 +22,8 @@ See `src/vm/core` and related headers for public entry points and value types. - Errors: propagate parse/runtime errors back to the host with useful messages. ## Extending with Rust -When `FUN_WITH_RUST=ON`, a Rust static library from `src/rust/` is built and linked. You can: +When `FUN_WITH_RUST=ON`, a Rust static library from [`src/rust/`](../src/rust/) is built and linked. You can: - Implement new opcodes/functions in Rust. - Expose a C ABI for the VM to call into. -See `docs/rust.md` for details and example code. +See [rust.md](./rust.md) for details and example code. diff --git a/docs/errors-and-diagnostics.md b/docs/errors-and-diagnostics.md index f2b5757..fc92ee3 100644 --- a/docs/errors-and-diagnostics.md +++ b/docs/errors-and-diagnostics.md @@ -8,7 +8,7 @@ This guide helps you understand common error messages and how to collect useful - Runtime errors: type mismatches, out-of-range access, invalid operations. ## Enabling diagnostics -- Build with `-DFUN_DEBUG=ON` to enable additional assertions and debug messages (see `docs/build.md`). +- Build with `-DFUN_DEBUG=ON` to enable additional assertions and debug messages (see [build.md](./build.md)). - Run with smaller, focused scripts to isolate issues. ## Getting useful reports diff --git a/docs/faq.md b/docs/faq.md index 82947b4..5e98acf 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -2,21 +2,21 @@ Answers to common questions. -## I built Fun but includes aren’t found -Set `FUN_LIB_DIR` to the repository’s `./lib` directory when running without installation: +## I built Fun but includes aren't found +Set `FUN_LIB_DIR` to the repository's `./lib` directory when running without installation: ``` FUN_LIB_DIR=./lib ./build_debug/fun examples/hello.fun ``` -See `docs/includes.md`. +See [includes.md](./includes.md). ## How do I start the REPL? -Run `fun -i` (or run `fun` without a script, depending on version). See `docs/repl.md`. +Run `fun -i` (or run `fun` without a script, depending on version). See [repl.md](./repl.md). ## Which build target should I use? -Use the aggregate `build` target to build `fun`, `fun_test`, and `test_opcodes`. See `docs/build.md`. +Use the aggregate `build` target to build `fun`, `fun_test`, and `test_opcodes`. See [build.md](./build.md). ## Where are the standard libraries? -Under `./lib/`. See `docs/stdlib.md` for an overview. +Under [`./lib/`](../lib/). See [stdlib.md](./stdlib.md) for an overview. ## Where can I find internals and opcodes? -Browse `src/vm/` and `docs/internals.md` / `docs/opcodes.md`. +Browse [src/vm](../src/vm/) and [internals.md](./internals.md) / [opcodes.md](./opcodes.md). diff --git a/docs/roadmap.md b/docs/roadmap.md index 4792b8f..3235a4f 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -9,13 +9,13 @@ This page outlines high-level areas of focus and points to places where you can - Safety: clearer error messages, diagnostics, and sandboxing guidance ## Near-term -- Expand CLI reference and examples (`docs/cli.md`) -- Improve testing docs and coverage (`docs/writing-tests.md`) -- Fill gaps in stdlib documentation (`docs/stdlib.md`) +- Expand CLI reference and examples ([cli.md](./cli.md)) +- Improve testing docs and coverage ([writing-tests.md](./writing-tests.md)) +- Fill gaps in stdlib documentation ([stdlib.md](./stdlib.md)) ## Medium-term -- Bytecode/reference updates as internals evolve (`docs/bytecode-format.md`, `docs/internals.md`) -- Embedding guides and host API stability (`docs/embedding.md`, `docs/rust.md`) +- Bytecode/reference updates as internals evolve ([bytecode-format.md](./bytecode-format.md), [internals.md](./internals.md)) +- Embedding guides and host API stability ([embedding.md](./embedding.md), [rust.md](./rust.md)) ## Contributing -See `docs/contributing.md` for how to propose and implement items. Track concrete tasks via repository issues and PRs. +See [contributing.md](./contributing.md) for how to propose and implement items. Track concrete tasks via repository issues and PRs. diff --git a/docs/stdlib.md b/docs/stdlib.md index a075823..c580379 100644 --- a/docs/stdlib.md +++ b/docs/stdlib.md @@ -1,19 +1,19 @@ # Standard Library Overview -This page provides a quick orientation to the standard library located under `./lib/`. +This page provides a quick orientation to the standard library located under [`./lib/`](../lib/). The stdlib is written in Fun and organized by domain. Below are top-level modules and what they generally cover. Refer to the source for full APIs and examples. ## Module index (selected) -- `crypt/` — cryptographic helpers (hashing, encoding helpers). See also `lib/crypt`. -- `encoding/` — text/binary encodings and conversions. -- `io/` — file and stream utilities. -- `net/` — basic networking helpers. -- `regex/` — regular expression utilities (PCRE2 when available). -- `ui/` — UI helpers (e.g., Tk if enabled at build time). -- `utils/` — small reusable helpers and utilities. +- `crypt/` - cryptographic helpers (hashing, encoding helpers). See also [lib/crypt](../lib/crypt/). +- `encoding/` - text/binary encodings and conversions. +- `io/` - file and stream utilities. +- `net/` - basic networking helpers. +- `regex/` - regular expression utilities (PCRE2 when available). +- `ui/` - UI helpers (e.g., Tk if enabled at build time). +- `utils/` - small reusable helpers and utilities. -Note: Availability of some modules can depend on optional extensions selected at build time (see `docs/build.md`). +Note: Availability of some modules can depend on optional extensions selected at build time (see [build.md](./build.md)). ## Using modules ```fun @@ -23,4 +23,4 @@ let s = strings.trim(" hello ") print(s) ``` -For search paths and namespacing details, see `docs/includes.md` and `docs/cli.md` (FUN_LIB_DIR and DEFAULT_LIB_DIR). +For search paths and namespacing details, see [includes.md](./includes.md) and [cli.md](./cli.md) (FUN_LIB_DIR and DEFAULT_LIB_DIR). From 53698478d9cf3b31be84b7aefe09eb7f615740d9 Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 19 Feb 2026 12:33:33 +0100 Subject: [PATCH 31/39] Added OpenSSL as an extension, but just implemented MD5. (0.38.12) --- CMakeLists.txt | 2 +- README.md | 15 ++++++++++ cmake/Extensions/Extensions.cmake | 2 ++ cmake/Extensions/OPENSSL.cmake | 41 +++++++++++++++++++++++++++ cmake/Targets.cmake | 7 ++++- docs/README.md | 3 +- docs/examples.md | 4 +-- docs/opcodes.md | 5 ++++ examples/crypto/openssl_md5.fun | 28 ++++++++++++++++++ src/bytecode.c | 1 + src/bytecode.h | 3 ++ src/external/opensssl.c | 47 +++++++++++++++++++++++++++++++ src/parser.c | 9 ++++++ src/vm.c | 4 +++ src/vm/openssl/md5.c | 16 +++++++++++ 15 files changed, 182 insertions(+), 5 deletions(-) create mode 100644 cmake/Extensions/OPENSSL.cmake create mode 100644 examples/crypto/openssl_md5.fun create mode 100644 src/external/opensssl.c create mode 100644 src/vm/openssl/md5.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 8aef879..fd663a3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.11 LANGUAGES C) +project(fun VERSION 0.38.12 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) diff --git a/README.md b/README.md index 8a540ba..402a86d 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ See [./lib/](https://git.xw3.org/fun/fun/src/branch/main/lib) for what the stand - [libSQL](https://github.com/tursodatabase/libsql) support builtin as a compatible alternative to SQLite (optional) ☑ - [PCRE2](https://pcre2project.github.io/pcre2/) support builtin for Perl-Compatible Regular Expressions (optional) ☑ - [PCSC](https://pcscworkgroup.com/) smart card support builtin using [PCSC lite](https://pcsclite.apdu.fr/) (optional) ☑ +- [OpenSSL](https://www.openssl.org/) integration (currently MD5 helper) (optional) ☑ - [SQLite](https://sqlite.org/) support builtin (optional) ☑ - [Tk](https://www.tcl-lang.org/) support builtin for GUI application development (optional) ☑ - [XML](https://www.w3.org/XML/) support builtin using [libxml2](https://gitlab.gnome.org/GNOME/libxml2/-/wikis/home) (optional) ☑ @@ -103,6 +104,20 @@ Note: Not all of the above features will be implemented. Those who are marked "D There are some libs written in Fun available in the [./lib/](https://git.xw3.org/fun/fun/src/branch/main/lib) diretory. In the future most Fun enhancements should be written in Fun itself. +### OpenSSL quickstart (MD5) + +The OpenSSL integration is optional and currently provides an `openssl_md5(data)` helper. + +- Build with OpenSSL enabled: + - `cmake -S . -B build_debug -DFUN_WITH_OPENSSL=ON` + - `cmake --build build_debug --target fun` +- Run the example: + - `./build_debug/fun examples/crypto/openssl_md5.fun` + +If OpenSSL is disabled, the function returns an empty string (consistent with other optional extensions). + +Note: On OpenSSL 3.x the legacy `MD5_*` APIs are deprecated; you may see warnings during build. + ## Documentation Looking for docs? Start here: diff --git a/cmake/Extensions/Extensions.cmake b/cmake/Extensions/Extensions.cmake index 070f410..b16333b 100644 --- a/cmake/Extensions/Extensions.cmake +++ b/cmake/Extensions/Extensions.cmake @@ -22,6 +22,7 @@ include(${CMAKE_SOURCE_DIR}/cmake/Extensions/PCRE2.cmake) include(${CMAKE_SOURCE_DIR}/cmake/Extensions/CURL.cmake) include(${CMAKE_SOURCE_DIR}/cmake/Extensions/NOTCURSES.cmake) include(${CMAKE_SOURCE_DIR}/cmake/Extensions/REPL.cmake) +include(${CMAKE_SOURCE_DIR}/cmake/Extensions/OPENSSL.cmake) # Summary of extension toggles message(STATUS "---- Fun extension summary ----") @@ -36,4 +37,5 @@ _fun_print_feature("PCRE2 (FUN_WITH_PCRE2)" FUN_WITH_PCRE2) _fun_print_feature("libcurl (FUN_WITH_CURL)" FUN_WITH_CURL) _fun_print_feature("Notcurses (FUN_WITH_NOTCURSES)" FUN_WITH_NOTCURSES) _fun_print_feature("REPL (FUN_WITH_REPL)" FUN_WITH_REPL) +_fun_print_feature("OpenSSL (FUN_WITH_OPENSSL)" FUN_WITH_OPENSSL) message(STATUS "--------------------------------") diff --git a/cmake/Extensions/OPENSSL.cmake b/cmake/Extensions/OPENSSL.cmake new file mode 100644 index 0000000..3a3f623 --- /dev/null +++ b/cmake/Extensions/OPENSSL.cmake @@ -0,0 +1,41 @@ +## OpenSSL optional integration (MD5, etc.) + +option(FUN_WITH_OPENSSL "Enable OpenSSL-based features (e.g., md5)" OFF) + +set(OPENSSL_INCLUDE_DIRS "") +set(OPENSSL_LINK_LIBS "") + +if(FUN_WITH_OPENSSL) + find_package(OpenSSL REQUIRED) + if(NOT OpenSSL_FOUND AND NOT OPENSSL_FOUND) + message(FATAL_ERROR "FUN_WITH_OPENSSL=ON but OpenSSL not found") + endif() + + # CMake 3.11+ standard variables + if(TARGET OpenSSL::Crypto) + set(OPENSSL_LINK_LIBS OpenSSL::Crypto) + elseif(DEFINED OPENSSL_CRYPTO_LIBRARY) + set(OPENSSL_LINK_LIBS ${OPENSSL_CRYPTO_LIBRARY}) + endif() + + if(DEFINED OPENSSL_INCLUDE_DIR) + list(APPEND OPENSSL_INCLUDE_DIRS ${OPENSSL_INCLUDE_DIR}) + endif() + + # Propagate to main targets if they exist in this scope + if(TARGET fun_core) + target_link_libraries(fun_core PRIVATE ${OPENSSL_LINK_LIBS}) + target_include_directories(fun_core PRIVATE ${OPENSSL_INCLUDE_DIRS}) + target_compile_definitions(fun_core PRIVATE FUN_WITH_OPENSSL=1) + endif() + if(TARGET fun) + target_link_libraries(fun PRIVATE ${OPENSSL_LINK_LIBS}) + target_include_directories(fun PRIVATE ${OPENSSL_INCLUDE_DIRS}) + target_compile_definitions(fun PRIVATE FUN_WITH_OPENSSL=1) + endif() + if(TARGET fun_test) + target_link_libraries(fun_test PRIVATE ${OPENSSL_LINK_LIBS}) + target_include_directories(fun_test PRIVATE ${OPENSSL_INCLUDE_DIRS}) + target_compile_definitions(fun_test PRIVATE FUN_WITH_OPENSSL=1) + endif() +endif() diff --git a/cmake/Targets.cmake b/cmake/Targets.cmake index 99146ec..bd6c48e 100644 --- a/cmake/Targets.cmake +++ b/cmake/Targets.cmake @@ -36,7 +36,8 @@ foreach(var_pair LIBSQL LIBXML2 TCL - NOTCURSES) + NOTCURSES + OPENSSL) if(${var_pair}_INCLUDE_DIRS) target_include_directories(fun_core PRIVATE ${${var_pair}_INCLUDE_DIRS}) endif() @@ -89,6 +90,10 @@ if(FUN_WITH_TCLTK) target_compile_definitions(fun_core PUBLIC FUN_WITH_TCLTK=1) endif() +if(FUN_WITH_OPENSSL) + target_compile_definitions(fun_core PUBLIC FUN_WITH_OPENSSL=1) +endif() + # Workaround: provide a dummy rust_eh_personality to satisfy linker when using # no_std Rust staticlib with panic abort (some toolchains still reference it). # If needed, we could add a C shim here, but the Rust crate now defines diff --git a/docs/README.md b/docs/README.md index 75e488f..2c4cccc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -21,7 +21,7 @@ This file serves as an index of the documents in this directory. Links are relat ## New and supplemental guides -- [build.md](./build.md) - How to build Fun with CMake, available targets, and build options (FUN_DEBUG, FUN_USE_MUSL, FUN_WITH_CPP, FUN_WITH_RUST). +- [build.md](./build.md) - How to build Fun with CMake, available targets, and build options (FUN_DEBUG, FUN_USE_MUSL, FUN_WITH_CPP, FUN_WITH_RUST, FUN_WITH_OPENSSL). - [cli.md](./cli.md) - Command-line usage of the `fun` executable: synopsis, options, exit codes, includes and library paths. - [contributing.md](./contributing.md) - How to contribute: project structure, coding style, running tests, and PR guidelines. - [style-guide.md](./style-guide.md) - Coding conventions for C and Fun (indentation, naming, idioms). @@ -39,3 +39,4 @@ This file serves as an index of the documents in this directory. Links are relat - When building from the repo without installing, set `FUN_LIB_DIR` to the local `./lib` directory so examples and the REPL can locate the stdlib. - For a broader project overview and quickstart, see the repository root [README.md](../README.md). +- Crypto example: if built with `-DFUN_WITH_OPENSSL=ON`, try `examples/crypto/openssl_md5.fun` to compute MD5 using OpenSSL. diff --git a/docs/examples.md b/docs/examples.md index 358ef0f..5571db7 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -37,14 +37,14 @@ Notes: Tip: you can run specific examples directly too: ``` -FUN_LIB_DIR="$(pwd)/lib" fun examples/crypto/aes256.fun +FUN_LIB_DIR="$(pwd)/lib" fun examples/crypto/openssl_md5.fun ``` ## Example categories Browse the `examples/` tree for areas of interest: -- crypto — crypto demonstrations (e.g., AES) +- crypto — crypto demonstrations (e.g., OpenSSL MD5 helper; requires build with `-DFUN_WITH_OPENSSL=ON`) - blocking / interactive — I/O or user-interactive patterns - error / broken — negative tests and error showcases - math — numeric operations diff --git a/docs/opcodes.md b/docs/opcodes.md index 15c742d..d1d9dbc 100644 --- a/docs/opcodes.md +++ b/docs/opcodes.md @@ -202,6 +202,11 @@ This document provides an overview of the available VM opcodes implemented under - OP_CURL_POST: HTTP POST; pops body:string, url:string; pushes response:string or Nil. - OP_CURL_DOWNLOAD: Download URL to file; pops path:string, url:string; pushes 1/0. +## OpenSSL (optional) + +- OP_OPENSSL_MD5: Compute MD5 digest and return lowercase hex string; pops data:string; pushes md5:string. + - Requires building with `-DFUN_WITH_OPENSSL=ON`. When disabled, this opcode still exists but returns an empty string to match other optional extensions’ fallback behavior. + ## PCRE2 (Regex) - OP_PCRE2_TEST: Test pattern; pops flags:int, text:string, pattern:string; pushes 1/0. diff --git a/examples/crypto/openssl_md5.fun b/examples/crypto/openssl_md5.fun new file mode 100644 index 0000000..7002721 --- /dev/null +++ b/examples/crypto/openssl_md5.fun @@ -0,0 +1,28 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2025 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +// OpenSSL MD5 example +// Enable with -DFUN_WITH_OPENSSL=ON during build for real hashing. + +s = "abc" +d = openssl_md5(s) +print("md5(abc) = " + d) + +// Another quick check (empty string) +e = "" +print("md5(\"\") = " + openssl_md5(e)) + +/* Expected output: +md5(abc) = 900150983cd24fb0d6963f7d28e17f72 +md5("") = d41d8cd98f00b204e9800998ecf8427e +*/ diff --git a/src/bytecode.c b/src/bytecode.c index 793ef79..13e2ce9 100644 --- a/src/bytecode.c +++ b/src/bytecode.c @@ -169,6 +169,7 @@ static const char *opcode_name(OpCode op) { case OP_PCRE2_TEST: return "PCRE2_TEST"; case OP_PCRE2_MATCH: return "PCRE2_MATCH"; case OP_PCRE2_FINDALL: return "PCRE2_FINDALL"; + case OP_OPENSSL_MD5: return "OPENSSL_MD5"; case OP_INI_LOAD: return "INI_LOAD"; case OP_INI_FREE: return "INI_FREE"; case OP_INI_GET_STRING: return "INI_GET_STRING"; diff --git a/src/bytecode.h b/src/bytecode.h index 5eb3de4..92f9867 100644 --- a/src/bytecode.h +++ b/src/bytecode.h @@ -181,6 +181,9 @@ typedef enum { OP_PCRE2_MATCH, // pops flags, text, pattern; pushes match map or Nil OP_PCRE2_FINDALL, // pops flags, text, pattern; pushes array of match maps + // OpenSSL (optional) + OP_OPENSSL_MD5, // pops data string; pushes md5 hex string + // INI (iniparser 4.2.6) optional OP_INI_LOAD, // pops path; pushes handle (>0) or 0 OP_INI_FREE, // pops handle; pushes 1/0 diff --git a/src/external/opensssl.c b/src/external/opensssl.c new file mode 100644 index 0000000..a4fcf26 --- /dev/null +++ b/src/external/opensssl.c @@ -0,0 +1,47 @@ +/* +* This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2025 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + + /* + * OpenSSL integration helpers (currently MD5 only) + */ + +#ifdef FUN_WITH_OPENSSL +# include +#endif +#include + +/* Compute MD5 hex of input buffer; returns malloc'ed C string (lowercase hex). + * Caller must free(). Returns NULL on failure. When OpenSSL is disabled, + * returns an allocated empty string ("") to keep behavior consistent with + * other optional extensions. */ +static char *fun_openssl_md5_hex(const unsigned char *data, size_t len) { + static const char hexdig[] = "0123456789abcdef"; + if (!data && len != 0) return NULL; +#ifdef FUN_WITH_OPENSSL + unsigned char digest[MD5_DIGEST_LENGTH]; + MD5_CTX ctx; + if (MD5_Init(&ctx) != 1) return NULL; + if (len && MD5_Update(&ctx, data, len) != 1) return NULL; + if (MD5_Final(digest, &ctx) != 1) return NULL; + char *hex = (char*)malloc(MD5_DIGEST_LENGTH * 2 + 1); + if (!hex) return NULL; + for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) { + hex[2*i] = hexdig[(digest[i] >> 4) & 0xF]; + hex[2*i+1] = hexdig[digest[i] & 0xF]; + } + hex[MD5_DIGEST_LENGTH * 2] = '\0'; + return hex; +#else + char *hex = (char*)malloc(1); + if (hex) hex[0] = '\0'; + return hex; +#endif +} diff --git a/src/parser.c b/src/parser.c index ad8dd1b..aa16896 100644 --- a/src/parser.c +++ b/src/parser.c @@ -1197,6 +1197,15 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos) free(name); return 1; } + /* OpenSSL (md5) */ + if (strcmp(name, "openssl_md5") == 0) { + (*pos)++; /* '(' */ + if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "openssl_md5 expects (data)"); free(name); return 0; } + if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "Expected ')' after openssl_md5 arg"); free(name); return 0; } + bytecode_add_instruction(bc, OP_OPENSSL_MD5, 0); + free(name); + return 1; + } /* PCSC builtins */ if (strcmp(name, "pcsc_establish") == 0) { (*pos)++; /* '(' */ diff --git a/src/vm.c b/src/vm.c index c8f42e4..a64f80c 100644 --- a/src/vm.c +++ b/src/vm.c @@ -73,6 +73,7 @@ #include "external/sqlite.c" #include "external/tcltk.c" #include "external/xml2.c" +#include "external/opensssl.c" /* forward declarations for include mapping used in error reporting */ extern char *preprocess_includes(const char *src); @@ -868,6 +869,9 @@ void vm_run(VM *vm, Bytecode *entry) { #include "vm/curl/download.c" #endif + /* OpenSSL ops (md5) */ + #include "vm/openssl/md5.c" + /* Tk (Tcl/Tk) ops */ #ifdef FUN_WITH_TCLTK #include "vm/tk/eval.c" diff --git a/src/vm/openssl/md5.c b/src/vm/openssl/md5.c new file mode 100644 index 0000000..473605d --- /dev/null +++ b/src/vm/openssl/md5.c @@ -0,0 +1,16 @@ +/** + * OpenSSL MD5 builtin + */ +case OP_OPENSSL_MD5: { + Value vdata = pop_value(vm); + char *s = value_to_string_alloc(&vdata); + free_value(vdata); + if (!s) { push_value(vm, make_string("")); break; } + char *hex = fun_openssl_md5_hex((const unsigned char*)s, strlen(s)); + free(s); + if (!hex) { push_value(vm, make_string("")); break; } + Value out = make_string(hex); + free(hex); + push_value(vm, out); + break; +} From 38968a9a51d7922c48ed7d00fbaf9767b5858471 Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 19 Feb 2026 14:05:14 +0100 Subject: [PATCH 32/39] More OpenSSL and documenation fun. No more words to say. (0.38.13) --- CMakeLists.txt | 2 +- README.md | 32 +++---- docs/README.md | 7 ++ docs/cli.md | 4 +- docs/examples.md | 2 +- docs/external/README.md | 25 ++++++ docs/external/curl.md | 14 ++++ docs/external/ini.md | 20 +++++ docs/external/json.md | 15 ++++ docs/external/libsql.md | 15 ++++ docs/external/notcurses.md | 16 ++++ docs/external/openssl.md | 31 +++++++ docs/external/pcre2.md | 14 ++++ docs/external/pcsc.md | 17 ++++ docs/external/sqlite.md | 15 ++++ docs/external/tcltk.md | 16 ++++ docs/external/xml2.md | 15 ++++ docs/faq.md | 2 +- docs/opcodes.md | 4 +- docs/rust.md | 10 +-- docs/testing.md | 8 +- docs/troubleshooting.md | 4 +- examples/crypto/openssl_sha256.fun | 28 +++++++ examples/crypto/openssl_sha512.fun | 28 +++++++ make | 5 ++ src/bytecode.c | 2 + src/bytecode.h | 2 + src/external/openssl.c | 130 +++++++++++++++++++++++++++++ src/external/opensssl.c | 47 ----------- src/parser.c | 18 +++- src/vm.c | 6 +- src/vm/openssl/sha256.c | 16 ++++ src/vm/openssl/sha512.c | 16 ++++ 33 files changed, 498 insertions(+), 88 deletions(-) create mode 100644 docs/external/README.md create mode 100644 docs/external/curl.md create mode 100644 docs/external/ini.md create mode 100644 docs/external/json.md create mode 100644 docs/external/libsql.md create mode 100644 docs/external/notcurses.md create mode 100644 docs/external/openssl.md create mode 100644 docs/external/pcre2.md create mode 100644 docs/external/pcsc.md create mode 100644 docs/external/sqlite.md create mode 100644 docs/external/tcltk.md create mode 100644 docs/external/xml2.md create mode 100644 examples/crypto/openssl_sha256.fun create mode 100644 examples/crypto/openssl_sha512.fun create mode 100644 src/external/openssl.c delete mode 100644 src/external/opensssl.c create mode 100644 src/vm/openssl/sha256.c create mode 100644 src/vm/openssl/sha512.c diff --git a/CMakeLists.txt b/CMakeLists.txt index fd663a3..a5a8aba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.12 LANGUAGES C) +project(fun VERSION 0.38.13 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) diff --git a/README.md b/README.md index 402a86d..dcfc6fd 100644 --- a/README.md +++ b/README.md @@ -87,16 +87,16 @@ See [./lib/](https://git.xw3.org/fun/fun/src/branch/main/lib) for what the stand ### Optional extensions (build-time selectable / only testing this on Linux actually): - [CGI](https://en.wikipedia.org/wiki/Common_Gateway_Interface) support builtin using [kcgi](https://kristaps.bsd.lv/kcgi/) (optional) ☐ -- [cURL](https://curl.se/) support builtin using [libcurl](https://curl.se/libcurl/) (optional) ☑ -- [INI](https://en.wikipedia.org/wiki/INI_file) support builtin using [iniparser](https://gitlab.com/iniparser/iniparser/) (optional) ☑ -- [JSON](https://www.json.org/) support builtin using [json-c](https://github.com/json-c/json-c) (optional) ☑ -- [libSQL](https://github.com/tursodatabase/libsql) support builtin as a compatible alternative to SQLite (optional) ☑ -- [PCRE2](https://pcre2project.github.io/pcre2/) support builtin for Perl-Compatible Regular Expressions (optional) ☑ -- [PCSC](https://pcscworkgroup.com/) smart card support builtin using [PCSC lite](https://pcsclite.apdu.fr/) (optional) ☑ -- [OpenSSL](https://www.openssl.org/) integration (currently MD5 helper) (optional) ☑ -- [SQLite](https://sqlite.org/) support builtin (optional) ☑ -- [Tk](https://www.tcl-lang.org/) support builtin for GUI application development (optional) ☑ -- [XML](https://www.w3.org/XML/) support builtin using [libxml2](https://gitlab.gnome.org/GNOME/libxml2/-/wikis/home) (optional) ☑ +- [cURL (libcurl)](./docs/external/curl.md) (optional) ☑ +- [INI (iniparser)](./docs/external/ini.md) (optional) ☑ +- [JSON (json-c)](./docs/external/json.md) (optional) ☑ +- [libSQL](./docs/external/libsql.md) (optional) ☑ +- [PCRE2](./docs/external/pcre2.md) (optional) ☑ +- [PCSC (smart cards)](./docs/external/pcsc.md) (optional) ☑ +- [OpenSSL](./docs/external/openssl.md) (optional) ☑ +- [SQLite](./docs/external/sqlite.md) (optional) ☑ +- [Tk (Tcl/Tk GUI)](./docs/external/tcltk.md) (optional) ☑ +- [XML (libxml2)](./docs/external/xml2.md) (optional) ☑ ☑ = Done / ☐ = Planned or in progress. @@ -106,17 +106,7 @@ There are some libs written in Fun available in the [./lib/](https://git.xw3.org ### OpenSSL quickstart (MD5) -The OpenSSL integration is optional and currently provides an `openssl_md5(data)` helper. - -- Build with OpenSSL enabled: - - `cmake -S . -B build_debug -DFUN_WITH_OPENSSL=ON` - - `cmake --build build_debug --target fun` -- Run the example: - - `./build_debug/fun examples/crypto/openssl_md5.fun` - -If OpenSSL is disabled, the function returns an empty string (consistent with other optional extensions). - -Note: On OpenSSL 3.x the legacy `MD5_*` APIs are deprecated; you may see warnings during build. +See the dedicated page: ./docs/external/openssl.md ## Documentation diff --git a/docs/README.md b/docs/README.md index 2c4cccc..ab2ea78 100644 --- a/docs/README.md +++ b/docs/README.md @@ -35,6 +35,13 @@ This file serves as an index of the documents in this directory. Links are relat - [bytecode-format.md](./bytecode-format.md) - Reference for the bytecode format (split out from internals for convenience). - [roadmap.md](./roadmap.md) - High-level direction, planned features, and pointers to issues. +## External extensions + +Documentation for optional, build-time selectable integrations lives in [external/](./external/): + +- [Index of extensions](./external/README.md) + - Highlights: [cURL](./external/curl.md), [INI](./external/ini.md), [JSON](./external/json.md), [XML (libxml2)](./external/xml2.md), [SQLite](./external/sqlite.md), [libSQL](./external/libsql.md), [PCRE2](./external/pcre2.md), [PC/SC](./external/pcsc.md), [Notcurses](./external/notcurses.md), [Tcl/Tk](./external/tcltk.md), [OpenSSL](./external/openssl.md) + ## Tips - When building from the repo without installing, set `FUN_LIB_DIR` to the local `./lib` directory so examples and the REPL can locate the stdlib. diff --git a/docs/cli.md b/docs/cli.md index 0874569..46f8a32 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -29,10 +29,10 @@ See also: [includes.md](./includes.md) for namespaced includes and search order. ## Examples Run a script: ``` -FUN_LIB_DIR=./lib ./build_debug/fun examples/hello.fun +FUN_LIB_DIR=./lib ./build/fun examples/hello.fun ``` Start the REPL: ``` -./build_debug/fun -i +./build/fun -i ``` diff --git a/docs/examples.md b/docs/examples.md index 5571db7..abd6614 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -44,7 +44,7 @@ FUN_LIB_DIR="$(pwd)/lib" fun examples/crypto/openssl_md5.fun Browse the `examples/` tree for areas of interest: -- crypto — crypto demonstrations (e.g., OpenSSL MD5 helper; requires build with `-DFUN_WITH_OPENSSL=ON`) +- crypto — crypto demonstrations (e.g., OpenSSL MD5/SHA-256/SHA-512 helpers; requires build with `-DFUN_WITH_OPENSSL=ON`) - blocking / interactive — I/O or user-interactive patterns - error / broken — negative tests and error showcases - math — numeric operations diff --git a/docs/external/README.md b/docs/external/README.md new file mode 100644 index 0000000..8f3391e --- /dev/null +++ b/docs/external/README.md @@ -0,0 +1,25 @@ +# External integrations (optional extensions) + +This section documents Fun’s optional, build‑time selectable extensions. Each page covers: +- How to enable the extension via CMake option (FUN_WITH_*) +- Build requirements and detection notes +- Available opcodes and/or helper functions +- Minimal usage examples and links to example scripts + +Extensions: + +- [cURL (libcurl)](./curl.md) +- [INI (iniparser)](./ini.md) +- [JSON (json-c)](./json.md) +- [libxml2 (XML)](./xml2.md) +- [SQLite](./sqlite.md) +- [libSQL (SQLite-compatible)](./libsql.md) +- [PCRE2 (Perl-compatible regex)](./pcre2.md) +- [PC/SC (Smart cards)](./pcsc.md) +- [Notcurses (TUI)](./notcurses.md) +- [Tcl/Tk (GUI)](./tcltk.md) +- [OpenSSL (MD5 helper)](./openssl.md) + +Notes: +- These integrations are optional; the VM compiles without them. +- When disabled, related builtins usually return empty strings/neutral values rather than fail hard, mirroring existing optionality patterns. diff --git a/docs/external/curl.md b/docs/external/curl.md new file mode 100644 index 0000000..b47ddc3 --- /dev/null +++ b/docs/external/curl.md @@ -0,0 +1,14 @@ +# cURL (libcurl) extension (optional) + +- CMake option: FUN_WITH_CURL=ON +- Purpose: HTTP helpers using libcurl. +- Homepage: https://curl.se/libcurl/ + +Opcodes: +- OP_CURL_GET: GET; pops url:string; pushes body:string (empty on error/disabled) +- OP_CURL_POST: POST; pops body:string, url:string; pushes response:string +- OP_CURL_DOWNLOAD: Download to file; pops path:string, url:string; pushes 1/0 + +Notes: +- Requires libcurl development headers/libs. +- When disabled, helpers return empty strings/0 to match optional behavior. diff --git a/docs/external/ini.md b/docs/external/ini.md new file mode 100644 index 0000000..2975313 --- /dev/null +++ b/docs/external/ini.md @@ -0,0 +1,20 @@ +# INI (iniparser) extension (optional) + +- CMake option: FUN_WITH_INI=ON +- Purpose: Read/write simple INI configuration files. +- Homepage: https://github.com/ndevilla/iniparser + +Opcodes: +- OP_INI_LOAD: pops path; pushes handle (>0) or 0 +- OP_INI_FREE: pops handle; pushes 1/0 +- OP_INI_GET_STRING: pops def, key, section, handle; pushes string +- OP_INI_GET_INT: pops def, key, section, handle; pushes int +- OP_INI_GET_DOUBLE: pops def, key, section, handle; pushes float +- OP_INI_GET_BOOL: pops def, key, section, handle; pushes 0/1 +- OP_INI_SET: pops value, key, section, handle; pushes 1/0 +- OP_INI_UNSET: pops key, section, handle; pushes 1/0 +- OP_INI_SAVE: pops path, handle; pushes 1/0 + +Notes: +- Requires iniparser development headers/libs. +- When disabled, helpers return neutral values (0/empty strings) like other optional extensions. diff --git a/docs/external/json.md b/docs/external/json.md new file mode 100644 index 0000000..60475d1 --- /dev/null +++ b/docs/external/json.md @@ -0,0 +1,15 @@ +# JSON (json-c) extension (optional) + +- CMake option: FUN_WITH_JSON=ON +- Purpose: JSON parse/stringify and file helpers via json-c. +- Homepage: https://json-c.github.io/json-c/ + +Opcodes: +- OP_JSON_PARSE: pops text; pushes value or Nil on error +- OP_JSON_STRINGIFY: pops pretty:int(0/1), value; pushes string +- OP_JSON_FROM_FILE: pops path; pushes value or Nil +- OP_JSON_TO_FILE: pops pretty:int(0/1), value, path; pushes 1/0 + +Notes: +- Requires json-c development headers/libs. +- When disabled, functions push empty/neutral values similar to other optional modules. diff --git a/docs/external/libsql.md b/docs/external/libsql.md new file mode 100644 index 0000000..c2df1f9 --- /dev/null +++ b/docs/external/libsql.md @@ -0,0 +1,15 @@ +# libSQL extension (optional) + +- CMake option: FUN_WITH_LIBSQL=ON +- Purpose: SQLite-compatible client using the libSQL (Turso) library. +- Homepage: https://libsql.org/ + +Opcodes: +- OP_LIBSQL_OPEN: pops url_or_path; pushes handle (>0) or 0 +- OP_LIBSQL_CLOSE: pops handle; pushes Nil +- OP_LIBSQL_EXEC: pops sql, handle; pushes rc:int (0=OK) +- OP_LIBSQL_QUERY: pops sql, handle; pushes array + +Notes: +- Uses a SQLite-compatible C API provided by libSQL; behavior is similar to the SQLite backend. +- This module is independent from the SQLite extension; you may enable either or both. diff --git a/docs/external/notcurses.md b/docs/external/notcurses.md new file mode 100644 index 0000000..c596981 --- /dev/null +++ b/docs/external/notcurses.md @@ -0,0 +1,16 @@ +# Notcurses (TUI) extension (optional) + +- CMake option: FUN_WITH_NOTCURSES=ON +- Purpose: Terminal UI capabilities via the Notcurses library. +- Homepage: https://notcurses.com/ + +Opcodes: +- OP_NC_INIT: initialize Notcurses; returns 1 on success, 0 on failure +- OP_NC_SHUTDOWN: shutdown; returns 0 +- OP_NC_CLEAR: clear screen/plane; returns 0 +- OP_NC_DRAW_TEXT: pops text, x, y; draws; returns 0 +- OP_NC_GETCH: pops timeout_ms; returns codepoint or -1 on timeout/error + +Notes: +- Requires Notcurses development headers/libs. +- Behavior may vary across terminals; see the implementation for details. diff --git a/docs/external/openssl.md b/docs/external/openssl.md new file mode 100644 index 0000000..c0a743b --- /dev/null +++ b/docs/external/openssl.md @@ -0,0 +1,31 @@ +# OpenSSL extension (optional) + +- CMake option: FUN_WITH_OPENSSL=ON +- Purpose: provide small crypto helpers backed by OpenSSL. Includes md5, sha256, sha512 helpers. +- Homepage: https://www.openssl.org/ + +Build notes: +- Requires system OpenSSL development headers and libraries. +- On OpenSSL 3.x, legacy MD5_* APIs are deprecated; you may see warnings during build. + +Provided helper/opcodes: +- Function: openssl_md5(data:string) -> string (lowercase hex). Falls back to empty string when the extension is disabled, mirroring other optional modules. +- Function: openssl_sha256(data:string) -> string (lowercase hex). +- Function: openssl_sha512(data:string) -> string (lowercase hex). +- Opcodes: OP_OPENSSL_MD5, OP_OPENSSL_SHA256, OP_OPENSSL_SHA512 (internal mappings for the functions above). + +Quickstart: +- Configure: cmake -S . -B build -DFUN_WITH_OPENSSL=ON +- Build: cmake --build build --target fun +- Run examples: + - ./build/fun examples/crypto/openssl_md5.fun + - ./build/fun examples/crypto/openssl_sha256.fun + - ./build/fun examples/crypto/openssl_sha512.fun + +Example output: +- md5(abc) = 900150983cd24fb0d6963f7d28e17f72 +- md5("") = d41d8cd98f00b204e9800998ecf8427e +- sha256(abc) = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad +- sha256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 +- sha512(abc) = ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f +- sha512("") = cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e diff --git a/docs/external/pcre2.md b/docs/external/pcre2.md new file mode 100644 index 0000000..9e4d9f2 --- /dev/null +++ b/docs/external/pcre2.md @@ -0,0 +1,14 @@ +# PCRE2 (Perl-Compatible Regex) extension (optional) + +- CMake option: FUN_WITH_PCRE2=ON +- Purpose: Advanced regular expressions via PCRE2. +- Homepage: https://www.pcre.org/ + +Opcodes: +- OP_PCRE2_TEST: pops flags, text, pattern; pushes 1/0 +- OP_PCRE2_MATCH: pops flags, text, pattern; pushes match map or Nil +- OP_PCRE2_FINDALL: pops flags, text, pattern; pushes array of match maps + +Notes: +- Requires PCRE2 development headers/libs. +- Flags are backend-specific; see implementation for supported bits. diff --git a/docs/external/pcsc.md b/docs/external/pcsc.md new file mode 100644 index 0000000..c00b171 --- /dev/null +++ b/docs/external/pcsc.md @@ -0,0 +1,17 @@ +# PC/SC (smart cards) extension (optional) + +- CMake option: FUN_WITH_PCSC=ON +- Purpose: Access smart card readers/cards via PC/SC (pcsclite). +- Homepage: https://pcsclite.apdu.fr/ + +Opcodes: +- OP_PCSC_ESTABLISH: returns context id (>0) or 0 +- OP_PCSC_RELEASE: pops ctx id; returns 1/0 +- OP_PCSC_LIST_READERS: pops ctx id; returns array of reader names +- OP_PCSC_CONNECT: pops reader, ctx id; returns handle (>0) or 0 +- OP_PCSC_DISCONNECT: pops handle id; returns 1/0 +- OP_PCSC_TRANSMIT: pops apdu, handle id; returns map with data/SW/rc + +Notes: +- Requires PC/SC lite development headers/libs. +- Behavior and availability depend on platform and reader drivers. diff --git a/docs/external/sqlite.md b/docs/external/sqlite.md new file mode 100644 index 0000000..e246a76 --- /dev/null +++ b/docs/external/sqlite.md @@ -0,0 +1,15 @@ +# SQLite extension (optional) + +- CMake option: FUN_WITH_SQLITE=ON +- Purpose: Access SQLite databases via the native C API. +- Homepage: https://www.sqlite.org/ + +Opcodes: +- OP_SQLITE_OPEN: pops path; pushes handle (>0) or 0 +- OP_SQLITE_CLOSE: pops handle; pushes Nil +- OP_SQLITE_EXEC: pops sql, handle; pushes rc:int (0=OK) +- OP_SQLITE_QUERY: pops sql, handle; pushes array + +Notes: +- Requires SQLite development headers/libs. +- See also: `libSQL` for a compatible alternative backend. diff --git a/docs/external/tcltk.md b/docs/external/tcltk.md new file mode 100644 index 0000000..97cc429 --- /dev/null +++ b/docs/external/tcltk.md @@ -0,0 +1,16 @@ +# Tcl/Tk (GUI) extension (optional) +- CMake option: FUN_WITH_TCLTK=ON +- Purpose: Basic GUI functionality via Tcl/Tk. +- Homepage: https://www.tcl.tk/ +Opcodes: +- OP_TK_EVAL: pops script string; pushes rc (0=OK) +- OP_TK_RESULT: pushes last Tcl result string +- OP_TK_LOOP: enters main event loop; pushes Nil when done +- OP_TK_WM_TITLE: pops title string; sets window title; pushes rc +- OP_TK_LABEL: pops text, id; creates/updates label .id; pushes rc +- OP_TK_BUTTON: pops text, id; creates/updates button .id; pushes rc +- OP_TK_PACK: pops id; packs .id; pushes rc +- OP_TK_BIND: pops command, event, id; binds; pushes rc +Notes: +- Requires Tcl/Tk development headers/libs. +- GUI behavior depends on your desktop environment/window manager. diff --git a/docs/external/xml2.md b/docs/external/xml2.md new file mode 100644 index 0000000..3a86071 --- /dev/null +++ b/docs/external/xml2.md @@ -0,0 +1,15 @@ +# XML (libxml2) extension (optional) + +- CMake option: FUN_WITH_XML2=ON +- Purpose: Minimal XML parsing helpers using libxml2. +- Homepage: http://xmlsoft.org/ + +Opcodes: +- OP_XML_PARSE: pops text; pushes doc handle (>0) or 0 +- OP_XML_ROOT: pops doc handle; pushes node handle (>0) or 0 +- OP_XML_NAME: pops node handle; pushes string (node name) +- OP_XML_TEXT: pops node handle; pushes string (concatenated text) + +Notes: +- Requires libxml2 development headers/libs. +- On many systems, the include path is `/usr/include/libxml2`. diff --git a/docs/faq.md b/docs/faq.md index 5e98acf..1fbc565 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -5,7 +5,7 @@ Answers to common questions. ## I built Fun but includes aren't found Set `FUN_LIB_DIR` to the repository's `./lib` directory when running without installation: ``` -FUN_LIB_DIR=./lib ./build_debug/fun examples/hello.fun +FUN_LIB_DIR=./lib ./build/fun examples/hello.fun ``` See [includes.md](./includes.md). diff --git a/docs/opcodes.md b/docs/opcodes.md index d1d9dbc..5ea6c86 100644 --- a/docs/opcodes.md +++ b/docs/opcodes.md @@ -205,7 +205,9 @@ This document provides an overview of the available VM opcodes implemented under ## OpenSSL (optional) - OP_OPENSSL_MD5: Compute MD5 digest and return lowercase hex string; pops data:string; pushes md5:string. - - Requires building with `-DFUN_WITH_OPENSSL=ON`. When disabled, this opcode still exists but returns an empty string to match other optional extensions’ fallback behavior. +- OP_OPENSSL_SHA256: Compute SHA‑256 digest and return lowercase hex string; pops data:string; pushes sha256:string. +- OP_OPENSSL_SHA512: Compute SHA‑512 digest and return lowercase hex string; pops data:string; pushes sha512:string. + - Requires building with `-DFUN_WITH_OPENSSL=ON`. When disabled, these opcodes still exist but return an empty string to match other optional extensions’ fallback behavior. ## PCRE2 (Regex) diff --git a/docs/rust.md b/docs/rust.md index 71ca53b..9145916 100644 --- a/docs/rust.md +++ b/docs/rust.md @@ -27,8 +27,8 @@ Rust integration is optional and gated by a CMake flag. Default builds usually h Enable it for a configured profile (Debug or Release): - Debug example: - cmake -S . -B build_debug -DFUN_WITH_RUST=ON - cmake --build build_debug --target fun + cmake -S . -B build -DFUN_WITH_RUST=ON + cmake --build build --target fun - Release example: cmake -S . -B build_release -DFUN_WITH_RUST=ON @@ -137,11 +137,11 @@ Once wired, expose the opcode via a builtin function or directly in bytecode. Th Run the example: 1) Build with Rust enabled (Debug): - cmake -S . -B build_debug -DFUN_WITH_RUST=ON - cmake --build build_debug --target fun + cmake -S . -B build -DFUN_WITH_RUST=ON + cmake --build build --target fun 2) Execute the script: - build_debug/fun examples/rust_hello.fun + build/fun examples/rust_hello.fun Expected output: Hello from Rust ops! diff --git a/docs/testing.md b/docs/testing.md index 410e18a..acb140b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -18,7 +18,7 @@ To list targets with CMake directly, consult your IDE or run the build system’ Debug profile example: ``` -cmake --build build_debug --target test_opcodes && ./build/test_opcodes +cmake --build build --target test_opcodes && ./build/test_opcodes ``` Release profile example: @@ -30,14 +30,14 @@ cmake --build build_release --target test_opcodes && ./build/test_opcodes If `fun_test` exists in your configuration: ``` -cmake --build build_debug --target fun_test && ./build/fun_test +cmake --build build --target fun_test && ./build/fun_test ``` You can also invoke CTest to run any tests registered with `add_test()`: ``` -cmake --build build_debug --target test -ctest --test-dir build_debug -j +cmake --build build --target test +ctest --test-dir build -j ``` ## Adding new tests diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index e8dfec0..95fb6cf 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -40,8 +40,8 @@ Fix: - Build with `-DFUN_WITH_REPL=ON` and rebuild the `fun` target. Then launch without arguments: ``` -cmake -S . -B build_debug -DFUN_WITH_REPL=ON -cmake --build build_debug --target fun +cmake -S . -B build -DFUN_WITH_REPL=ON +cmake --build build --target fun FUN_LIB_DIR="$(pwd)/lib" ./build/fun ``` diff --git a/examples/crypto/openssl_sha256.fun b/examples/crypto/openssl_sha256.fun new file mode 100644 index 0000000..f6f564b --- /dev/null +++ b/examples/crypto/openssl_sha256.fun @@ -0,0 +1,28 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +// OpenSSL SHA-256 example +// Enable with -DFUN_WITH_OPENSSL=ON during build for real hashing. + +s = "abc" +d = openssl_sha256(s) +print("sha256(abc) = " + d) + +// Another quick check (empty string) +e = "" +print("sha256(\"\") = " + openssl_sha256(e)) + +/* Expected output: +sha256(abc) = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad +sha256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 +*/ diff --git a/examples/crypto/openssl_sha512.fun b/examples/crypto/openssl_sha512.fun new file mode 100644 index 0000000..f6f8eb7 --- /dev/null +++ b/examples/crypto/openssl_sha512.fun @@ -0,0 +1,28 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +// OpenSSL SHA-512 example +// Enable with -DFUN_WITH_OPENSSL=ON during build for real hashing. + +s = "abc" +d = openssl_sha512(s) +print("sha512(abc) = " + d) + +// Another quick check (empty string) +e = "" +print("sha512(\"\") = " + openssl_sha512(e)) + +/* Expected output: +sha512(abc) = ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f +sha512("") = cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e +*/ diff --git a/make b/make index 4f7dd8d..01e2fbd 100755 --- a/make +++ b/make @@ -32,6 +32,7 @@ if [ "$target" = "all" ]; then -DFUN_WITH_INI=ON \ -DFUN_WITH_NOTCURSES=ON \ -DFUN_WITH_CPP=ON \ + -DFUN_WITH_OPENSSL=ON \ && cmake --build build --target fun elif [ "$target" = "all_debug" ]; then rm -rf build \ @@ -48,6 +49,7 @@ elif [ "$target" = "all_debug" ]; then -DFUN_WITH_INI=ON \ -DFUN_WITH_NOTCURSES=ON \ -DFUN_WITH_CPP=ON \ + -DFUN_WITH_OPENSSL=ON \ -DFUN_DEBUG=ON \ && cmake --build build --target fun elif [ "$target" = "alpine" ]; then @@ -62,6 +64,7 @@ elif [ "$target" = "alpine" ]; then -DFUN_WITH_JSON=ON \ -DFUN_WITH_INI=ON \ -DFUN_WITH_CPP=ON \ + -DFUN_WITH_OPENSSL=ON \ && cmake --build build --target fun elif [ "$target" = "cpp_all" ]; then rm -rf build \ @@ -78,6 +81,7 @@ elif [ "$target" = "cpp_all" ]; then -DFUN_WITH_INI=ON \ -DFUN_WITH_NOTCURSES=ON \ -DFUN_WITH_CPP=ON \ + -DFUN_WITH_OPENSSL=ON \ && cmake --build build --target fun elif [ "$target" = "cpp_minimal" ]; then rm -rf build \ @@ -133,6 +137,7 @@ elif [ "$target" = "rust_all" ]; then -DFUN_WITH_INI=ON \ -DFUN_WITH_RUST=ON \ -DFUN_WITH_CPP=ON \ + -DFUN_WITH_OPENSSL=ON \ -DFUN_DEBUG=OFF \ && cmake --build build --target fun elif [ "$target" = "rust_minimal" ]; then diff --git a/src/bytecode.c b/src/bytecode.c index 13e2ce9..caf6029 100644 --- a/src/bytecode.c +++ b/src/bytecode.c @@ -170,6 +170,8 @@ static const char *opcode_name(OpCode op) { case OP_PCRE2_MATCH: return "PCRE2_MATCH"; case OP_PCRE2_FINDALL: return "PCRE2_FINDALL"; case OP_OPENSSL_MD5: return "OPENSSL_MD5"; + case OP_OPENSSL_SHA256: return "OPENSSL_SHA256"; + case OP_OPENSSL_SHA512: return "OPENSSL_SHA512"; case OP_INI_LOAD: return "INI_LOAD"; case OP_INI_FREE: return "INI_FREE"; case OP_INI_GET_STRING: return "INI_GET_STRING"; diff --git a/src/bytecode.h b/src/bytecode.h index 92f9867..446dd21 100644 --- a/src/bytecode.h +++ b/src/bytecode.h @@ -183,6 +183,8 @@ typedef enum { // OpenSSL (optional) OP_OPENSSL_MD5, // pops data string; pushes md5 hex string + OP_OPENSSL_SHA256, // pops data string; pushes sha256 hex string + OP_OPENSSL_SHA512, // pops data string; pushes sha512 hex string // INI (iniparser 4.2.6) optional OP_INI_LOAD, // pops path; pushes handle (>0) or 0 diff --git a/src/external/openssl.c b/src/external/openssl.c new file mode 100644 index 0000000..cbec06e --- /dev/null +++ b/src/external/openssl.c @@ -0,0 +1,130 @@ +/* +* This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2025 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + + /* + * OpenSSL integration helpers (MD5, SHA-256, SHA-512) + */ + +#ifdef FUN_WITH_OPENSSL +# include +#endif +#include + +/* Compute MD5 hex of input buffer; returns malloc'ed C string (lowercase hex). + * Caller must free(). Returns NULL on failure. When OpenSSL is disabled, + * returns an allocated empty string ("") to keep behavior consistent with + * other optional extensions. */ +static char *fun_openssl_md5_hex(const unsigned char *data, size_t len) { + static const char hexdig[] = "0123456789abcdef"; + if (!data && len != 0) return NULL; +#ifdef FUN_WITH_OPENSSL + const EVP_MD *md = EVP_md5(); + if (!md) return NULL; + int dlen = EVP_MD_get_size(md); + if (dlen <= 0) return NULL; + unsigned char *digest = (unsigned char*)malloc((size_t)dlen); + if (!digest) return NULL; + unsigned int out_len = 0; + int ok; + if (len == 0) { + // EVP_Digest handles zero-length fine as well + ok = EVP_Digest(NULL, 0, digest, &out_len, md, NULL); + } else { + ok = EVP_Digest(data, len, digest, &out_len, md, NULL); + } + if (ok != 1 || (int)out_len != dlen) { free(digest); return NULL; } + char *hex = (char*)malloc((size_t)dlen * 2 + 1); + if (!hex) { free(digest); return NULL; } + for (int i = 0; i < dlen; ++i) { + hex[2*i] = hexdig[(digest[i] >> 4) & 0xF]; + hex[2*i+1] = hexdig[digest[i] & 0xF]; + } + hex[dlen * 2] = '\0'; + free(digest); + return hex; +#else + char *hex = (char*)malloc(1); + if (hex) hex[0] = '\0'; + return hex; +#endif +} + +/* Compute SHA-256 hex of input buffer; returns malloc'ed C string (lowercase hex). + * Fallback when OpenSSL disabled: empty string. */ +static char *fun_openssl_sha256_hex(const unsigned char *data, size_t len) { + static const char hexdig[] = "0123456789abcdef"; + if (!data && len != 0) return NULL; +#ifdef FUN_WITH_OPENSSL + const EVP_MD *md = EVP_sha256(); + if (!md) return NULL; + int dlen = EVP_MD_get_size(md); + if (dlen <= 0) return NULL; + unsigned char *digest = (unsigned char*)malloc((size_t)dlen); + if (!digest) return NULL; + unsigned int out_len = 0; + int ok; + if (len == 0) { + ok = EVP_Digest(NULL, 0, digest, &out_len, md, NULL); + } else { + ok = EVP_Digest(data, len, digest, &out_len, md, NULL); + } + if (ok != 1 || (int)out_len != dlen) { free(digest); return NULL; } + char *hex = (char*)malloc((size_t)dlen * 2 + 1); + if (!hex) { free(digest); return NULL; } + for (int i = 0; i < dlen; ++i) { + hex[2*i] = hexdig[(digest[i] >> 4) & 0xF]; + hex[2*i+1] = hexdig[digest[i] & 0xF]; + } + hex[dlen * 2] = '\0'; + free(digest); + return hex; +#else + char *hex = (char*)malloc(1); + if (hex) hex[0] = '\0'; + return hex; +#endif +} + +/* Compute SHA-512 hex of input buffer; returns malloc'ed C string (lowercase hex). + * Fallback when OpenSSL disabled: empty string. */ +static char *fun_openssl_sha512_hex(const unsigned char *data, size_t len) { + static const char hexdig[] = "0123456789abcdef"; + if (!data && len != 0) return NULL; +#ifdef FUN_WITH_OPENSSL + const EVP_MD *md = EVP_sha512(); + if (!md) return NULL; + int dlen = EVP_MD_get_size(md); + if (dlen <= 0) return NULL; + unsigned char *digest = (unsigned char*)malloc((size_t)dlen); + if (!digest) return NULL; + unsigned int out_len = 0; + int ok; + if (len == 0) { + ok = EVP_Digest(NULL, 0, digest, &out_len, md, NULL); + } else { + ok = EVP_Digest(data, len, digest, &out_len, md, NULL); + } + if (ok != 1 || (int)out_len != dlen) { free(digest); return NULL; } + char *hex = (char*)malloc((size_t)dlen * 2 + 1); + if (!hex) { free(digest); return NULL; } + for (int i = 0; i < dlen; ++i) { + hex[2*i] = hexdig[(digest[i] >> 4) & 0xF]; + hex[2*i+1] = hexdig[digest[i] & 0xF]; + } + hex[dlen * 2] = '\0'; + free(digest); + return hex; +#else + char *hex = (char*)malloc(1); + if (hex) hex[0] = '\0'; + return hex; +#endif +} diff --git a/src/external/opensssl.c b/src/external/opensssl.c deleted file mode 100644 index a4fcf26..0000000 --- a/src/external/opensssl.c +++ /dev/null @@ -1,47 +0,0 @@ -/* -* This file is part of the Fun programming language. - * https://fun-lang.xyz/ - * - * Copyright 2025 Johannes Findeisen - * Licensed under the terms of the Apache-2.0 license. - * https://opensource.org/license/apache-2-0 - * - * Added: 2026-02-19 - */ - - /* - * OpenSSL integration helpers (currently MD5 only) - */ - -#ifdef FUN_WITH_OPENSSL -# include -#endif -#include - -/* Compute MD5 hex of input buffer; returns malloc'ed C string (lowercase hex). - * Caller must free(). Returns NULL on failure. When OpenSSL is disabled, - * returns an allocated empty string ("") to keep behavior consistent with - * other optional extensions. */ -static char *fun_openssl_md5_hex(const unsigned char *data, size_t len) { - static const char hexdig[] = "0123456789abcdef"; - if (!data && len != 0) return NULL; -#ifdef FUN_WITH_OPENSSL - unsigned char digest[MD5_DIGEST_LENGTH]; - MD5_CTX ctx; - if (MD5_Init(&ctx) != 1) return NULL; - if (len && MD5_Update(&ctx, data, len) != 1) return NULL; - if (MD5_Final(digest, &ctx) != 1) return NULL; - char *hex = (char*)malloc(MD5_DIGEST_LENGTH * 2 + 1); - if (!hex) return NULL; - for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) { - hex[2*i] = hexdig[(digest[i] >> 4) & 0xF]; - hex[2*i+1] = hexdig[digest[i] & 0xF]; - } - hex[MD5_DIGEST_LENGTH * 2] = '\0'; - return hex; -#else - char *hex = (char*)malloc(1); - if (hex) hex[0] = '\0'; - return hex; -#endif -} diff --git a/src/parser.c b/src/parser.c index aa16896..b27055e 100644 --- a/src/parser.c +++ b/src/parser.c @@ -1197,7 +1197,7 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos) free(name); return 1; } - /* OpenSSL (md5) */ + /* OpenSSL (md5/sha256/sha512) */ if (strcmp(name, "openssl_md5") == 0) { (*pos)++; /* '(' */ if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "openssl_md5 expects (data)"); free(name); return 0; } @@ -1206,6 +1206,22 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos) free(name); return 1; } + if (strcmp(name, "openssl_sha256") == 0) { + (*pos)++; /* '(' */ + if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "openssl_sha256 expects (data)"); free(name); return 0; } + if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "Expected ')' after openssl_sha256 arg"); free(name); return 0; } + bytecode_add_instruction(bc, OP_OPENSSL_SHA256, 0); + free(name); + return 1; + } + if (strcmp(name, "openssl_sha512") == 0) { + (*pos)++; /* '(' */ + if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "openssl_sha512 expects (data)"); free(name); return 0; } + if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "Expected ')' after openssl_sha512 arg"); free(name); return 0; } + bytecode_add_instruction(bc, OP_OPENSSL_SHA512, 0); + free(name); + return 1; + } /* PCSC builtins */ if (strcmp(name, "pcsc_establish") == 0) { (*pos)++; /* '(' */ diff --git a/src/vm.c b/src/vm.c index a64f80c..19d9181 100644 --- a/src/vm.c +++ b/src/vm.c @@ -73,7 +73,7 @@ #include "external/sqlite.c" #include "external/tcltk.c" #include "external/xml2.c" -#include "external/opensssl.c" +#include "external/openssl.c" /* forward declarations for include mapping used in error reporting */ extern char *preprocess_includes(const char *src); @@ -869,8 +869,10 @@ void vm_run(VM *vm, Bytecode *entry) { #include "vm/curl/download.c" #endif - /* OpenSSL ops (md5) */ + /* OpenSSL ops (md5/sha256/sha512) */ #include "vm/openssl/md5.c" + #include "vm/openssl/sha256.c" + #include "vm/openssl/sha512.c" /* Tk (Tcl/Tk) ops */ #ifdef FUN_WITH_TCLTK diff --git a/src/vm/openssl/sha256.c b/src/vm/openssl/sha256.c new file mode 100644 index 0000000..bed86f0 --- /dev/null +++ b/src/vm/openssl/sha256.c @@ -0,0 +1,16 @@ +/** + * OpenSSL SHA-256 builtin + */ +case OP_OPENSSL_SHA256: { + Value vdata = pop_value(vm); + char *s = value_to_string_alloc(&vdata); + free_value(vdata); + if (!s) { push_value(vm, make_string("")); break; } + char *hex = fun_openssl_sha256_hex((const unsigned char*)s, strlen(s)); + free(s); + if (!hex) { push_value(vm, make_string("")); break; } + Value out = make_string(hex); + free(hex); + push_value(vm, out); + break; +} diff --git a/src/vm/openssl/sha512.c b/src/vm/openssl/sha512.c new file mode 100644 index 0000000..2e091b1 --- /dev/null +++ b/src/vm/openssl/sha512.c @@ -0,0 +1,16 @@ +/** + * OpenSSL SHA-512 builtin + */ +case OP_OPENSSL_SHA512: { + Value vdata = pop_value(vm); + char *s = value_to_string_alloc(&vdata); + free_value(vdata); + if (!s) { push_value(vm, make_string("")); break; } + char *hex = fun_openssl_sha512_hex((const unsigned char*)s, strlen(s)); + free(s); + if (!hex) { push_value(vm, make_string("")); break; } + Value out = make_string(hex); + free(hex); + push_value(vm, out); + break; +} From 6fa95f0d470b8fe1cf0a807717dd9ec807ff3335 Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 19 Feb 2026 14:19:17 +0100 Subject: [PATCH 33/39] Added OpenSSL RIPEMD-160 fun. (0.38.14) --- docs/examples.md | 1 + docs/external/README.md | 2 +- docs/external/openssl.md | 11 +++++-- docs/opcodes.md | 1 + examples/crypto/openssl_md5.fun | 2 +- examples/crypto/openssl_ripemd160.fun | 28 +++++++++++++++++ src/bytecode.c | 1 + src/bytecode.h | 1 + src/external/openssl.c | 44 +++++++++++++++++++++++++-- src/parser.c | 8 +++++ src/vm.c | 3 +- src/vm/openssl/md5.c | 13 +++++++- src/vm/openssl/ripemd160.c | 16 ++++++++++ src/vm/openssl/sha256.c | 11 +++++++ src/vm/openssl/sha512.c | 11 +++++++ 15 files changed, 144 insertions(+), 9 deletions(-) create mode 100644 examples/crypto/openssl_ripemd160.fun create mode 100644 src/vm/openssl/ripemd160.c diff --git a/docs/examples.md b/docs/examples.md index abd6614..93a792c 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -45,6 +45,7 @@ FUN_LIB_DIR="$(pwd)/lib" fun examples/crypto/openssl_md5.fun Browse the `examples/` tree for areas of interest: - crypto — crypto demonstrations (e.g., OpenSSL MD5/SHA-256/SHA-512 helpers; requires build with `-DFUN_WITH_OPENSSL=ON`) + - crypto — crypto demonstrations (e.g., OpenSSL MD5/SHA-256/SHA-512/RIPEMD‑160 helpers; requires build with `-DFUN_WITH_OPENSSL=ON`) - blocking / interactive — I/O or user-interactive patterns - error / broken — negative tests and error showcases - math — numeric operations diff --git a/docs/external/README.md b/docs/external/README.md index 8f3391e..15950cb 100644 --- a/docs/external/README.md +++ b/docs/external/README.md @@ -18,7 +18,7 @@ Extensions: - [PC/SC (Smart cards)](./pcsc.md) - [Notcurses (TUI)](./notcurses.md) - [Tcl/Tk (GUI)](./tcltk.md) -- [OpenSSL (MD5 helper)](./openssl.md) +- [OpenSSL](./openssl.md) Notes: - These integrations are optional; the VM compiles without them. diff --git a/docs/external/openssl.md b/docs/external/openssl.md index c0a743b..7606280 100644 --- a/docs/external/openssl.md +++ b/docs/external/openssl.md @@ -1,7 +1,7 @@ # OpenSSL extension (optional) - CMake option: FUN_WITH_OPENSSL=ON -- Purpose: provide small crypto helpers backed by OpenSSL. Includes md5, sha256, sha512 helpers. +- Purpose: provide small crypto helpers backed by OpenSSL. Includes md5, sha256, sha512, ripemd160 helpers. - Homepage: https://www.openssl.org/ Build notes: @@ -12,7 +12,8 @@ Provided helper/opcodes: - Function: openssl_md5(data:string) -> string (lowercase hex). Falls back to empty string when the extension is disabled, mirroring other optional modules. - Function: openssl_sha256(data:string) -> string (lowercase hex). - Function: openssl_sha512(data:string) -> string (lowercase hex). -- Opcodes: OP_OPENSSL_MD5, OP_OPENSSL_SHA256, OP_OPENSSL_SHA512 (internal mappings for the functions above). +- Function: openssl_ripemd160(data:string) -> string (lowercase hex). Note: On OpenSSL 3.x this may require the legacy provider; if the digest is unavailable, the helper returns an empty string. +- Opcodes: OP_OPENSSL_MD5, OP_OPENSSL_SHA256, OP_OPENSSL_SHA512, OP_OPENSSL_RIPEMD160 (internal mappings for the functions above). Quickstart: - Configure: cmake -S . -B build -DFUN_WITH_OPENSSL=ON @@ -21,6 +22,7 @@ Quickstart: - ./build/fun examples/crypto/openssl_md5.fun - ./build/fun examples/crypto/openssl_sha256.fun - ./build/fun examples/crypto/openssl_sha512.fun + - ./build/fun examples/crypto/openssl_ripemd160.fun Example output: - md5(abc) = 900150983cd24fb0d6963f7d28e17f72 @@ -29,3 +31,8 @@ Example output: - sha256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 - sha512(abc) = ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f - sha512("") = cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e + - ripemd160(abc) = 8eb208f7e05d987a9b044a8e98c6b087f15a0bfc + - ripemd160("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31 + +Notes: +- The OpenSSL 3.x provider configuration on your system determines availability of RIPEMD‑160. If the legacy provider is not enabled, openssl_ripemd160() will return an empty string. diff --git a/docs/opcodes.md b/docs/opcodes.md index 5ea6c86..47e2b01 100644 --- a/docs/opcodes.md +++ b/docs/opcodes.md @@ -207,6 +207,7 @@ This document provides an overview of the available VM opcodes implemented under - OP_OPENSSL_MD5: Compute MD5 digest and return lowercase hex string; pops data:string; pushes md5:string. - OP_OPENSSL_SHA256: Compute SHA‑256 digest and return lowercase hex string; pops data:string; pushes sha256:string. - OP_OPENSSL_SHA512: Compute SHA‑512 digest and return lowercase hex string; pops data:string; pushes sha512:string. + - OP_OPENSSL_RIPEMD160: Compute RIPEMD‑160 digest and return lowercase hex string; pops data:string; pushes ripemd160:string. On OpenSSL 3.x this may require the legacy provider; if unavailable, the helper returns an empty string. - Requires building with `-DFUN_WITH_OPENSSL=ON`. When disabled, these opcodes still exist but return an empty string to match other optional extensions’ fallback behavior. ## PCRE2 (Regex) diff --git a/examples/crypto/openssl_md5.fun b/examples/crypto/openssl_md5.fun index 7002721..63f906b 100644 --- a/examples/crypto/openssl_md5.fun +++ b/examples/crypto/openssl_md5.fun @@ -4,7 +4,7 @@ * This file is part of the Fun programming language. * https://fun-lang.xyz/ * - * Copyright 2025 Johannes Findeisen + * Copyright 2026 Johannes Findeisen * Licensed under the terms of the Apache-2.0 license. * https://opensource.org/license/apache-2-0 * diff --git a/examples/crypto/openssl_ripemd160.fun b/examples/crypto/openssl_ripemd160.fun new file mode 100644 index 0000000..65d0f85 --- /dev/null +++ b/examples/crypto/openssl_ripemd160.fun @@ -0,0 +1,28 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +// OpenSSL RIPEMD-160 example +// Enable with -DFUN_WITH_OPENSSL=ON during build for real hashing. + +s = "abc" +d = openssl_ripemd160(s) +print("ripemd160(abc) = " + d) + +// Another quick check (empty string) +e = "" +print("ripemd160(\"\") = " + openssl_ripemd160(e)) + +/* Expected output (if RIPEMD-160 is available in your OpenSSL build): +ripemd160(abc) = 8eb208f7e05d987a9b044a8e98c6b087f15a0bfc +ripemd160("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31 +*/ diff --git a/src/bytecode.c b/src/bytecode.c index caf6029..405e6b7 100644 --- a/src/bytecode.c +++ b/src/bytecode.c @@ -172,6 +172,7 @@ static const char *opcode_name(OpCode op) { case OP_OPENSSL_MD5: return "OPENSSL_MD5"; case OP_OPENSSL_SHA256: return "OPENSSL_SHA256"; case OP_OPENSSL_SHA512: return "OPENSSL_SHA512"; + case OP_OPENSSL_RIPEMD160: return "OPENSSL_RIPEMD160"; case OP_INI_LOAD: return "INI_LOAD"; case OP_INI_FREE: return "INI_FREE"; case OP_INI_GET_STRING: return "INI_GET_STRING"; diff --git a/src/bytecode.h b/src/bytecode.h index 446dd21..5f89650 100644 --- a/src/bytecode.h +++ b/src/bytecode.h @@ -185,6 +185,7 @@ typedef enum { OP_OPENSSL_MD5, // pops data string; pushes md5 hex string OP_OPENSSL_SHA256, // pops data string; pushes sha256 hex string OP_OPENSSL_SHA512, // pops data string; pushes sha512 hex string + OP_OPENSSL_RIPEMD160, // pops data string; pushes ripemd160 hex string // INI (iniparser 4.2.6) optional OP_INI_LOAD, // pops path; pushes handle (>0) or 0 diff --git a/src/external/openssl.c b/src/external/openssl.c index cbec06e..810e430 100644 --- a/src/external/openssl.c +++ b/src/external/openssl.c @@ -2,7 +2,7 @@ * This file is part of the Fun programming language. * https://fun-lang.xyz/ * - * Copyright 2025 Johannes Findeisen + * Copyright 2026 Johannes Findeisen * Licensed under the terms of the Apache-2.0 license. * https://opensource.org/license/apache-2-0 * @@ -10,11 +10,11 @@ */ /* - * OpenSSL integration helpers (MD5, SHA-256, SHA-512) + * OpenSSL integration helpers (MD5, RIPEMD-160, SHA-256, SHA-512) */ #ifdef FUN_WITH_OPENSSL -# include +#include #endif #include @@ -128,3 +128,41 @@ static char *fun_openssl_sha512_hex(const unsigned char *data, size_t len) { return hex; #endif } + +/* Compute RIPEMD-160 hex of input buffer; returns malloc'ed C string (lowercase hex). + * Note: On OpenSSL 3.x, RIPEMD160 may require the legacy provider; if unavailable, + * EVP_ripemd160() can return NULL. In that case we return NULL and the VM opcode + * will fall back to empty string behavior. When OpenSSL is disabled, return empty string. */ +static char *fun_openssl_ripemd160_hex(const unsigned char *data, size_t len) { + static const char hexdig[] = "0123456789abcdef"; + if (!data && len != 0) return NULL; +#ifdef FUN_WITH_OPENSSL + const EVP_MD *md = EVP_ripemd160(); + if (!md) return NULL; + int dlen = EVP_MD_get_size(md); + if (dlen <= 0) return NULL; + unsigned char *digest = (unsigned char*)malloc((size_t)dlen); + if (!digest) return NULL; + unsigned int out_len = 0; + int ok; + if (len == 0) { + ok = EVP_Digest(NULL, 0, digest, &out_len, md, NULL); + } else { + ok = EVP_Digest(data, len, digest, &out_len, md, NULL); + } + if (ok != 1 || (int)out_len != dlen) { free(digest); return NULL; } + char *hex = (char*)malloc((size_t)dlen * 2 + 1); + if (!hex) { free(digest); return NULL; } + for (int i = 0; i < dlen; ++i) { + hex[2*i] = hexdig[(digest[i] >> 4) & 0xF]; + hex[2*i+1] = hexdig[digest[i] & 0xF]; + } + hex[dlen * 2] = '\0'; + free(digest); + return hex; +#else + char *hex = (char*)malloc(1); + if (hex) hex[0] = '\0'; + return hex; +#endif +} diff --git a/src/parser.c b/src/parser.c index b27055e..faa2944 100644 --- a/src/parser.c +++ b/src/parser.c @@ -1222,6 +1222,14 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos) free(name); return 1; } + if (strcmp(name, "openssl_ripemd160") == 0) { + (*pos)++; /* '(' */ + if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "openssl_ripemd160 expects (data)"); free(name); return 0; } + if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "Expected ')' after openssl_ripemd160 arg"); free(name); return 0; } + bytecode_add_instruction(bc, OP_OPENSSL_RIPEMD160, 0); + free(name); + return 1; + } /* PCSC builtins */ if (strcmp(name, "pcsc_establish") == 0) { (*pos)++; /* '(' */ diff --git a/src/vm.c b/src/vm.c index 19d9181..eb9af8d 100644 --- a/src/vm.c +++ b/src/vm.c @@ -869,10 +869,11 @@ void vm_run(VM *vm, Bytecode *entry) { #include "vm/curl/download.c" #endif - /* OpenSSL ops (md5/sha256/sha512) */ + /* OpenSSL ops (md5/sha256/sha512/ripemd160) */ #include "vm/openssl/md5.c" #include "vm/openssl/sha256.c" #include "vm/openssl/sha512.c" + #include "vm/openssl/ripemd160.c" /* Tk (Tcl/Tk) ops */ #ifdef FUN_WITH_TCLTK diff --git a/src/vm/openssl/md5.c b/src/vm/openssl/md5.c index 473605d..a741dd3 100644 --- a/src/vm/openssl/md5.c +++ b/src/vm/openssl/md5.c @@ -1,4 +1,15 @@ -/** +/* +* This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + + /** * OpenSSL MD5 builtin */ case OP_OPENSSL_MD5: { diff --git a/src/vm/openssl/ripemd160.c b/src/vm/openssl/ripemd160.c new file mode 100644 index 0000000..2fc7b77 --- /dev/null +++ b/src/vm/openssl/ripemd160.c @@ -0,0 +1,16 @@ +/* + * OpenSSL RIPEMD-160 builtin + */ +case OP_OPENSSL_RIPEMD160: { + Value vdata = pop_value(vm); + char *s = value_to_string_alloc(&vdata); + free_value(vdata); + if (!s) { push_value(vm, make_string("")); break; } + char *hex = fun_openssl_ripemd160_hex((const unsigned char*)s, strlen(s)); + free(s); + if (!hex) { push_value(vm, make_string("")); break; } + Value out = make_string(hex); + free(hex); + push_value(vm, out); + break; +} diff --git a/src/vm/openssl/sha256.c b/src/vm/openssl/sha256.c index bed86f0..342fbd7 100644 --- a/src/vm/openssl/sha256.c +++ b/src/vm/openssl/sha256.c @@ -1,3 +1,14 @@ +/* +* This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + /** * OpenSSL SHA-256 builtin */ diff --git a/src/vm/openssl/sha512.c b/src/vm/openssl/sha512.c index 2e091b1..63c71fa 100644 --- a/src/vm/openssl/sha512.c +++ b/src/vm/openssl/sha512.c @@ -1,3 +1,14 @@ +/* +* This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + /** * OpenSSL SHA-512 builtin */ From cb5e61c0912b59f9df7df8dca372855da8fb62a9 Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 19 Feb 2026 14:23:00 +0100 Subject: [PATCH 34/39] Just cosmetic changes. (0.38.14) --- CMakeLists.txt | 2 +- src/vm/openssl/md5.c | 2 +- src/vm/openssl/ripemd160.c | 11 +++++++++++ src/vm/openssl/sha256.c | 2 +- src/vm/openssl/sha512.c | 2 +- 5 files changed, 15 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a5a8aba..00ad1d4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.13 LANGUAGES C) +project(fun VERSION 0.38.14 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) diff --git a/src/vm/openssl/md5.c b/src/vm/openssl/md5.c index a741dd3..abc549f 100644 --- a/src/vm/openssl/md5.c +++ b/src/vm/openssl/md5.c @@ -1,5 +1,5 @@ /* -* This file is part of the Fun programming language. + * This file is part of the Fun programming language. * https://fun-lang.xyz/ * * Copyright 2026 Johannes Findeisen diff --git a/src/vm/openssl/ripemd160.c b/src/vm/openssl/ripemd160.c index 2fc7b77..3831048 100644 --- a/src/vm/openssl/ripemd160.c +++ b/src/vm/openssl/ripemd160.c @@ -1,4 +1,15 @@ /* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + + /* * OpenSSL RIPEMD-160 builtin */ case OP_OPENSSL_RIPEMD160: { diff --git a/src/vm/openssl/sha256.c b/src/vm/openssl/sha256.c index 342fbd7..90ed330 100644 --- a/src/vm/openssl/sha256.c +++ b/src/vm/openssl/sha256.c @@ -1,5 +1,5 @@ /* -* This file is part of the Fun programming language. + * This file is part of the Fun programming language. * https://fun-lang.xyz/ * * Copyright 2026 Johannes Findeisen diff --git a/src/vm/openssl/sha512.c b/src/vm/openssl/sha512.c index 63c71fa..c004820 100644 --- a/src/vm/openssl/sha512.c +++ b/src/vm/openssl/sha512.c @@ -1,5 +1,5 @@ /* -* This file is part of the Fun programming language. + * This file is part of the Fun programming language. * https://fun-lang.xyz/ * * Copyright 2026 Johannes Findeisen From 9016b207b8d558aca4a86c72be23f53216832f87 Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 19 Feb 2026 21:50:24 +0100 Subject: [PATCH 35/39] Some more stdlib fun and example code and cosmetic changes. (0.38.15) --- CMakeLists.txt | 2 +- docs/style-guide.md | 39 +++++++++++++- docs/testing.md | 5 +- examples/crypto/openssl_md5.fun | 0 examples/crypto/openssl_ripemd160.fun | 0 examples/crypto/openssl_sha256.fun | 0 examples/crypto/openssl_sha512.fun | 0 examples/error_handling.fun | 64 +++++++++++++++++++++++ examples/match.fun | 43 ++++++++++++++++ lib/utils/match.fun | 36 +++++++++++++ lib/utils/option.fun | 71 +++++++++++++++++++++++++ lib/utils/result.fun | 74 +++++++++++++++++++++++++++ 12 files changed, 330 insertions(+), 4 deletions(-) mode change 100644 => 100755 examples/crypto/openssl_md5.fun mode change 100644 => 100755 examples/crypto/openssl_ripemd160.fun mode change 100644 => 100755 examples/crypto/openssl_sha256.fun mode change 100644 => 100755 examples/crypto/openssl_sha512.fun create mode 100755 examples/error_handling.fun create mode 100755 examples/match.fun create mode 100644 lib/utils/match.fun create mode 100644 lib/utils/option.fun create mode 100644 lib/utils/result.fun diff --git a/CMakeLists.txt b/CMakeLists.txt index 00ad1d4..e0e52fe 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.14 LANGUAGES C) +project(fun VERSION 0.38.15 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) diff --git a/docs/style-guide.md b/docs/style-guide.md index 5c97cc9..b2f1645 100644 --- a/docs/style-guide.md +++ b/docs/style-guide.md @@ -3,23 +3,60 @@ Conventions for writing C and Fun code in this repository. ## General principles + - Two-space indentation. No tabs. - Keep lines reasonably short (~100 cols). Wrap thoughtfully. - Prefer explicit over implicit; favor clarity. ## C (C99) -- Indentation: two spaces, K&R-ish braces. + +- Indentation: four spaces, K&R-ish braces. - Naming: `snake_case` for functions and variables; `CAPS_SNAKE` for macros. - Error handling: return error codes or booleans; avoid hidden globals. - Headers: minimize includes in headers; forward-declare where practical. - Memory: clearly document ownership; free what you allocate. ## Fun language + - Indentation: two spaces. - Naming: `snake_case` for functions/variables; `PascalCase` for classes/constructors. - Modules: one primary concept per file; export a minimal, cohesive API. - Idioms: prefer arrays and maps over ad-hoc structures; keep functions small. ## Formatting and tools + - No auto-formatters required; follow these simple rules. - Keep diffs small and focused; avoid reformat-only commits. + +## Additional details (merged from legacy MVP draft) + +This section consolidates practical guidelines that were previously kept in docs/style_guide.md. + +1. Files and headers +- Keep the standard header block with license and date when editing stdlib files. + +2. Naming +- Functions and variables: snake_case (e.g., parse_int, is_some). +- Classes: PascalCase (e.g., DateTime). +- Constants: ALL_CAPS when truly constant. + +3. Layout +- Indent with two spaces; no tabs. +- One statement per line; no trailing spaces. +- Use blank lines sparingly to separate logical blocks. + +4. Comments +- Line comments with //; block comments with /* ... */ for file headers and longer notes. + +5. Collections +- Prefer [] for arrays and {"key": value} for dictionaries; use has_key() before subscripting unknown keys. + +6. Error handling +- Prefer Result and Option helpers from lib/utils over ad-hoc nil checks. +- Avoid unwrap() in library code; propagate errors using and_then()/or_else() patterns. + +7. Examples +- Keep examples executable via shebang: #!/usr/bin/env fun +- Print informative labels for outputs. + +This guide will evolve. Contributions and suggestions are welcome. diff --git a/docs/testing.md b/docs/testing.md index acb140b..8e754aa 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -25,7 +25,7 @@ Release profile example: ``` cmake --build build_release --target test_opcodes && ./build/test_opcodes -``> +``` If `fun_test` exists in your configuration: @@ -45,7 +45,8 @@ ctest --test-dir build -j - C/C++/VM-side tests: look for existing tests under `src` or `spec` and mirror the structure. Add a new source and register it in CMake with an executable or via `add_test()`. - Fun-level examples as tests: minimal scripts under `examples/` can act as smoke tests and are runnable via `./play.fun`. Consider adding a new example for new features and have CI invoke a subset. -Guidelines: +### Guidelines: + - Keep each test focused; prefer several small tests over one monolith. - Avoid nondeterminism; set seeds where randomness is involved. - Make tests independent of the working directory unless the behavior under test is precisely path resolution. diff --git a/examples/crypto/openssl_md5.fun b/examples/crypto/openssl_md5.fun old mode 100644 new mode 100755 diff --git a/examples/crypto/openssl_ripemd160.fun b/examples/crypto/openssl_ripemd160.fun old mode 100644 new mode 100755 diff --git a/examples/crypto/openssl_sha256.fun b/examples/crypto/openssl_sha256.fun old mode 100644 new mode 100755 diff --git a/examples/crypto/openssl_sha512.fun b/examples/crypto/openssl_sha512.fun old mode 100644 new mode 100755 diff --git a/examples/error_handling.fun b/examples/error_handling.fun new file mode 100755 index 0000000..9b6ab38 --- /dev/null +++ b/examples/error_handling.fun @@ -0,0 +1,64 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +/* + * Error handling examples using Result and Option helpers. + */ + +#include +#include + +// Simulate a fallible parse +fun parse_int(s) + if regex_match("^[+-]?[0-9]+$", s) + return ok(to_number(s)) + return err("invalid integer: " + s) + +// Divide two integers, handling division by zero +fun safe_div(a, b) + if b == 0 + return err("division by zero") + return ok(a / b) + +// Option example: get environment variable +fun get_env_opt(name) + v = env(name) + if v == nil + return none() + if v == "" + return none() + return some(v) + +print("-- Result examples --") +r = parse_int("123") +print("parse_int 123 ok? " + to_string(is_ok(r)) + ", value: " + to_string(unwrap_or(r, -1))) + +q = parse_int("x12") +print("parse_int x12 ok? " + to_string(is_ok(q)) + ", or default 0: " + to_string(unwrap_or(q, 0))) + +print("chained and_then: '10' / '2'") +// Simpler explicit flow without nested anonymous functions +a = parse_int("10") +b = parse_int("2") +if is_ok(a) && is_ok(b) + res = safe_div(unwrap(a), unwrap(b)) +else + if is_err(a) + res = a + else + res = b +print("=> ok? " + to_string(is_ok(res)) + ", value: " + to_string(unwrap_or(res, -1))) + +print("-- Option examples --") +home = get_env_opt("HOME") +print("HOME is set? " + to_string(is_some(home)) + ", value: " + to_string(unwrap_or(home, ""))) diff --git a/examples/match.fun b/examples/match.fun new file mode 100755 index 0000000..aedbfb5 --- /dev/null +++ b/examples/match.fun @@ -0,0 +1,43 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +/* + * Demonstrates dynamic match() helper. + */ + +#include + +print("-- match-like with numbers --") +x = 0 +if (x == -1) + print("minus one") +else if (x == 0) + print("zero") +else if (x > 0) + print("positive: " + to_string(x)) +else + print("negative: " + to_string(x)) + +print("-- match-like with Option --") +o1 = some(42) +o2 = none() + +if is_some(o1) + print("Some(" + to_string(unwrap(o1)) + ")") +else + print("None") + +if is_some(o2) + print("Some(" + to_string(unwrap(o2)) + ")") +else + print("None") diff --git a/lib/utils/match.fun b/lib/utils/match.fun new file mode 100644 index 0000000..51cdf51 --- /dev/null +++ b/lib/utils/match.fun @@ -0,0 +1,36 @@ +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +// A simple dynamic match helper. +// Usage: +// match(x, [ +// {"when": fun(v) v > 0, "then": fun(v) print("pos")}, +// {"is": 0, "then": fun(v) print("zero")}, +// {"else": fun(v) print("neg or other")} +// ]) + +fun match(value, cases) + // Iterate cases in order; support keys: is, when, else + for c in cases + if (has_key(c, "is")) + if (value == c["is"]) + th = c["then"] + return th(value) + else if (has_key(c, "when")) + pred = c["when"] + if (pred(value)) + th = c["then"] + return th(value) + else if (has_key(c, "else")) + el = c["else"] + return el(value) + // No match; return nil + return nil diff --git a/lib/utils/option.fun b/lib/utils/option.fun new file mode 100644 index 0000000..74e35f5 --- /dev/null +++ b/lib/utils/option.fun @@ -0,0 +1,71 @@ +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +// Option helpers for ergonomic error-absent values. +// Represented as dictionaries with a _tag and optional value field. + +// Constructors +fun some(x) + return {"_tag": "Some", "value": x} + +fun none() + return {"_tag": "None"} + +// Predicates +fun is_some(opt) + return opt["_tag"] == "Some" + +fun is_none(opt) + return opt["_tag"] == "None" + +// Extractors +fun unwrap(opt) + if is_some(opt) + return opt["value"] + // Fall back to raising a runtime error + error("called unwrap() on None") + return nil + +fun unwrap_or(opt, default) + if is_some(opt) + return opt["value"] + return default + +// Functional helpers +// map(opt, f) -> Some(f(value)) or None +fun option_map(opt, f) + if is_some(opt) + return some(f(opt["value"])) + return none() + +// and_then(opt, f) where f: a -> Option[b] +fun and_then(opt, f) + if is_some(opt) + return f(opt["value"]) + return none() + +// or_else(opt, f) where f: () -> Option[a] +fun or_else(opt, f) + if is_some(opt) + return opt + return f() + +// to_result(opt, err) +fun to_result(opt, err) + if is_some(opt) + return ok(opt["value"]) + return err(err) + +// Convenience: try_get(dict, key) -> Option[value] +fun try_get(dict, key) + if has_key(dict, key) + return some(dict[key]) + return none() diff --git a/lib/utils/result.fun b/lib/utils/result.fun new file mode 100644 index 0000000..f834517 --- /dev/null +++ b/lib/utils/result.fun @@ -0,0 +1,74 @@ +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +// Result helpers: Ok(value) or Err(error) + +// Constructors +fun ok(x) + return {"_tag": "Ok", "value": x} + +fun err(e) + return {"_tag": "Err", "error": e} + +// Predicates +fun is_ok(res) + return res["_tag"] == "Ok" + +fun is_err(res) + return res["_tag"] == "Err" + +// Extractors +fun unwrap(res) + if is_ok(res) + return res["value"] + error("called unwrap() on Err: " + to_string(res["error"])) + return nil + +fun unwrap_or(res, default) + if is_ok(res) + return res["value"] + return default + +fun unwrap_err(res) + if is_err(res) + return res["error"] + error("called unwrap_err() on Ok") + return nil + +// map(res, f) applies f to Ok value; Err passes through +fun result_map(res, f) + if is_ok(res) + return ok(f(res["value"])) + return res + +// map_err(res, f) applies f to error; Ok passes through +fun map_err(res, f) + if is_err(res) + return err(f(res["error"])) + return res + +// and_then(res, f) where f: a -> Result[b] +fun and_then(res, f) + if is_ok(res) + return f(res["value"]) // caller should return Result + return res + +// or_else(res, f) where f: () -> Result[a] +fun or_else(res, f) + if is_ok(res) + return res + return f() + +// to_option(res) -> Some(value) or None +fun to_option(res) + if is_ok(res) + return some(res["value"]) // requires option.fun loaded + return none() From d1d4adbf2cba0911d11cffbf78fff73bda77fb80 Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 19 Feb 2026 22:00:34 +0100 Subject: [PATCH 36/39] Added missing docs/build.md. (0.38.15) --- docs/build.md | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 docs/build.md diff --git a/docs/build.md b/docs/build.md new file mode 100644 index 0000000..0a45457 --- /dev/null +++ b/docs/build.md @@ -0,0 +1,71 @@ +# Building Fun + +This guide describes how to build Fun from source using CMake and the available build options. + +## Prerequisites +- A C compiler with C99 support +- CMake 3.20+ (or newer) +- Optional: Rust toolchain with cargo (required when building with `FUN_WITH_RUST=ON`) + +## Common targets +- `build` - aggregate target that depends on `fun`, `fun_test`, and `test_opcodes` +- `fun` - the CLI executable +- `fun_test` - unit/feature tests (run with CTest) +- `test_opcodes` - opcode tests (executable) + +These targets are defined by the project; use your configured CMake build directory/profile. + +## Build options +Fun exposes several options you can toggle at configure time: + +- `FUN_DEBUG` (ON/OFF) - Enables extra assertions and logging in the VM and runtime +- `FUN_USE_MUSL` (ON/OFF) - Link against musl for static/portable builds (Linux) +- `FUN_WITH_CPP` (ON/OFF) - Enable C++-based opcode/examples support +- `FUN_WITH_RUST` (ON/OFF) - Build and link Rust staticlib from `src/rust/` +- `FUN_WITH_OPENSSL` (ON/OFF) - Enable OpenSSL-backed helpers (MD5/SHA-256/SHA-512/RIPEMD-160) + +When configuring, the build prints a summary like: + +``` +==== Fun build options ==== + FUN_DEBUG: ENABLED|DISABLED + FUN_USE_MUSL: ENABLED|DISABLED + FUN_WITH_CPP: ENABLED|DISABLED + FUN_WITH_RUST: ENABLED|DISABLED +=========================== +``` + +## Example commands +Use the CLion-provided build directories or your own. Typical invocations: + +### Debug +``` +cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug \ + -DFUN_DEBUG=ON -DFUN_WITH_RUST=OFF +cmake --build build --target build +``` + +### Release +``` +cmake -S . -B build_release -DCMAKE_BUILD_TYPE=Release \ + -DFUN_DEBUG=OFF -DFUN_WITH_RUST=OFF +cmake --build build_release --target build +``` + +### Enabling optional extensions +``` +cmake -S . -B build_release -DCMAKE_BUILD_TYPE=Release \ + -DFUN_WITH_CPP=ON -DFUN_WITH_RUST=ON -DFUN_WITH_OPENSSL=ON +cmake --build build_release --target build +``` + +If `FUN_WITH_RUST` is enabled, ensure `cargo` is available in PATH; the build will invoke it and link the produced static library. + +If `FUN_WITH_OPENSSL` is enabled, CMake must detect your system OpenSSL. Hash helpers use the EVP interface (OpenSSL 3-compatible). Note: RIPEMD-160 may require the legacy provider on OpenSSL 3.x; if unavailable, the helper returns an empty string. + +## Running +- CLI: run the `fun` executable from your build directory. +- REPL: `fun -i` or just run `fun` without a script, depending on your CLI version (see [cli.md](./cli.md)). +- Examples: see [examples.md](./examples.md). + +Tip: When running from the repository without installation, set `FUN_LIB_DIR` to the local `./lib` so includes can find the stdlib. From 3e0d47a268fab8b34dbfc9228ba188713d48e298 Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 19 Feb 2026 23:33:00 +0100 Subject: [PATCH 37/39] Added LibreSSL as an alternative to OpenSSL. Needs more testing! (0.38.16) --- CMakeLists.txt | 2 +- cmake/Extensions/Extensions.cmake | 2 + cmake/Extensions/LIBRESSL.cmake | 100 ++++++++++++++ cmake/Targets.cmake | 9 +- docs/README.md | 8 +- docs/build.md | 5 +- docs/external/README.md | 6 +- docs/external/curl.md | 6 +- docs/external/ini.md | 6 +- docs/external/json.md | 6 +- docs/external/libressl.md | 45 +++++++ docs/external/libsql.md | 6 +- docs/external/notcurses.md | 6 +- docs/external/openssl.md | 19 ++- docs/external/pcre2.md | 6 +- docs/external/pcsc.md | 6 +- docs/external/sqlite.md | 6 +- docs/external/tcltk.md | 9 +- docs/external/xml2.md | 6 +- docs/internals.md | 4 +- examples/crypto/libressl_md5.fun | 28 ++++ examples/crypto/libressl_ripemd160.fun | 28 ++++ examples/crypto/libressl_sha256.fun | 28 ++++ examples/crypto/libressl_sha512.fun | 28 ++++ make | 1 + src/bytecode.c | 4 + src/bytecode.h | 6 + src/external/libressl.c | 172 +++++++++++++++++++++++++ src/external/openssl.c | 5 + src/parser.c | 33 +++++ src/vm.c | 11 ++ src/vm/libressl/md5.c | 27 ++++ src/vm/libressl/ripemd160.c | 27 ++++ src/vm/libressl/sha256.c | 27 ++++ src/vm/libressl/sha512.c | 27 ++++ 35 files changed, 677 insertions(+), 38 deletions(-) create mode 100644 cmake/Extensions/LIBRESSL.cmake create mode 100644 docs/external/libressl.md create mode 100644 examples/crypto/libressl_md5.fun create mode 100644 examples/crypto/libressl_ripemd160.fun create mode 100644 examples/crypto/libressl_sha256.fun create mode 100644 examples/crypto/libressl_sha512.fun create mode 100644 src/external/libressl.c create mode 100644 src/vm/libressl/md5.c create mode 100644 src/vm/libressl/ripemd160.c create mode 100644 src/vm/libressl/sha256.c create mode 100644 src/vm/libressl/sha512.c diff --git a/CMakeLists.txt b/CMakeLists.txt index e0e52fe..a935d11 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10) -project(fun VERSION 0.38.15 LANGUAGES C) +project(fun VERSION 0.38.16 LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) diff --git a/cmake/Extensions/Extensions.cmake b/cmake/Extensions/Extensions.cmake index b16333b..92843b6 100644 --- a/cmake/Extensions/Extensions.cmake +++ b/cmake/Extensions/Extensions.cmake @@ -23,6 +23,7 @@ include(${CMAKE_SOURCE_DIR}/cmake/Extensions/CURL.cmake) include(${CMAKE_SOURCE_DIR}/cmake/Extensions/NOTCURSES.cmake) include(${CMAKE_SOURCE_DIR}/cmake/Extensions/REPL.cmake) include(${CMAKE_SOURCE_DIR}/cmake/Extensions/OPENSSL.cmake) +include(${CMAKE_SOURCE_DIR}/cmake/Extensions/LIBRESSL.cmake) # Summary of extension toggles message(STATUS "---- Fun extension summary ----") @@ -38,4 +39,5 @@ _fun_print_feature("libcurl (FUN_WITH_CURL)" FUN_WITH_CURL) _fun_print_feature("Notcurses (FUN_WITH_NOTCURSES)" FUN_WITH_NOTCURSES) _fun_print_feature("REPL (FUN_WITH_REPL)" FUN_WITH_REPL) _fun_print_feature("OpenSSL (FUN_WITH_OPENSSL)" FUN_WITH_OPENSSL) +_fun_print_feature("LibreSSL (FUN_WITH_LIBRESSL)" FUN_WITH_LIBRESSL) message(STATUS "--------------------------------") diff --git a/cmake/Extensions/LIBRESSL.cmake b/cmake/Extensions/LIBRESSL.cmake new file mode 100644 index 0000000..2e82f8d --- /dev/null +++ b/cmake/Extensions/LIBRESSL.cmake @@ -0,0 +1,100 @@ +## LibreSSL optional integration (MD5, etc.) + +option(FUN_WITH_LIBRESSL "Enable LibreSSL-based features (e.g., md5)" OFF) + +set(LIBRESSL_INCLUDE_DIRS "") +set(LIBRESSL_LINK_LIBS "") + +if(FUN_WITH_LIBRESSL) + # We must NOT depend on OpenSSL being installed. Detect LibreSSL directly. + # Strategy (in order): + # 1) Prefer pkg-config 'libressl' if available (brings ssl+crypto and headers) + # 2) Else, prefer explicit LibreSSL include prefix (/usr/include/libressl) + # 3) Else, fall back to generic OpenSSL-compatible headers, but only if they + # are provided by LibreSSL (detected heuristically via opensslv.h content) + # 4) Link against libcrypto (from LibreSSL). No OpenSSL::Crypto usage. + + include(CheckIncludeFile) + include(FindPkgConfig) + + set(_libressl_found FALSE) + + # 1) Try pkg-config: libressl (meta) or libtls (often implies LibreSSL presence) + if(PKG_CONFIG_FOUND) + pkg_check_modules(LIBRESSL_PKG QUIET libressl) + if(LIBRESSL_PKG_FOUND) + list(APPEND LIBRESSL_INCLUDE_DIRS ${LIBRESSL_PKG_INCLUDE_DIRS}) + list(APPEND LIBRESSL_LINK_LIBS ${LIBRESSL_PKG_LIBRARIES}) + set(_libressl_found TRUE) + else() + # Some distros provide only crypto/ssl pc files from LibreSSL + pkg_check_modules(LIBRESSL_CRYPTO QUIET libcrypto) + pkg_check_modules(LIBRESSL_SSL QUIET libssl) + if(LIBRESSL_CRYPTO_FOUND) + list(APPEND LIBRESSL_INCLUDE_DIRS ${LIBRESSL_CRYPTO_INCLUDE_DIRS}) + list(APPEND LIBRESSL_LINK_LIBS ${LIBRESSL_CRYPTO_LIBRARIES}) + if(LIBRESSL_SSL_FOUND) + list(APPEND LIBRESSL_INCLUDE_DIRS ${LIBRESSL_SSL_INCLUDE_DIRS}) + list(APPEND LIBRESSL_LINK_LIBS ${LIBRESSL_SSL_LIBRARIES}) + endif() + set(_libressl_found TRUE) + endif() + endif() + endif() + + # 2) Prefer explicit LibreSSL include prefix if present + if(EXISTS "/usr/include/libressl") + list(PREPEND LIBRESSL_INCLUDE_DIRS "/usr/include/libressl") + set(_libressl_found TRUE) + endif() + + # 3) Heuristic: check if the generic openssl headers are from LibreSSL + if(NOT _libressl_found) + # Try to find opensslv.h and see if it defines LIBRESSL_VERSION_NUMBER + find_path(_GEN_OPENSSL_INCLUDE_DIR openssl/opensslv.h + PATHS /usr/include /usr/local/include) + if(_GEN_OPENSSL_INCLUDE_DIR) + file(READ "${_GEN_OPENSSL_INCLUDE_DIR}/openssl/opensslv.h" _opensslv_h CONTENT_STRIP_TRAILING_WHITESPACE) + string(FIND "${_opensslv_h}" "LIBRESSL_VERSION_NUMBER" _idx) + if(NOT _idx EQUAL -1) + list(APPEND LIBRESSL_INCLUDE_DIRS "${_GEN_OPENSSL_INCLUDE_DIR}") + set(_libressl_found TRUE) + endif() + endif() + endif() + + # 4) Find the crypto library (from LibreSSL). Avoid CMake's OpenSSL package and target. + if(NOT LIBRESSL_LINK_LIBS) + # Try to locate libcrypto first + find_library(LIBRESSL_CRYPTO_LIB NAMES crypto libcrypto PATHS + /usr/lib /usr/local/lib /lib) + if(LIBRESSL_CRYPTO_LIB) + list(APPEND LIBRESSL_LINK_LIBS ${LIBRESSL_CRYPTO_LIB}) + endif() + endif() + + if(NOT _libressl_found OR NOT LIBRESSL_LINK_LIBS) + message(FATAL_ERROR "FUN_WITH_LIBRESSL=ON but LibreSSL headers and/or libcrypto not found.\n" + "Tried pkg-config (libressl/libcrypto), /usr/include/libressl, and generic openssl headers from LibreSSL.") + endif() + + # Ensure the compile definition is visible even if targets are created later + add_compile_definitions(FUN_WITH_LIBRESSL=1) + + # Propagate to main targets if they exist in this scope + if(TARGET fun_core) + target_link_libraries(fun_core PRIVATE ${LIBRESSL_LINK_LIBS}) + target_include_directories(fun_core PRIVATE ${LIBRESSL_INCLUDE_DIRS}) + target_compile_definitions(fun_core PRIVATE FUN_WITH_LIBRESSL=1) + endif() + if(TARGET fun) + target_link_libraries(fun PRIVATE ${LIBRESSL_LINK_LIBS}) + target_include_directories(fun PRIVATE ${LIBRESSL_INCLUDE_DIRS}) + target_compile_definitions(fun PRIVATE FUN_WITH_LIBRESSL=1) + endif() + if(TARGET fun_test) + target_link_libraries(fun_test PRIVATE ${LIBRESSL_LINK_LIBS}) + target_include_directories(fun_test PRIVATE ${LIBRESSL_INCLUDE_DIRS}) + target_compile_definitions(fun_test PRIVATE FUN_WITH_LIBRESSL=1) + endif() +endif() diff --git a/cmake/Targets.cmake b/cmake/Targets.cmake index bd6c48e..5ac9dbe 100644 --- a/cmake/Targets.cmake +++ b/cmake/Targets.cmake @@ -37,7 +37,8 @@ foreach(var_pair LIBXML2 TCL NOTCURSES - OPENSSL) + OPENSSL + LIBRESSL) if(${var_pair}_INCLUDE_DIRS) target_include_directories(fun_core PRIVATE ${${var_pair}_INCLUDE_DIRS}) endif() @@ -94,6 +95,12 @@ if(FUN_WITH_OPENSSL) target_compile_definitions(fun_core PUBLIC FUN_WITH_OPENSSL=1) endif() +# LibreSSL toggle: ensure compile definitions are applied to fun_core so +# the LibreSSL code paths are compiled, and linking vars are handled above. +if(FUN_WITH_LIBRESSL) + target_compile_definitions(fun_core PUBLIC FUN_WITH_LIBRESSL=1) +endif() + # Workaround: provide a dummy rust_eh_personality to satisfy linker when using # no_std Rust staticlib with panic abort (some toolchains still reference it). # If needed, we could add a C shim here, but the Rust crate now defines diff --git a/docs/README.md b/docs/README.md index ab2ea78..e3d4ed8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -21,7 +21,7 @@ This file serves as an index of the documents in this directory. Links are relat ## New and supplemental guides -- [build.md](./build.md) - How to build Fun with CMake, available targets, and build options (FUN_DEBUG, FUN_USE_MUSL, FUN_WITH_CPP, FUN_WITH_RUST, FUN_WITH_OPENSSL). +- [build.md](./build.md) - How to build Fun with CMake, available targets, and build options (FUN_DEBUG, FUN_USE_MUSL, FUN_WITH_CPP, FUN_WITH_RUST, FUN_WITH_OPENSSL, FUN_WITH_LIBRESSL). - [cli.md](./cli.md) - Command-line usage of the `fun` executable: synopsis, options, exit codes, includes and library paths. - [contributing.md](./contributing.md) - How to contribute: project structure, coding style, running tests, and PR guidelines. - [style-guide.md](./style-guide.md) - Coding conventions for C and Fun (indentation, naming, idioms). @@ -40,10 +40,12 @@ This file serves as an index of the documents in this directory. Links are relat Documentation for optional, build-time selectable integrations lives in [external/](./external/): - [Index of extensions](./external/README.md) - - Highlights: [cURL](./external/curl.md), [INI](./external/ini.md), [JSON](./external/json.md), [XML (libxml2)](./external/xml2.md), [SQLite](./external/sqlite.md), [libSQL](./external/libsql.md), [PCRE2](./external/pcre2.md), [PC/SC](./external/pcsc.md), [Notcurses](./external/notcurses.md), [Tcl/Tk](./external/tcltk.md), [OpenSSL](./external/openssl.md) + - Highlights: [cURL](./external/curl.md), [INI](./external/ini.md), [JSON](./external/json.md), [XML (libxml2)](./external/xml2.md), [SQLite](./external/sqlite.md), [libSQL](./external/libsql.md), [PCRE2](./external/pcre2.md), [PC/SC](./external/pcsc.md), [Notcurses](./external/notcurses.md), [Tcl/Tk](./external/tcltk.md), [OpenSSL](./external/openssl.md), [LibreSSL](./external/libressl.md) ## Tips - When building from the repo without installing, set `FUN_LIB_DIR` to the local `./lib` directory so examples and the REPL can locate the stdlib. - For a broader project overview and quickstart, see the repository root [README.md](../README.md). -- Crypto example: if built with `-DFUN_WITH_OPENSSL=ON`, try `examples/crypto/openssl_md5.fun` to compute MD5 using OpenSSL. +- Crypto examples: + - If built with `-DFUN_WITH_OPENSSL=ON`, try `examples/crypto/openssl_md5.fun`. + - If built with `-DFUN_WITH_LIBRESSL=ON`, try `examples/crypto/libressl_md5.fun`. diff --git a/docs/build.md b/docs/build.md index 0a45457..2d70544 100644 --- a/docs/build.md +++ b/docs/build.md @@ -23,6 +23,7 @@ Fun exposes several options you can toggle at configure time: - `FUN_WITH_CPP` (ON/OFF) - Enable C++-based opcode/examples support - `FUN_WITH_RUST` (ON/OFF) - Build and link Rust staticlib from `src/rust/` - `FUN_WITH_OPENSSL` (ON/OFF) - Enable OpenSSL-backed helpers (MD5/SHA-256/SHA-512/RIPEMD-160) + - `FUN_WITH_LIBRESSL` (ON/OFF) - Enable LibreSSL-backed helpers (MD5/SHA-256/SHA-512/RIPEMD-160) When configuring, the build prints a summary like: @@ -55,13 +56,13 @@ cmake --build build_release --target build ### Enabling optional extensions ``` cmake -S . -B build_release -DCMAKE_BUILD_TYPE=Release \ - -DFUN_WITH_CPP=ON -DFUN_WITH_RUST=ON -DFUN_WITH_OPENSSL=ON + -DFUN_WITH_CPP=ON -DFUN_WITH_RUST=ON -DFUN_WITH_OPENSSL=ON -DFUN_WITH_LIBRESSL=ON cmake --build build_release --target build ``` If `FUN_WITH_RUST` is enabled, ensure `cargo` is available in PATH; the build will invoke it and link the produced static library. -If `FUN_WITH_OPENSSL` is enabled, CMake must detect your system OpenSSL. Hash helpers use the EVP interface (OpenSSL 3-compatible). Note: RIPEMD-160 may require the legacy provider on OpenSSL 3.x; if unavailable, the helper returns an empty string. +If `FUN_WITH_OPENSSL` is enabled, CMake must detect your system OpenSSL (libcrypto). If `FUN_WITH_LIBRESSL` is enabled, CMake detects LibreSSL directly (via pkg-config or standard include/lib locations) and links to LibreSSL’s `libcrypto` — no OpenSSL installation is required. Both extensions use the EVP interface. Note: On OpenSSL 3.x, RIPEMD-160 may require the legacy provider; if unavailable, the helper returns an empty string. ## Running - CLI: run the `fun` executable from your build directory. diff --git a/docs/external/README.md b/docs/external/README.md index 15950cb..8a78aa7 100644 --- a/docs/external/README.md +++ b/docs/external/README.md @@ -6,7 +6,7 @@ This section documents Fun’s optional, build‑time selectable extensions. Eac - Available opcodes and/or helper functions - Minimal usage examples and links to example scripts -Extensions: +## Extensions: - [cURL (libcurl)](./curl.md) - [INI (iniparser)](./ini.md) @@ -19,7 +19,9 @@ Extensions: - [Notcurses (TUI)](./notcurses.md) - [Tcl/Tk (GUI)](./tcltk.md) - [OpenSSL](./openssl.md) +- [LibreSSL](./libressl.md) + +## Notes: -Notes: - These integrations are optional; the VM compiles without them. - When disabled, related builtins usually return empty strings/neutral values rather than fail hard, mirroring existing optionality patterns. diff --git a/docs/external/curl.md b/docs/external/curl.md index b47ddc3..e76f875 100644 --- a/docs/external/curl.md +++ b/docs/external/curl.md @@ -4,11 +4,13 @@ - Purpose: HTTP helpers using libcurl. - Homepage: https://curl.se/libcurl/ -Opcodes: +## Opcodes: + - OP_CURL_GET: GET; pops url:string; pushes body:string (empty on error/disabled) - OP_CURL_POST: POST; pops body:string, url:string; pushes response:string - OP_CURL_DOWNLOAD: Download to file; pops path:string, url:string; pushes 1/0 -Notes: +## Notes: + - Requires libcurl development headers/libs. - When disabled, helpers return empty strings/0 to match optional behavior. diff --git a/docs/external/ini.md b/docs/external/ini.md index 2975313..aeb5ac5 100644 --- a/docs/external/ini.md +++ b/docs/external/ini.md @@ -4,7 +4,8 @@ - Purpose: Read/write simple INI configuration files. - Homepage: https://github.com/ndevilla/iniparser -Opcodes: +## Opcodes: + - OP_INI_LOAD: pops path; pushes handle (>0) or 0 - OP_INI_FREE: pops handle; pushes 1/0 - OP_INI_GET_STRING: pops def, key, section, handle; pushes string @@ -15,6 +16,7 @@ Opcodes: - OP_INI_UNSET: pops key, section, handle; pushes 1/0 - OP_INI_SAVE: pops path, handle; pushes 1/0 -Notes: +## Notes: + - Requires iniparser development headers/libs. - When disabled, helpers return neutral values (0/empty strings) like other optional extensions. diff --git a/docs/external/json.md b/docs/external/json.md index 60475d1..4456174 100644 --- a/docs/external/json.md +++ b/docs/external/json.md @@ -4,12 +4,14 @@ - Purpose: JSON parse/stringify and file helpers via json-c. - Homepage: https://json-c.github.io/json-c/ -Opcodes: +## Opcodes: + - OP_JSON_PARSE: pops text; pushes value or Nil on error - OP_JSON_STRINGIFY: pops pretty:int(0/1), value; pushes string - OP_JSON_FROM_FILE: pops path; pushes value or Nil - OP_JSON_TO_FILE: pops pretty:int(0/1), value, path; pushes 1/0 -Notes: +## Notes: + - Requires json-c development headers/libs. - When disabled, functions push empty/neutral values similar to other optional modules. diff --git a/docs/external/libressl.md b/docs/external/libressl.md new file mode 100644 index 0000000..5751a0e --- /dev/null +++ b/docs/external/libressl.md @@ -0,0 +1,45 @@ +# LibreSSL extension (optional) + +- CMake option: FUN_WITH_LIBRESSL=ON +- Purpose: provide small crypto helpers backed by LibreSSL’s libcrypto. Includes md5, sha256, sha512, ripemd160 helpers under libressl_* names. +- Homepage: https://www.libressl.org/ + +## Build notes: + +- Requires system LibreSSL development headers and libcrypto. The build detects LibreSSL directly (via pkg-config or standard include/lib locations) and links to libcrypto from LibreSSL — it does not require OpenSSL to be installed. +- When disabled, the builtins below evaluate to empty strings to mirror optionality behavior across extensions. + +## Provided helper functions/opcodes: + +- Function: libressl_md5(data:string) -> string (lowercase hex). +- Function: libressl_sha256(data:string) -> string (lowercase hex). +- Function: libressl_sha512(data:string) -> string (lowercase hex). +- Function: libressl_ripemd160(data:string) -> string (lowercase hex). +- Opcodes: OP_LIBRESSL_MD5, OP_LIBRESSL_SHA256, OP_LIBRESSL_SHA512, OP_LIBRESSL_RIPEMD160 (internal mappings for the functions above). + +## Quickstart: + +- Configure: `cmake -S . -B build -DFUN_WITH_LIBRESSL=ON` +- Build: `cmake --build build --target fun` +- Run examples: + - `./build/fun examples/crypto/libressl_md5.fun` + - `./build/fun examples/crypto/libressl_sha256.fun` + - `./build/fun examples/crypto/libressl_sha512.fun` + - `./build/fun examples/crypto/libressl_ripemd160.fun` + +## Example output: + +- md5(abc) = 900150983cd24fb0d6963f7d28e17f72 +- md5("") = d41d8cd98f00b204e9800998ecf8427e +- sha256(abc) = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad +- sha256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 +- sha512(abc) = ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f +- sha512("") = cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e +- ripemd160(abc) = 8eb208f7e05d987a9b044a8e98c6b087f15a0bfc +- ripemd160("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31 + +## Notes: + +- The functions accept any Fun value; non-strings are coerced via `to_string` semantics by the VM before hashing. +- On some platforms, RIPEMD-160 may not be available; in that case the helper returns an empty string. +- If your system installs LibreSSL headers under `/usr/include/libressl`, CMake will automatically add this directory to the include path so that `#include ` resolves correctly. diff --git a/docs/external/libsql.md b/docs/external/libsql.md index c2df1f9..43662a7 100644 --- a/docs/external/libsql.md +++ b/docs/external/libsql.md @@ -4,12 +4,14 @@ - Purpose: SQLite-compatible client using the libSQL (Turso) library. - Homepage: https://libsql.org/ -Opcodes: +## Opcodes: + - OP_LIBSQL_OPEN: pops url_or_path; pushes handle (>0) or 0 - OP_LIBSQL_CLOSE: pops handle; pushes Nil - OP_LIBSQL_EXEC: pops sql, handle; pushes rc:int (0=OK) - OP_LIBSQL_QUERY: pops sql, handle; pushes array -Notes: +## Notes: + - Uses a SQLite-compatible C API provided by libSQL; behavior is similar to the SQLite backend. - This module is independent from the SQLite extension; you may enable either or both. diff --git a/docs/external/notcurses.md b/docs/external/notcurses.md index c596981..9985479 100644 --- a/docs/external/notcurses.md +++ b/docs/external/notcurses.md @@ -4,13 +4,15 @@ - Purpose: Terminal UI capabilities via the Notcurses library. - Homepage: https://notcurses.com/ -Opcodes: +## Opcodes: + - OP_NC_INIT: initialize Notcurses; returns 1 on success, 0 on failure - OP_NC_SHUTDOWN: shutdown; returns 0 - OP_NC_CLEAR: clear screen/plane; returns 0 - OP_NC_DRAW_TEXT: pops text, x, y; draws; returns 0 - OP_NC_GETCH: pops timeout_ms; returns codepoint or -1 on timeout/error -Notes: +## Notes: + - Requires Notcurses development headers/libs. - Behavior may vary across terminals; see the implementation for details. diff --git a/docs/external/openssl.md b/docs/external/openssl.md index 7606280..c0a732b 100644 --- a/docs/external/openssl.md +++ b/docs/external/openssl.md @@ -4,18 +4,21 @@ - Purpose: provide small crypto helpers backed by OpenSSL. Includes md5, sha256, sha512, ripemd160 helpers. - Homepage: https://www.openssl.org/ -Build notes: +## Build notes: + - Requires system OpenSSL development headers and libraries. - On OpenSSL 3.x, legacy MD5_* APIs are deprecated; you may see warnings during build. -Provided helper/opcodes: +## Provided helper/opcodes: + - Function: openssl_md5(data:string) -> string (lowercase hex). Falls back to empty string when the extension is disabled, mirroring other optional modules. - Function: openssl_sha256(data:string) -> string (lowercase hex). - Function: openssl_sha512(data:string) -> string (lowercase hex). - Function: openssl_ripemd160(data:string) -> string (lowercase hex). Note: On OpenSSL 3.x this may require the legacy provider; if the digest is unavailable, the helper returns an empty string. - Opcodes: OP_OPENSSL_MD5, OP_OPENSSL_SHA256, OP_OPENSSL_SHA512, OP_OPENSSL_RIPEMD160 (internal mappings for the functions above). -Quickstart: +## Quickstart: + - Configure: cmake -S . -B build -DFUN_WITH_OPENSSL=ON - Build: cmake --build build --target fun - Run examples: @@ -24,15 +27,17 @@ Quickstart: - ./build/fun examples/crypto/openssl_sha512.fun - ./build/fun examples/crypto/openssl_ripemd160.fun -Example output: +## Example output: + - md5(abc) = 900150983cd24fb0d6963f7d28e17f72 - md5("") = d41d8cd98f00b204e9800998ecf8427e - sha256(abc) = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad - sha256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 - sha512(abc) = ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f - sha512("") = cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e - - ripemd160(abc) = 8eb208f7e05d987a9b044a8e98c6b087f15a0bfc - - ripemd160("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31 +- ripemd160(abc) = 8eb208f7e05d987a9b044a8e98c6b087f15a0bfc +- ripemd160("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31 + +## Notes: -Notes: - The OpenSSL 3.x provider configuration on your system determines availability of RIPEMD‑160. If the legacy provider is not enabled, openssl_ripemd160() will return an empty string. diff --git a/docs/external/pcre2.md b/docs/external/pcre2.md index 9e4d9f2..2325e5d 100644 --- a/docs/external/pcre2.md +++ b/docs/external/pcre2.md @@ -4,11 +4,13 @@ - Purpose: Advanced regular expressions via PCRE2. - Homepage: https://www.pcre.org/ -Opcodes: +## Opcodes: + - OP_PCRE2_TEST: pops flags, text, pattern; pushes 1/0 - OP_PCRE2_MATCH: pops flags, text, pattern; pushes match map or Nil - OP_PCRE2_FINDALL: pops flags, text, pattern; pushes array of match maps -Notes: +## Notes: + - Requires PCRE2 development headers/libs. - Flags are backend-specific; see implementation for supported bits. diff --git a/docs/external/pcsc.md b/docs/external/pcsc.md index c00b171..4519054 100644 --- a/docs/external/pcsc.md +++ b/docs/external/pcsc.md @@ -4,7 +4,8 @@ - Purpose: Access smart card readers/cards via PC/SC (pcsclite). - Homepage: https://pcsclite.apdu.fr/ -Opcodes: +## Opcodes: + - OP_PCSC_ESTABLISH: returns context id (>0) or 0 - OP_PCSC_RELEASE: pops ctx id; returns 1/0 - OP_PCSC_LIST_READERS: pops ctx id; returns array of reader names @@ -12,6 +13,7 @@ Opcodes: - OP_PCSC_DISCONNECT: pops handle id; returns 1/0 - OP_PCSC_TRANSMIT: pops apdu, handle id; returns map with data/SW/rc -Notes: +## Notes: + - Requires PC/SC lite development headers/libs. - Behavior and availability depend on platform and reader drivers. diff --git a/docs/external/sqlite.md b/docs/external/sqlite.md index e246a76..6dcd00d 100644 --- a/docs/external/sqlite.md +++ b/docs/external/sqlite.md @@ -4,12 +4,14 @@ - Purpose: Access SQLite databases via the native C API. - Homepage: https://www.sqlite.org/ -Opcodes: +## Opcodes: + - OP_SQLITE_OPEN: pops path; pushes handle (>0) or 0 - OP_SQLITE_CLOSE: pops handle; pushes Nil - OP_SQLITE_EXEC: pops sql, handle; pushes rc:int (0=OK) - OP_SQLITE_QUERY: pops sql, handle; pushes array -Notes: +## Notes: + - Requires SQLite development headers/libs. - See also: `libSQL` for a compatible alternative backend. diff --git a/docs/external/tcltk.md b/docs/external/tcltk.md index 97cc429..f39d66a 100644 --- a/docs/external/tcltk.md +++ b/docs/external/tcltk.md @@ -1,8 +1,11 @@ # Tcl/Tk (GUI) extension (optional) + - CMake option: FUN_WITH_TCLTK=ON - Purpose: Basic GUI functionality via Tcl/Tk. - Homepage: https://www.tcl.tk/ -Opcodes: + +## Opcodes: + - OP_TK_EVAL: pops script string; pushes rc (0=OK) - OP_TK_RESULT: pushes last Tcl result string - OP_TK_LOOP: enters main event loop; pushes Nil when done @@ -11,6 +14,8 @@ Opcodes: - OP_TK_BUTTON: pops text, id; creates/updates button .id; pushes rc - OP_TK_PACK: pops id; packs .id; pushes rc - OP_TK_BIND: pops command, event, id; binds; pushes rc -Notes: + +## Notes: + - Requires Tcl/Tk development headers/libs. - GUI behavior depends on your desktop environment/window manager. diff --git a/docs/external/xml2.md b/docs/external/xml2.md index 3a86071..9c22f30 100644 --- a/docs/external/xml2.md +++ b/docs/external/xml2.md @@ -4,12 +4,14 @@ - Purpose: Minimal XML parsing helpers using libxml2. - Homepage: http://xmlsoft.org/ -Opcodes: +## Opcodes: + - OP_XML_PARSE: pops text; pushes doc handle (>0) or 0 - OP_XML_ROOT: pops doc handle; pushes node handle (>0) or 0 - OP_XML_NAME: pops node handle; pushes string (node name) - OP_XML_TEXT: pops node handle; pushes string (concatenated text) -Notes: +## Notes: + - Requires libxml2 development headers/libs. - On many systems, the include path is `/usr/include/libxml2`. diff --git a/docs/internals.md b/docs/internals.md index 5ce70a2..4fdba6f 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -80,7 +80,7 @@ The interpreter loop lives in src/vm.c: vm_run. Opcodes are executed in a tight Opcode handlers organization: - To keep vm.c readable, most opcode implementations are factored into small .c files included directly into vm.c (e.g., vm/core/load_const.c, vm/logic/and.c, vm/arrays/push.c, vm/math/abs.c, vm/os/thread_spawn.c, etc.). - This is a deliberate “amalgamation” style: small single‑purpose C units compiled as part of vm.c. -- Optional subsystems (JSON, PCRE2, CURL, SQLite, libSQL, PC/SC, XML2, Tcl/Tk, Notcurses, INI, sockets, serial, OS helpers) are grouped under src/external and src/vm//. +- Optional subsystems (JSON, PCRE2, CURL, SQLite, libSQL, PC/SC, XML2, Tcl/Tk, Notcurses, INI, OpenSSL/LibreSSL crypto helpers, sockets, serial, OS helpers) are grouped under src/external and src/vm//. Dispatch naming and visibility: - Human‑readable names for opcodes live in vm.h: opcode_names[]. These are used in debug prints and error messages. @@ -117,7 +117,7 @@ The VM is dynamically typed. Values carry a tag; operations check types at runti - Maps: OP_MAKE_MAP/KEYS/VALUES/HAS_KEY. - Conversions/reflection: OP_TO_NUMBER/TO_STRING/CAST/TYPEOF, OP_UCLAMP/SCLAMP. - I/O and OS: OP_READ_FILE/WRITE_FILE/INPUT_LINE/ENV/PROC_RUN/PROC_SYSTEM/TIME_NOW_MS/CLOCK_MONO_MS/DATE_FORMAT/OS_LIST_DIR/RANDOM_NUMBER, sockets, serial. -- External integrations (optional): JSON, CURL, SQLite, libSQL, PC/SC, XML2, Tcl/Tk, Notcurses, INI. +- External integrations (optional): JSON, CURL, SQLite, libSQL, PC/SC, XML2, Tcl/Tk, Notcurses, INI, OpenSSL/LibreSSL. Each handler enforces argument types and returns clear error messages via vm_raise_error on misuse. diff --git a/examples/crypto/libressl_md5.fun b/examples/crypto/libressl_md5.fun new file mode 100644 index 0000000..24b3740 --- /dev/null +++ b/examples/crypto/libressl_md5.fun @@ -0,0 +1,28 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +// LibreSSL MD5 example +// Enable with -DFUN_WITH_LIBRESSL=ON during build for real hashing. + +s = "abc" +d = libressl_md5(s) +print("md5(abc) = " + d) + +// Another quick check (empty string) +e = "" +print("md5(\"\") = " + libressl_md5(e)) + +/* Expected output: +md5(abc) = 900150983cd24fb0d6963f7d28e17f72 +md5("") = d41d8cd98f00b204e9800998ecf8427e +*/ diff --git a/examples/crypto/libressl_ripemd160.fun b/examples/crypto/libressl_ripemd160.fun new file mode 100644 index 0000000..437e6e1 --- /dev/null +++ b/examples/crypto/libressl_ripemd160.fun @@ -0,0 +1,28 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +// LibreSSL RIPEMD-160 example +// Enable with -DFUN_WITH_LIBRESSL=ON during build for real hashing. + +s = "abc" +d = libressl_ripemd160(s) +print("ripemd160(abc) = " + d) + +// Another quick check (empty string) +e = "" +print("ripemd160(\"\") = " + libressl_ripemd160(e)) + +/* Expected output: +ripemd160(abc) = 8eb208f7e05d987a9b049a9a5c0c2b74e07e6a5d +ripemd160("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31 +*/ diff --git a/examples/crypto/libressl_sha256.fun b/examples/crypto/libressl_sha256.fun new file mode 100644 index 0000000..a51baed --- /dev/null +++ b/examples/crypto/libressl_sha256.fun @@ -0,0 +1,28 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +// LibreSSL SHA-256 example +// Enable with -DFUN_WITH_LIBRESSL=ON during build for real hashing. + +s = "abc" +d = libressl_sha256(s) +print("sha256(abc) = " + d) + +// Another quick check (empty string) +e = "" +print("sha256(\"\") = " + libressl_sha256(e)) + +/* Expected output: +sha256(abc) = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad +sha256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 +*/ diff --git a/examples/crypto/libressl_sha512.fun b/examples/crypto/libressl_sha512.fun new file mode 100644 index 0000000..525dbcf --- /dev/null +++ b/examples/crypto/libressl_sha512.fun @@ -0,0 +1,28 @@ +#!/usr/bin/env fun + +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +// LibreSSL SHA-512 example +// Enable with -DFUN_WITH_LIBRESSL=ON during build for real hashing. + +s = "abc" +d = libressl_sha512(s) +print("sha512(abc) = " + d) + +// Another quick check (empty string) +e = "" +print("sha512(\"\") = " + libressl_sha512(e)) + +/* Expected output: +sha512(abc) = ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f +sha512("") = cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e +*/ diff --git a/make b/make index 01e2fbd..a11600c 100755 --- a/make +++ b/make @@ -33,6 +33,7 @@ if [ "$target" = "all" ]; then -DFUN_WITH_NOTCURSES=ON \ -DFUN_WITH_CPP=ON \ -DFUN_WITH_OPENSSL=ON \ + -DFUN_WITH_LIBRESSL=ON \ && cmake --build build --target fun elif [ "$target" = "all_debug" ]; then rm -rf build \ diff --git a/src/bytecode.c b/src/bytecode.c index 405e6b7..01629c8 100644 --- a/src/bytecode.c +++ b/src/bytecode.c @@ -173,6 +173,10 @@ static const char *opcode_name(OpCode op) { case OP_OPENSSL_SHA256: return "OPENSSL_SHA256"; case OP_OPENSSL_SHA512: return "OPENSSL_SHA512"; case OP_OPENSSL_RIPEMD160: return "OPENSSL_RIPEMD160"; + case OP_LIBRESSL_MD5: return "LIBRESSL_MD5"; + case OP_LIBRESSL_SHA256: return "LIBRESSL_SHA256"; + case OP_LIBRESSL_SHA512: return "LIBRESSL_SHA512"; + case OP_LIBRESSL_RIPEMD160: return "LIBRESSL_RIPEMD160"; case OP_INI_LOAD: return "INI_LOAD"; case OP_INI_FREE: return "INI_FREE"; case OP_INI_GET_STRING: return "INI_GET_STRING"; diff --git a/src/bytecode.h b/src/bytecode.h index 5f89650..ac173af 100644 --- a/src/bytecode.h +++ b/src/bytecode.h @@ -187,6 +187,12 @@ typedef enum { OP_OPENSSL_SHA512, // pops data string; pushes sha512 hex string OP_OPENSSL_RIPEMD160, // pops data string; pushes ripemd160 hex string + // LibreSSL (optional; same API as OpenSSL but different toggle) + OP_LIBRESSL_MD5, // pops data string; pushes md5 hex string + OP_LIBRESSL_SHA256, // pops data string; pushes sha256 hex string + OP_LIBRESSL_SHA512, // pops data string; pushes sha512 hex string + OP_LIBRESSL_RIPEMD160, // pops data string; pushes ripemd160 hex string + // INI (iniparser 4.2.6) optional OP_INI_LOAD, // pops path; pushes handle (>0) or 0 OP_INI_FREE, // pops handle; pushes 1/0 diff --git a/src/external/libressl.c b/src/external/libressl.c new file mode 100644 index 0000000..78ad66a --- /dev/null +++ b/src/external/libressl.c @@ -0,0 +1,172 @@ +/* +* This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +/* + * LibreSSL integration helpers (MD5, RIPEMD-160, SHA-256, SHA-512) + */ + +#ifdef FUN_WITH_LIBRESSL +/* + * When building with LibreSSL, include the LibreSSL-provided headers explicitly. + * Downstream distros often ship them under /usr/include/libressl/openssl/… + * and expect the include path to point at /usr/include/libressl so that any + * nested `#include ` inside these headers resolves to the + * corresponding LibreSSL headers as well (not the system OpenSSL 3.x ones). + */ +#include +/* Compatibility: Prefer EVP_MD_get_size universally. If LibreSSL headers + * don't declare it, provide a forward declaration so we can link against + * OpenSSL's libcrypto symbol when that is what CMake found. */ +#ifndef EVP_MD_get_size +int EVP_MD_get_size(const EVP_MD *md); +#endif +#endif +#include + +/* Compute MD5 hex of input buffer; returns malloc'ed C string (lowercase hex). */ +static char *fun_libressl_md5_hex(const unsigned char *data, size_t len) { + static const char hexdig[] = "0123456789abcdef"; + if (!data && len != 0) return NULL; +#ifdef FUN_WITH_LIBRESSL + const EVP_MD *md = EVP_md5(); + if (!md) return NULL; + int dlen = EVP_MD_get_size(md); + if (dlen <= 0) return NULL; + unsigned char *digest = (unsigned char*)malloc((size_t)dlen); + if (!digest) return NULL; + unsigned int out_len = 0; + int ok; + if (len == 0) { + ok = EVP_Digest(NULL, 0, digest, &out_len, md, NULL); + } else { + ok = EVP_Digest(data, len, digest, &out_len, md, NULL); + } + if (ok != 1 || (int)out_len != dlen) { free(digest); return NULL; } + char *hex = (char*)malloc((size_t)dlen * 2 + 1); + if (!hex) { free(digest); return NULL; } + for (int i = 0; i < dlen; ++i) { + hex[2*i] = hexdig[(digest[i] >> 4) & 0xF]; + hex[2*i+1] = hexdig[digest[i] & 0xF]; + } + hex[dlen * 2] = '\0'; + free(digest); + return hex; +#else + char *hex = (char*)malloc(1); + if (hex) hex[0] = '\0'; + return hex; +#endif +} + +/* Compute SHA-256 hex of input buffer; returns malloc'ed C string (lowercase hex). */ +static char *fun_libressl_sha256_hex(const unsigned char *data, size_t len) { + static const char hexdig[] = "0123456789abcdef"; + if (!data && len != 0) return NULL; +#ifdef FUN_WITH_LIBRESSL + const EVP_MD *md = EVP_sha256(); + if (!md) return NULL; + int dlen = EVP_MD_get_size(md); + if (dlen <= 0) return NULL; + unsigned char *digest = (unsigned char*)malloc((size_t)dlen); + if (!digest) return NULL; + unsigned int out_len = 0; + int ok; + if (len == 0) { + ok = EVP_Digest(NULL, 0, digest, &out_len, md, NULL); + } else { + ok = EVP_Digest(data, len, digest, &out_len, md, NULL); + } + if (ok != 1 || (int)out_len != dlen) { free(digest); return NULL; } + char *hex = (char*)malloc((size_t)dlen * 2 + 1); + if (!hex) { free(digest); return NULL; } + for (int i = 0; i < dlen; ++i) { + hex[2*i] = hexdig[(digest[i] >> 4) & 0xF]; + hex[2*i+1] = hexdig[digest[i] & 0xF]; + } + hex[dlen * 2] = '\0'; + free(digest); + return hex; +#else + char *hex = (char*)malloc(1); + if (hex) hex[0] = '\0'; + return hex; +#endif +} + +/* Compute SHA-512 hex of input buffer; returns malloc'ed C string (lowercase hex). */ +static char *fun_libressl_sha512_hex(const unsigned char *data, size_t len) { + static const char hexdig[] = "0123456789abcdef"; + if (!data && len != 0) return NULL; +#ifdef FUN_WITH_LIBRESSL + const EVP_MD *md = EVP_sha512(); + if (!md) return NULL; + int dlen = EVP_MD_get_size(md); + if (dlen <= 0) return NULL; + unsigned char *digest = (unsigned char*)malloc((size_t)dlen); + if (!digest) return NULL; + unsigned int out_len = 0; + int ok; + if (len == 0) { + ok = EVP_Digest(NULL, 0, digest, &out_len, md, NULL); + } else { + ok = EVP_Digest(data, len, digest, &out_len, md, NULL); + } + if (ok != 1 || (int)out_len != dlen) { free(digest); return NULL; } + char *hex = (char*)malloc((size_t)dlen * 2 + 1); + if (!hex) { free(digest); return NULL; } + for (int i = 0; i < dlen; ++i) { + hex[2*i] = hexdig[(digest[i] >> 4) & 0xF]; + hex[2*i+1] = hexdig[digest[i] & 0xF]; + } + hex[dlen * 2] = '\0'; + free(digest); + return hex; +#else + char *hex = (char*)malloc(1); + if (hex) hex[0] = '\0'; + return hex; +#endif +} + +/* Compute RIPEMD-160 hex of input buffer; returns malloc'ed C string (lowercase hex). */ +static char *fun_libressl_ripemd160_hex(const unsigned char *data, size_t len) { + static const char hexdig[] = "0123456789abcdef"; + if (!data && len != 0) return NULL; +#ifdef FUN_WITH_LIBRESSL + const EVP_MD *md = EVP_ripemd160(); + if (!md) return NULL; + int dlen = EVP_MD_get_size(md); + if (dlen <= 0) return NULL; + unsigned char *digest = (unsigned char*)malloc((size_t)dlen); + if (!digest) return NULL; + unsigned int out_len = 0; + int ok; + if (len == 0) { + ok = EVP_Digest(NULL, 0, digest, &out_len, md, NULL); + } else { + ok = EVP_Digest(data, len, digest, &out_len, md, NULL); + } + if (ok != 1 || (int)out_len != dlen) { free(digest); return NULL; } + char *hex = (char*)malloc((size_t)dlen * 2 + 1); + if (!hex) { free(digest); return NULL; } + for (int i = 0; i < dlen; ++i) { + hex[2*i] = hexdig[(digest[i] >> 4) & 0xF]; + hex[2*i+1] = hexdig[digest[i] & 0xF]; + } + hex[dlen * 2] = '\0'; + free(digest); + return hex; +#else + char *hex = (char*)malloc(1); + if (hex) hex[0] = '\0'; + return hex; +#endif +} diff --git a/src/external/openssl.c b/src/external/openssl.c index 810e430..ac0301e 100644 --- a/src/external/openssl.c +++ b/src/external/openssl.c @@ -15,6 +15,11 @@ #ifdef FUN_WITH_OPENSSL #include +/* Always use EVP_MD_get_size; if headers don't declare it, provide a + * forward declaration to allow linking against OpenSSL libcrypto. */ +#ifndef EVP_MD_get_size +int EVP_MD_get_size(const EVP_MD *md); +#endif #endif #include diff --git a/src/parser.c b/src/parser.c index faa2944..f8f7c49 100644 --- a/src/parser.c +++ b/src/parser.c @@ -1230,6 +1230,39 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos) free(name); return 1; } + /* LibreSSL (md5/sha256/sha512/ripemd160) */ + if (strcmp(name, "libressl_md5") == 0) { + (*pos)++; /* '(' */ + if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "libressl_md5 expects (data)"); free(name); return 0; } + if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "Expected ')' after libressl_md5 arg"); free(name); return 0; } + bytecode_add_instruction(bc, OP_LIBRESSL_MD5, 0); + free(name); + return 1; + } + if (strcmp(name, "libressl_sha256") == 0) { + (*pos)++; /* '(' */ + if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "libressl_sha256 expects (data)"); free(name); return 0; } + if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "Expected ')' after libressl_sha256 arg"); free(name); return 0; } + bytecode_add_instruction(bc, OP_LIBRESSL_SHA256, 0); + free(name); + return 1; + } + if (strcmp(name, "libressl_sha512") == 0) { + (*pos)++; /* '(' */ + if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "libressl_sha512 expects (data)"); free(name); return 0; } + if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "Expected ')' after libressl_sha512 arg"); free(name); return 0; } + bytecode_add_instruction(bc, OP_LIBRESSL_SHA512, 0); + free(name); + return 1; + } + if (strcmp(name, "libressl_ripemd160") == 0) { + (*pos)++; /* '(' */ + if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "libressl_ripemd160 expects (data)"); free(name); return 0; } + if (!consume_char(src, len, pos, ')')) { parser_fail(*pos, "Expected ')' after libressl_ripemd160 arg"); free(name); return 0; } + bytecode_add_instruction(bc, OP_LIBRESSL_RIPEMD160, 0); + free(name); + return 1; + } /* PCSC builtins */ if (strcmp(name, "pcsc_establish") == 0) { (*pos)++; /* '(' */ diff --git a/src/vm.c b/src/vm.c index eb9af8d..6fa2f2f 100644 --- a/src/vm.c +++ b/src/vm.c @@ -74,6 +74,7 @@ #include "external/tcltk.c" #include "external/xml2.c" #include "external/openssl.c" +#include "external/libressl.c" /* forward declarations for include mapping used in error reporting */ extern char *preprocess_includes(const char *src); @@ -870,10 +871,20 @@ void vm_run(VM *vm, Bytecode *entry) { #endif /* OpenSSL ops (md5/sha256/sha512/ripemd160) */ + #ifdef FUN_WITH_OPENSSL #include "vm/openssl/md5.c" #include "vm/openssl/sha256.c" #include "vm/openssl/sha512.c" #include "vm/openssl/ripemd160.c" + #endif + + /* LibreSSL ops (md5/sha256/sha512/ripemd160) */ + #ifdef FUN_WITH_LIBRESSL + #include "vm/libressl/md5.c" + #include "vm/libressl/sha256.c" + #include "vm/libressl/sha512.c" + #include "vm/libressl/ripemd160.c" + #endif /* Tk (Tcl/Tk) ops */ #ifdef FUN_WITH_TCLTK diff --git a/src/vm/libressl/md5.c b/src/vm/libressl/md5.c new file mode 100644 index 0000000..1ffc998 --- /dev/null +++ b/src/vm/libressl/md5.c @@ -0,0 +1,27 @@ +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +/** +* LibreSSL MD5 builtin +*/ +case OP_LIBRESSL_MD5: { + Value vdata = pop_value(vm); + char *s = value_to_string_alloc(&vdata); + free_value(vdata); + if (!s) { push_value(vm, make_string("")); break; } + char *hex = fun_libressl_md5_hex((const unsigned char*)s, strlen(s)); + free(s); + if (!hex) { push_value(vm, make_string("")); break; } + Value out = make_string(hex); + free(hex); + push_value(vm, out); + break; +} diff --git a/src/vm/libressl/ripemd160.c b/src/vm/libressl/ripemd160.c new file mode 100644 index 0000000..6dd766c --- /dev/null +++ b/src/vm/libressl/ripemd160.c @@ -0,0 +1,27 @@ +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +/** + * LibreSSL RIPEMD-160 builtin + */ +case OP_LIBRESSL_RIPEMD160: { + Value vdata = pop_value(vm); + char *s = value_to_string_alloc(&vdata); + free_value(vdata); + if (!s) { push_value(vm, make_string("")); break; } + char *hex = fun_libressl_ripemd160_hex((const unsigned char*)s, strlen(s)); + free(s); + if (!hex) { push_value(vm, make_string("")); break; } + Value out = make_string(hex); + free(hex); + push_value(vm, out); + break; +} diff --git a/src/vm/libressl/sha256.c b/src/vm/libressl/sha256.c new file mode 100644 index 0000000..1b27be0 --- /dev/null +++ b/src/vm/libressl/sha256.c @@ -0,0 +1,27 @@ +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +/** + * LibreSSL SHA-256 builtin + */ +case OP_LIBRESSL_SHA256: { + Value vdata = pop_value(vm); + char *s = value_to_string_alloc(&vdata); + free_value(vdata); + if (!s) { push_value(vm, make_string("")); break; } + char *hex = fun_libressl_sha256_hex((const unsigned char*)s, strlen(s)); + free(s); + if (!hex) { push_value(vm, make_string("")); break; } + Value out = make_string(hex); + free(hex); + push_value(vm, out); + break; +} diff --git a/src/vm/libressl/sha512.c b/src/vm/libressl/sha512.c new file mode 100644 index 0000000..67abcc8 --- /dev/null +++ b/src/vm/libressl/sha512.c @@ -0,0 +1,27 @@ +/* + * This file is part of the Fun programming language. + * https://fun-lang.xyz/ + * + * Copyright 2026 Johannes Findeisen + * Licensed under the terms of the Apache-2.0 license. + * https://opensource.org/license/apache-2-0 + * + * Added: 2026-02-19 + */ + +/** + * LibreSSL SHA-512 builtin + */ +case OP_LIBRESSL_SHA512: { + Value vdata = pop_value(vm); + char *s = value_to_string_alloc(&vdata); + free_value(vdata); + if (!s) { push_value(vm, make_string("")); break; } + char *hex = fun_libressl_sha512_hex((const unsigned char*)s, strlen(s)); + free(s); + if (!hex) { push_value(vm, make_string("")); break; } + Value out = make_string(hex); + free(hex); + push_value(vm, out); + break; +} From b7538ca165c084d9a7f603d941087804600e0e7d Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 19 Feb 2026 23:41:34 +0100 Subject: [PATCH 38/39] Some unicode fixes in docs/. No code changes. (0.38.16) --- docs/build.md | 6 ++++-- docs/external/README.md | 2 +- docs/external/libressl.md | 2 +- docs/external/openssl.md | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/build.md b/docs/build.md index 2d70544..04c45a0 100644 --- a/docs/build.md +++ b/docs/build.md @@ -23,7 +23,7 @@ Fun exposes several options you can toggle at configure time: - `FUN_WITH_CPP` (ON/OFF) - Enable C++-based opcode/examples support - `FUN_WITH_RUST` (ON/OFF) - Build and link Rust staticlib from `src/rust/` - `FUN_WITH_OPENSSL` (ON/OFF) - Enable OpenSSL-backed helpers (MD5/SHA-256/SHA-512/RIPEMD-160) - - `FUN_WITH_LIBRESSL` (ON/OFF) - Enable LibreSSL-backed helpers (MD5/SHA-256/SHA-512/RIPEMD-160) +- `FUN_WITH_LIBRESSL` (ON/OFF) - Enable LibreSSL-backed helpers (MD5/SHA-256/SHA-512/RIPEMD-160) When configuring, the build prints a summary like: @@ -62,7 +62,9 @@ cmake --build build_release --target build If `FUN_WITH_RUST` is enabled, ensure `cargo` is available in PATH; the build will invoke it and link the produced static library. -If `FUN_WITH_OPENSSL` is enabled, CMake must detect your system OpenSSL (libcrypto). If `FUN_WITH_LIBRESSL` is enabled, CMake detects LibreSSL directly (via pkg-config or standard include/lib locations) and links to LibreSSL’s `libcrypto` — no OpenSSL installation is required. Both extensions use the EVP interface. Note: On OpenSSL 3.x, RIPEMD-160 may require the legacy provider; if unavailable, the helper returns an empty string. +If `FUN_WITH_OPENSSL` is enabled, CMake must detect your system OpenSSL (libcrypto). + +If `FUN_WITH_LIBRESSL` is enabled, CMake detects LibreSSL directly (via pkg-config or standard include/lib locations) and links to LibreSSL's `libcrypto` — no OpenSSL installation is required. Both extensions use the EVP interface. Note: On OpenSSL 3.x, RIPEMD-160 may require the legacy provider; if unavailable, the helper returns an empty string. ## Running - CLI: run the `fun` executable from your build directory. diff --git a/docs/external/README.md b/docs/external/README.md index 8a78aa7..5219cbd 100644 --- a/docs/external/README.md +++ b/docs/external/README.md @@ -1,6 +1,6 @@ # External integrations (optional extensions) -This section documents Fun’s optional, build‑time selectable extensions. Each page covers: +This section documents Fun's optional, build-time selectable extensions. Each page covers: - How to enable the extension via CMake option (FUN_WITH_*) - Build requirements and detection notes - Available opcodes and/or helper functions diff --git a/docs/external/libressl.md b/docs/external/libressl.md index 5751a0e..388c69a 100644 --- a/docs/external/libressl.md +++ b/docs/external/libressl.md @@ -1,7 +1,7 @@ # LibreSSL extension (optional) - CMake option: FUN_WITH_LIBRESSL=ON -- Purpose: provide small crypto helpers backed by LibreSSL’s libcrypto. Includes md5, sha256, sha512, ripemd160 helpers under libressl_* names. +- Purpose: provide small crypto helpers backed by LibreSSL's libcrypto. Includes md5, sha256, sha512, ripemd160 helpers under libressl_* names. - Homepage: https://www.libressl.org/ ## Build notes: diff --git a/docs/external/openssl.md b/docs/external/openssl.md index c0a732b..f56a3ce 100644 --- a/docs/external/openssl.md +++ b/docs/external/openssl.md @@ -40,4 +40,4 @@ ## Notes: -- The OpenSSL 3.x provider configuration on your system determines availability of RIPEMD‑160. If the legacy provider is not enabled, openssl_ripemd160() will return an empty string. +- The OpenSSL 3.x provider configuration on your system determines availability of RIPEMD-160. If the legacy provider is not enabled, openssl_ripemd160() will return an empty string. From 7b4072d6a44342af43b505ad69c4082669e9018e Mon Sep 17 00:00:00 2001 From: hanez Date: Thu, 19 Feb 2026 23:43:49 +0100 Subject: [PATCH 39/39] Some unicode fixes in docs/. No code changes. (0.38.16) --- docs/internals.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/internals.md b/docs/internals.md index 4fdba6f..ecd45d7 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -79,11 +79,11 @@ The interpreter loop lives in src/vm.c: vm_run. Opcodes are executed in a tight Opcode handlers organization: - To keep vm.c readable, most opcode implementations are factored into small .c files included directly into vm.c (e.g., vm/core/load_const.c, vm/logic/and.c, vm/arrays/push.c, vm/math/abs.c, vm/os/thread_spawn.c, etc.). -- This is a deliberate “amalgamation” style: small single‑purpose C units compiled as part of vm.c. +- This is a deliberate “amalgamation” style: small single-purpose C units compiled as part of vm.c. - Optional subsystems (JSON, PCRE2, CURL, SQLite, libSQL, PC/SC, XML2, Tcl/Tk, Notcurses, INI, OpenSSL/LibreSSL crypto helpers, sockets, serial, OS helpers) are grouped under src/external and src/vm//. Dispatch naming and visibility: -- Human‑readable names for opcodes live in vm.h: opcode_names[]. These are used in debug prints and error messages. +- Human-readable names for opcodes live in vm.h: opcode_names[]. These are used in debug prints and error messages. ## Stacks, frames, locals, globals