Compare commits
39 commits
6fd3497032
...
7b4072d6a4
| Author | SHA1 | Date | |
|---|---|---|---|
| 7b4072d6a4 | |||
| b7538ca165 | |||
| 3e0d47a268 | |||
| d1d4adbf2c | |||
| 9016b207b8 | |||
| cb5e61c091 | |||
| 6fa95f0d47 | |||
| 38968a9a51 | |||
| 53698478d9 | |||
| 15082bdc3e | |||
| f896e1d3bf | |||
| bd2d619cb9 | |||
| eaf5f88dc0 | |||
| 16c36a6b8a | |||
| c44eba681c | |||
| 6ee78cc4fb | |||
| 41ebd59187 | |||
| b558af3a5f | |||
| 988e9e4c27 | |||
| ed0d30078b | |||
| 55c32952ec | |||
| 494f47a9a5 | |||
| 8a1afc2aa1 | |||
| 794a2354d6 | |||
| 54d94a1f3d | |||
| e017466cc7 | |||
| cd35ea767d | |||
| e7e1563228 | |||
| bc5c699a6a | |||
| c03ac29e40 | |||
| 5fdd02f3a6 | |||
| 4e155b55a5 | |||
| d79815e366 | |||
| d39ef1a58e | |||
| c2e7f3869e | |||
| 543483041b | |||
| 87833b0c1e | |||
| 058631e11b | |||
| 40c509626e |
108 changed files with 4818 additions and 796 deletions
|
|
@ -1,5 +1,5 @@
|
||||||
cmake_minimum_required(VERSION 3.10)
|
cmake_minimum_required(VERSION 3.10)
|
||||||
project(fun VERSION 0.38.0 LANGUAGES C)
|
project(fun VERSION 0.38.16 LANGUAGES C)
|
||||||
|
|
||||||
set(CMAKE_C_STANDARD 99)
|
set(CMAKE_C_STANDARD 99)
|
||||||
set(CMAKE_C_STANDARD_REQUIRED ON)
|
set(CMAKE_C_STANDARD_REQUIRED ON)
|
||||||
|
|
@ -19,6 +19,18 @@ else()
|
||||||
set(_FUN_DEBUG_STATE "DISABLED")
|
set(_FUN_DEBUG_STATE "DISABLED")
|
||||||
endif()
|
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()
|
||||||
|
set(_FUN_WITH_CPP_STATE "DISABLED")
|
||||||
|
endif()
|
||||||
|
|
||||||
if(FUN_WITH_RUST)
|
if(FUN_WITH_RUST)
|
||||||
set(_FUN_WITH_RUST_STATE "ENABLED")
|
set(_FUN_WITH_RUST_STATE "ENABLED")
|
||||||
else()
|
else()
|
||||||
|
|
@ -27,6 +39,8 @@ endif()
|
||||||
|
|
||||||
message(STATUS "==== Fun build options ====")
|
message(STATUS "==== Fun build options ====")
|
||||||
message(STATUS " FUN_DEBUG: ${_FUN_DEBUG_STATE}")
|
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 " FUN_WITH_RUST: ${_FUN_WITH_RUST_STATE}")
|
||||||
message(STATUS "===========================")
|
message(STATUS "===========================")
|
||||||
|
|
||||||
|
|
@ -98,6 +112,36 @@ if(FUN_WITH_RUST)
|
||||||
endif()
|
endif()
|
||||||
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) ---
|
# --- Size optimization for final binaries (Release) ---
|
||||||
# Enable function/data sectioning for better GC; safe for all configs.
|
# Enable function/data sectioning for better GC; safe for all configs.
|
||||||
add_compile_options(-ffunction-sections -fdata-sections)
|
add_compile_options(-ffunction-sections -fdata-sections)
|
||||||
|
|
@ -185,15 +229,10 @@ endif()
|
||||||
# Common locations (out-of-source and legacy in-source builds)
|
# Common locations (out-of-source and legacy in-source builds)
|
||||||
list(APPEND _candidates
|
list(APPEND _candidates
|
||||||
\"\${CMAKE_BINARY_DIR}/install_manifest.txt\"
|
\"\${CMAKE_BINARY_DIR}/install_manifest.txt\"
|
||||||
\"\${CMAKE_SOURCE_DIR}/install_manifest.txt\"
|
|
||||||
\"\${CMAKE_BINARY_DIR}/install_manifest_Debug.txt\"
|
\"\${CMAKE_BINARY_DIR}/install_manifest_Debug.txt\"
|
||||||
\"\${CMAKE_BINARY_DIR}/install_manifest_Release.txt\"
|
\"\${CMAKE_BINARY_DIR}/install_manifest_Release.txt\"
|
||||||
\"\${CMAKE_BINARY_DIR}/install_manifest_RelWithDebInfo.txt\"
|
\"\${CMAKE_BINARY_DIR}/install_manifest_RelWithDebInfo.txt\"
|
||||||
\"\${CMAKE_BINARY_DIR}/install_manifest_MinSizeRel.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 \"\")
|
set(_manifest_file \"\")
|
||||||
|
|
@ -316,6 +355,45 @@ endfunction()
|
||||||
# Define the uninstall target
|
# Define the uninstall target
|
||||||
fun_add_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 $<TARGET_FILE:fun> "${_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
|
# Install rules
|
||||||
# Binary
|
# Binary
|
||||||
install(TARGETS fun
|
install(TARGETS fun
|
||||||
|
|
|
||||||
42
README.md
42
README.md
|
|
@ -87,15 +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):
|
### 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) ☐
|
- [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) ☑
|
- [cURL (libcurl)](./docs/external/curl.md) (optional) ☑
|
||||||
- [INI](https://en.wikipedia.org/wiki/INI_file) support builtin using [iniparser](https://gitlab.com/iniparser/iniparser/) (optional) ☑
|
- [INI (iniparser)](./docs/external/ini.md) (optional) ☑
|
||||||
- [JSON](https://www.json.org/) support builtin using [json-c](https://github.com/json-c/json-c) (optional) ☑
|
- [JSON (json-c)](./docs/external/json.md) (optional) ☑
|
||||||
- [libSQL](https://github.com/tursodatabase/libsql) support builtin as a compatible alternative to SQLite (optional) ☑
|
- [libSQL](./docs/external/libsql.md) (optional) ☑
|
||||||
- [PCRE2](https://pcre2project.github.io/pcre2/) support builtin for Perl-Compatible Regular Expressions (optional) ☑
|
- [PCRE2](./docs/external/pcre2.md) (optional) ☑
|
||||||
- [PCSC](https://pcscworkgroup.com/) smart card support builtin using [PCSC lite](https://pcsclite.apdu.fr/) (optional) ☑
|
- [PCSC (smart cards)](./docs/external/pcsc.md) (optional) ☑
|
||||||
- [SQLite](https://sqlite.org/) support builtin (optional) ☑
|
- [OpenSSL](./docs/external/openssl.md) (optional) ☑
|
||||||
- [Tk](https://www.tcl-lang.org/) support builtin for GUI application development (optional) ☑
|
- [SQLite](./docs/external/sqlite.md) (optional) ☑
|
||||||
- [XML](https://www.w3.org/XML/) support builtin using [libxml2](https://gitlab.gnome.org/GNOME/libxml2/-/wikis/home) (optional) ☑
|
- [Tk (Tcl/Tk GUI)](./docs/external/tcltk.md) (optional) ☑
|
||||||
|
- [XML (libxml2)](./docs/external/xml2.md) (optional) ☑
|
||||||
|
|
||||||
☑ = Done / ☐ = Planned or in progress.
|
☑ = Done / ☐ = Planned or in progress.
|
||||||
|
|
||||||
|
|
@ -103,19 +104,28 @@ 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.
|
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)
|
||||||
|
|
||||||
|
See the dedicated page: ./docs/external/openssl.md
|
||||||
|
|
||||||
## Documentation
|
## 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.
|
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.
|
||||||
|
|
||||||
Complete API documentation will follow.
|
|
||||||
|
|
||||||
## Author
|
## Author
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -22,6 +22,8 @@ include(${CMAKE_SOURCE_DIR}/cmake/Extensions/PCRE2.cmake)
|
||||||
include(${CMAKE_SOURCE_DIR}/cmake/Extensions/CURL.cmake)
|
include(${CMAKE_SOURCE_DIR}/cmake/Extensions/CURL.cmake)
|
||||||
include(${CMAKE_SOURCE_DIR}/cmake/Extensions/NOTCURSES.cmake)
|
include(${CMAKE_SOURCE_DIR}/cmake/Extensions/NOTCURSES.cmake)
|
||||||
include(${CMAKE_SOURCE_DIR}/cmake/Extensions/REPL.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
|
# Summary of extension toggles
|
||||||
message(STATUS "---- Fun extension summary ----")
|
message(STATUS "---- Fun extension summary ----")
|
||||||
|
|
@ -36,4 +38,6 @@ _fun_print_feature("PCRE2 (FUN_WITH_PCRE2)" FUN_WITH_PCRE2)
|
||||||
_fun_print_feature("libcurl (FUN_WITH_CURL)" FUN_WITH_CURL)
|
_fun_print_feature("libcurl (FUN_WITH_CURL)" FUN_WITH_CURL)
|
||||||
_fun_print_feature("Notcurses (FUN_WITH_NOTCURSES)" FUN_WITH_NOTCURSES)
|
_fun_print_feature("Notcurses (FUN_WITH_NOTCURSES)" FUN_WITH_NOTCURSES)
|
||||||
_fun_print_feature("REPL (FUN_WITH_REPL)" FUN_WITH_REPL)
|
_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 "--------------------------------")
|
message(STATUS "--------------------------------")
|
||||||
|
|
|
||||||
100
cmake/Extensions/LIBRESSL.cmake
Normal file
100
cmake/Extensions/LIBRESSL.cmake
Normal file
|
|
@ -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()
|
||||||
41
cmake/Extensions/OPENSSL.cmake
Normal file
41
cmake/Extensions/OPENSSL.cmake
Normal file
|
|
@ -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()
|
||||||
|
|
@ -17,7 +17,6 @@ target_include_directories(fun_core PUBLIC
|
||||||
|
|
||||||
# Apply options to core
|
# Apply options to core
|
||||||
if(FUN_DEBUG)
|
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_VERSION="${PROJECT_VERSION}")
|
||||||
target_compile_definitions(fun_core PUBLIC FUN_DEBUG=1)
|
target_compile_definitions(fun_core PUBLIC FUN_DEBUG=1)
|
||||||
endif()
|
endif()
|
||||||
|
|
@ -37,7 +36,9 @@ foreach(var_pair
|
||||||
LIBSQL
|
LIBSQL
|
||||||
LIBXML2
|
LIBXML2
|
||||||
TCL
|
TCL
|
||||||
NOTCURSES)
|
NOTCURSES
|
||||||
|
OPENSSL
|
||||||
|
LIBRESSL)
|
||||||
if(${var_pair}_INCLUDE_DIRS)
|
if(${var_pair}_INCLUDE_DIRS)
|
||||||
target_include_directories(fun_core PRIVATE ${${var_pair}_INCLUDE_DIRS})
|
target_include_directories(fun_core PRIVATE ${${var_pair}_INCLUDE_DIRS})
|
||||||
endif()
|
endif()
|
||||||
|
|
@ -90,6 +91,26 @@ if(FUN_WITH_TCLTK)
|
||||||
target_compile_definitions(fun_core PUBLIC FUN_WITH_TCLTK=1)
|
target_compile_definitions(fun_core PUBLIC FUN_WITH_TCLTK=1)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
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
|
||||||
|
# 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
|
# Special case for libxml2 system include path if enabled
|
||||||
if(FUN_WITH_XML2)
|
if(FUN_WITH_XML2)
|
||||||
if(EXISTS "/usr/include/libxml2")
|
if(EXISTS "/usr/include/libxml2")
|
||||||
|
|
|
||||||
51
docs/README.md
Normal file
51
docs/README.md
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
# 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.
|
||||||
|
- [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, 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).
|
||||||
|
- [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.
|
||||||
|
|
||||||
|
## 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), [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 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`.
|
||||||
197
docs/arrays.md
Normal file
197
docs/arrays.md
Normal file
|
|
@ -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 <utils/iter.fun> 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 <utils/strings.fun> 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.
|
||||||
74
docs/build.md
Normal file
74
docs/build.md
Normal file
|
|
@ -0,0 +1,74 @@
|
||||||
|
# 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)
|
||||||
|
- `FUN_WITH_LIBRESSL` (ON/OFF) - Enable LibreSSL-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 -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 (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.
|
||||||
|
- 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.
|
||||||
29
docs/bytecode-format.md
Normal file
29
docs/bytecode-format.md
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
# Bytecode Format (Overview)
|
||||||
|
|
||||||
|
This document summarizes the Fun bytecode format. For deep VM details, see [internals.md](./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.
|
||||||
38
docs/cli.md
Normal file
38
docs/cli.md
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
# Fun CLI
|
||||||
|
|
||||||
|
Reference for the `fun` command-line interface.
|
||||||
|
|
||||||
|
## Synopsis
|
||||||
|
```
|
||||||
|
fun [options] <script.fun> [-- args...]
|
||||||
|
```
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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: [includes.md](./includes.md) for namespaced includes and search order.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
Run a script:
|
||||||
|
```
|
||||||
|
FUN_LIB_DIR=./lib ./build/fun examples/hello.fun
|
||||||
|
```
|
||||||
|
|
||||||
|
Start the REPL:
|
||||||
|
```
|
||||||
|
./build/fun -i
|
||||||
|
```
|
||||||
40
docs/contributing.md
Normal file
40
docs/contributing.md
Normal file
|
|
@ -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 [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](../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 [style-guide.md](./style-guide.md).
|
||||||
|
|
||||||
|
## Development workflow
|
||||||
|
1. Create a small, focused branch.
|
||||||
|
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.
|
||||||
|
|
||||||
|
## 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](../CODE_OF_CONDUCT.md) in the repository root.
|
||||||
29
docs/embedding.md
Normal file
29
docs/embedding.md
Normal file
|
|
@ -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](../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:
|
||||||
|
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](../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/`](../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 [rust.md](./rust.md) for details and example code.
|
||||||
21
docs/errors-and-diagnostics.md
Normal file
21
docs/errors-and-diagnostics.md
Normal file
|
|
@ -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 [build.md](./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.
|
||||||
63
docs/examples.md
Normal file
63
docs/examples.md
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
# 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/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/fun examples/include_lib.fun
|
||||||
|
```
|
||||||
|
|
||||||
|
Windows (PowerShell):
|
||||||
|
|
||||||
|
```
|
||||||
|
$env:FUN_LIB_DIR = "$PWD/lib"
|
||||||
|
./build/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/openssl_md5.fun
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example categories
|
||||||
|
|
||||||
|
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
|
||||||
|
- 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 <io/console.fun>
|
||||||
|
```
|
||||||
|
|
||||||
|
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.).
|
||||||
27
docs/external/README.md
vendored
Normal file
27
docs/external/README.md
vendored
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
# 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](./openssl.md)
|
||||||
|
- [LibreSSL](./libressl.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.
|
||||||
16
docs/external/curl.md
vendored
Normal file
16
docs/external/curl.md
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
# 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.
|
||||||
22
docs/external/ini.md
vendored
Normal file
22
docs/external/ini.md
vendored
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
# 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.
|
||||||
17
docs/external/json.md
vendored
Normal file
17
docs/external/json.md
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
# 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.
|
||||||
45
docs/external/libressl.md
vendored
Normal file
45
docs/external/libressl.md
vendored
Normal file
|
|
@ -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 <libressl/openssl/...>` resolves correctly.
|
||||||
17
docs/external/libsql.md
vendored
Normal file
17
docs/external/libsql.md
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
# 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<map>
|
||||||
|
|
||||||
|
## 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.
|
||||||
18
docs/external/notcurses.md
vendored
Normal file
18
docs/external/notcurses.md
vendored
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
# 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.
|
||||||
43
docs/external/openssl.md
vendored
Normal file
43
docs/external/openssl.md
vendored
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
# OpenSSL extension (optional)
|
||||||
|
|
||||||
|
- CMake option: FUN_WITH_OPENSSL=ON
|
||||||
|
- Purpose: provide small crypto helpers backed by OpenSSL. Includes md5, sha256, sha512, ripemd160 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).
|
||||||
|
- 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
|
||||||
|
- 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
|
||||||
|
- ./build/fun examples/crypto/openssl_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 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.
|
||||||
16
docs/external/pcre2.md
vendored
Normal file
16
docs/external/pcre2.md
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
# 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.
|
||||||
19
docs/external/pcsc.md
vendored
Normal file
19
docs/external/pcsc.md
vendored
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
# 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.
|
||||||
17
docs/external/sqlite.md
vendored
Normal file
17
docs/external/sqlite.md
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
# 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<map>
|
||||||
|
|
||||||
|
## Notes:
|
||||||
|
|
||||||
|
- Requires SQLite development headers/libs.
|
||||||
|
- See also: `libSQL` for a compatible alternative backend.
|
||||||
21
docs/external/tcltk.md
vendored
Normal file
21
docs/external/tcltk.md
vendored
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
# 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.
|
||||||
17
docs/external/xml2.md
vendored
Normal file
17
docs/external/xml2.md
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
# 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`.
|
||||||
22
docs/faq.md
Normal file
22
docs/faq.md
Normal file
|
|
@ -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/fun examples/hello.fun
|
||||||
|
```
|
||||||
|
See [includes.md](./includes.md).
|
||||||
|
|
||||||
|
## How do I start the REPL?
|
||||||
|
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 [build.md](./build.md).
|
||||||
|
|
||||||
|
## Where are the standard libraries?
|
||||||
|
Under [`./lib/`](../lib/). See [stdlib.md](./stdlib.md) for an overview.
|
||||||
|
|
||||||
|
## Where can I find internals and opcodes?
|
||||||
|
Browse [src/vm](../src/vm/) and [internals.md](./internals.md) / [opcodes.md](./opcodes.md).
|
||||||
137
docs/includes.md
Normal file
137
docs/includes.md
Normal file
|
|
@ -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 <path/inside/stdlib.fun>`
|
||||||
|
- 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 <hello.fun>
|
||||||
|
#include <utils/math.fun>
|
||||||
|
|
||||||
|
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 <utils/math.fun> 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/<path>` 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 <utils/math.fun>`
|
||||||
|
- Use `as` for clarity and to avoid name clashes: `#include <utils/math.fun> 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`)
|
||||||
|
|
@ -79,11 +79,11 @@ The interpreter loop lives in src/vm.c: vm_run. Opcodes are executed in a tight
|
||||||
|
|
||||||
Opcode handlers organization:
|
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.).
|
- 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, sockets, serial, OS helpers) are grouped under src/external and src/vm/<domain>/.
|
- 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/<domain>/.
|
||||||
|
|
||||||
Dispatch naming and visibility:
|
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
|
## Stacks, frames, locals, globals
|
||||||
|
|
||||||
|
|
@ -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.
|
- Maps: OP_MAKE_MAP/KEYS/VALUES/HAS_KEY.
|
||||||
- Conversions/reflection: OP_TO_NUMBER/TO_STRING/CAST/TYPEOF, OP_UCLAMP/SCLAMP.
|
- 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.
|
- 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.
|
Each handler enforces argument types and returns clear error messages via vm_raise_error on misuse.
|
||||||
|
|
||||||
|
|
@ -256,8 +256,6 @@ From vm.h defaults (tuned for simplicity; adjust if needed):
|
||||||
|
|
||||||
## Concurrency, isolates, and garbage collection
|
## 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.
|
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
|
### Concurrency model
|
||||||
|
|
@ -285,6 +283,160 @@ 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 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.
|
- 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.
|
||||||
|
|
||||||
|
### 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:
|
||||||
|
|
||||||
|
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
|
### Embedding patterns
|
||||||
|
|
||||||
- Parallelism: Create N VMs for N cores, wire them with channels or shared buffers. No global lock contention.
|
- Parallelism: Create N VMs for N cores, wire them with channels or shared buffers. No global lock contention.
|
||||||
|
|
|
||||||
203
docs/maps.md
Normal file
203
docs/maps.md
Normal file
|
|
@ -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 <io/json.fun> 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.
|
||||||
162
docs/numbers.md
Normal file
162
docs/numbers.md
Normal file
|
|
@ -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)
|
||||||
|
|
@ -202,6 +202,14 @@ 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_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.
|
- 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.
|
||||||
|
- 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)
|
## PCRE2 (Regex)
|
||||||
|
|
||||||
- OP_PCRE2_TEST: Test pattern; pops flags:int, text:string, pattern:string; pushes 1/0.
|
- OP_PCRE2_TEST: Test pattern; pops flags:int, text:string, pattern:string; pushes 1/0.
|
||||||
|
|
|
||||||
21
docs/performance.md
Normal file
21
docs/performance.md
Normal file
|
|
@ -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.
|
||||||
21
docs/roadmap.md
Normal file
21
docs/roadmap.md
Normal file
|
|
@ -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 ([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 ([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 [contributing.md](./contributing.md) for how to propose and implement items. Track concrete tasks via repository issues and PRs.
|
||||||
205
docs/rust.md
Normal file
205
docs/rust.md
Normal file
|
|
@ -0,0 +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 -DFUN_WITH_RUST=ON
|
||||||
|
cmake --build build --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 -DFUN_WITH_RUST=ON
|
||||||
|
cmake --build build --target fun
|
||||||
|
|
||||||
|
2) Execute the script:
|
||||||
|
build/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
|
||||||
17
docs/security-and-sandboxing.md
Normal file
17
docs/security-and-sandboxing.md
Normal file
|
|
@ -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.
|
||||||
26
docs/stdlib.md
Normal file
26
docs/stdlib.md
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
# Standard Library Overview
|
||||||
|
|
||||||
|
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](../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 [build.md](./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 [includes.md](./includes.md) and [cli.md](./cli.md) (FUN_LIB_DIR and DEFAULT_LIB_DIR).
|
||||||
99
docs/strings.md
Normal file
99
docs/strings.md
Normal file
|
|
@ -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)
|
||||||
62
docs/style-guide.md
Normal file
62
docs/style-guide.md
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
# 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: 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.
|
||||||
60
docs/testing.md
Normal file
60
docs/testing.md
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
# 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 --target test_opcodes && ./build/test_opcodes
|
||||||
|
```
|
||||||
|
|
||||||
|
Release profile example:
|
||||||
|
|
||||||
|
```
|
||||||
|
cmake --build build_release --target test_opcodes && ./build/test_opcodes
|
||||||
|
```
|
||||||
|
|
||||||
|
If `fun_test` exists in your configuration:
|
||||||
|
|
||||||
|
```
|
||||||
|
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 --target test
|
||||||
|
ctest --test-dir build -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.
|
||||||
91
docs/troubleshooting.md
Normal file
91
docs/troubleshooting.md
Normal file
|
|
@ -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 '<io/console.fun>'
|
||||||
|
```
|
||||||
|
|
||||||
|
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/fun examples/include_lib.fun
|
||||||
|
```
|
||||||
|
|
||||||
|
Windows (PowerShell):
|
||||||
|
|
||||||
|
```
|
||||||
|
$env:FUN_LIB_DIR = "$PWD/lib"
|
||||||
|
./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.
|
||||||
|
|
||||||
|
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 -DFUN_WITH_REPL=ON
|
||||||
|
cmake --build build --target fun
|
||||||
|
FUN_LIB_DIR="$(pwd)/lib" ./build/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\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/` for an interactive tour.
|
||||||
209
docs/types.md
Normal file
209
docs/types.md
Normal file
|
|
@ -0,0 +1,209 @@
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
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)
|
||||||
|
- 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 <utils/iter.fun> 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 <json/json.fun>
|
||||||
|
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)
|
||||||
24
docs/writing-tests.md
Normal file
24
docs/writing-tests.md
Normal file
|
|
@ -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.
|
||||||
28
examples/cpp_add.fun
Executable file
28
examples/cpp_add.fun
Executable file
|
|
@ -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 <you@hanez.org>
|
||||||
|
* 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
|
||||||
|
*/
|
||||||
45
examples/crypto/aes256.fun
Executable file
45
examples/crypto/aes256.fun
Executable file
|
|
@ -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 <you@hanez.org>
|
||||||
|
* 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 <crypt/aes256.fun>
|
||||||
|
|
||||||
|
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
|
||||||
|
*/
|
||||||
28
examples/crypto/libressl_md5.fun
Normal file
28
examples/crypto/libressl_md5.fun
Normal file
|
|
@ -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 <you@hanez.org>
|
||||||
|
* 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
|
||||||
|
*/
|
||||||
28
examples/crypto/libressl_ripemd160.fun
Normal file
28
examples/crypto/libressl_ripemd160.fun
Normal file
|
|
@ -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 <you@hanez.org>
|
||||||
|
* 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
|
||||||
|
*/
|
||||||
28
examples/crypto/libressl_sha256.fun
Normal file
28
examples/crypto/libressl_sha256.fun
Normal file
|
|
@ -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 <you@hanez.org>
|
||||||
|
* 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
|
||||||
|
*/
|
||||||
28
examples/crypto/libressl_sha512.fun
Normal file
28
examples/crypto/libressl_sha512.fun
Normal file
|
|
@ -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 <you@hanez.org>
|
||||||
|
* 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
|
||||||
|
*/
|
||||||
28
examples/crypto/openssl_md5.fun
Executable file
28
examples/crypto/openssl_md5.fun
Executable file
|
|
@ -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 <you@hanez.org>
|
||||||
|
* 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
|
||||||
|
*/
|
||||||
28
examples/crypto/openssl_ripemd160.fun
Executable file
28
examples/crypto/openssl_ripemd160.fun
Executable file
|
|
@ -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 <you@hanez.org>
|
||||||
|
* 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
|
||||||
|
*/
|
||||||
28
examples/crypto/openssl_sha256.fun
Executable file
28
examples/crypto/openssl_sha256.fun
Executable file
|
|
@ -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 <you@hanez.org>
|
||||||
|
* 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
|
||||||
|
*/
|
||||||
28
examples/crypto/openssl_sha512.fun
Executable file
28
examples/crypto/openssl_sha512.fun
Executable file
|
|
@ -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 <you@hanez.org>
|
||||||
|
* 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
|
||||||
|
*/
|
||||||
39
examples/error/rust_vm_access.fun
Executable file
39
examples/error/rust_vm_access.fun
Executable file
|
|
@ -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 <you@hanez.org>
|
||||||
|
* 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 42 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
|
||||||
64
examples/error_handling.fun
Executable file
64
examples/error_handling.fun
Executable file
|
|
@ -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 <utils/option.fun>
|
||||||
|
#include <utils/result.fun>
|
||||||
|
|
||||||
|
// 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, "<none>")))
|
||||||
|
|
@ -33,9 +33,9 @@ if len(readers) > 0
|
||||||
|
|
||||||
if h != 0
|
if h != 0
|
||||||
// Sample APDU: SELECT MF (00 A4 00 00 02 3F 00)
|
// Sample APDU: SELECT MF (00 A4 00 00 02 3F 00)
|
||||||
resp = pc.transmit_hex(h, "00A40000023F00")
|
// Use the safe convenience transmitter which returns a map {data, sw1, sw2, code}
|
||||||
// Print hex data and SW
|
resp = pc.transmit("00A40000023F00")
|
||||||
print("resp.data_hex=" + resp["data_hex"])
|
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"]))
|
print("resp.sw1=" + to_string(resp["sw1"]) + " sw2=" + to_string(resp["sw2"]) + " code=" + to_string(resp["code"]))
|
||||||
|
|
||||||
_ = pc.disconnect(h)
|
_ = pc.disconnect(h)
|
||||||
|
|
|
||||||
0
examples/features.fun
Normal file → Executable file
0
examples/features.fun
Normal file → Executable file
43
examples/match.fun
Executable file
43
examples/match.fun
Executable file
|
|
@ -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 <utils/option.fun>
|
||||||
|
|
||||||
|
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")
|
||||||
6
examples/rust_hello.fun
Normal file → Executable file
6
examples/rust_hello.fun
Normal file → Executable file
|
|
@ -4,7 +4,7 @@
|
||||||
* This file is part of the Fun programming language.
|
* This file is part of the Fun programming language.
|
||||||
* https://fun-lang.xyz/
|
* https://fun-lang.xyz/
|
||||||
*
|
*
|
||||||
* Copyright 2025 Johannes Findeisen <you@hanez.org>
|
* Copyright 2026 Johannes Findeisen <you@hanez.org>
|
||||||
* Licensed under the terms of the Apache-2.0 license.
|
* Licensed under the terms of the Apache-2.0 license.
|
||||||
* https://opensource.org/license/apache-2-0
|
* https://opensource.org/license/apache-2-0
|
||||||
*
|
*
|
||||||
|
|
@ -30,3 +30,7 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
print(rust_hello())
|
print(rust_hello())
|
||||||
|
|
||||||
|
/* Expected output:
|
||||||
|
Hello from Rust ops!
|
||||||
|
*/
|
||||||
|
|
|
||||||
37
examples/rust_hello_args.fun
Executable file
37
examples/rust_hello_args.fun
Executable file
|
|
@ -0,0 +1,37 @@
|
||||||
|
#!/usr/bin/env fun
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This file is part of the Fun programming language.
|
||||||
|
* https://fun-lang.xyz/
|
||||||
|
*
|
||||||
|
* Copyright 2026 Johannes Findeisen <you@hanez.org>
|
||||||
|
* 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!
|
||||||
|
*/
|
||||||
34
examples/rust_hello_args_return.fun
Executable file
34
examples/rust_hello_args_return.fun
Executable file
|
|
@ -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 <you@hanez.org>
|
||||||
|
* 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)!
|
||||||
|
*/
|
||||||
271
lib/crypt/aes256.fun
Normal file
271
lib/crypt/aes256.fun
Normal file
|
|
@ -0,0 +1,271 @@
|
||||||
|
/*
|
||||||
|
* This file is part of the Fun programming language.
|
||||||
|
* https://fun-lang.xyz/
|
||||||
|
*
|
||||||
|
* Copyright 2026 Johannes Findeisen <you@hanez.org>
|
||||||
|
* 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 <hex.fun>
|
||||||
|
#include <strings.fun>
|
||||||
|
|
||||||
|
class AES256()
|
||||||
|
// ---------- Hex helpers ----------
|
||||||
|
fun from_hex(this, hex)
|
||||||
|
arr = []
|
||||||
|
i = 0
|
||||||
|
n = len(hex)
|
||||||
|
while i + 1 < n
|
||||||
|
push(arr, byte_from_hex_pair(substr(hex, i, 2)))
|
||||||
|
i = i + 2
|
||||||
|
return arr
|
||||||
|
|
||||||
|
// ---------- 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 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 bytes_to_hex(out_bytes)
|
||||||
|
|
@ -23,6 +23,7 @@
|
||||||
// c = CRC32()
|
// c = CRC32()
|
||||||
// print(c.crc32_str("123456789"))
|
// print(c.crc32_str("123456789"))
|
||||||
|
|
||||||
|
#include <hex.fun>
|
||||||
#include <strings.fun>
|
#include <strings.fun>
|
||||||
|
|
||||||
class CRC32()
|
class CRC32()
|
||||||
|
|
@ -48,80 +49,23 @@ class CRC32()
|
||||||
return band(this.u32(a), this.u32(b))
|
return band(this.u32(a), this.u32(b))
|
||||||
|
|
||||||
// hex helpers (mirroring style from lib/crypt/md5.fun)
|
// 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))
|
|
||||||
return hi * 16 + lo
|
|
||||||
|
|
||||||
fun from_hex(this, hex)
|
fun from_hex(this, hex)
|
||||||
arr = []
|
arr = []
|
||||||
i = 0
|
i = 0
|
||||||
n = len(hex)
|
n = len(hex)
|
||||||
while i + 1 < n
|
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)
|
push(arr, b)
|
||||||
i = i + 2
|
i = i + 2
|
||||||
return arr
|
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)
|
fun u32_to_hex8(this, n)
|
||||||
// big-endian printing (MSB first), common for CRC displays
|
// big-endian printing (MSB first), common for CRC displays
|
||||||
b3 = this.and32(this.shr32(n, 24), 255)
|
b3 = this.and32(this.shr32(n, 24), 255)
|
||||||
b2 = this.and32(this.shr32(n, 16), 255)
|
b2 = this.and32(this.shr32(n, 16), 255)
|
||||||
b1 = this.and32(this.shr32(n, 8), 255)
|
b1 = this.and32(this.shr32(n, 8), 255)
|
||||||
b0 = this.and32(n, 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
|
// Bitwise update (no table needed) using reflected polynomial 0xEDB88320
|
||||||
POLY = 3988292384 // 0xEDB88320
|
POLY = 3988292384 // 0xEDB88320
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@
|
||||||
// c = CRC32C()
|
// c = CRC32C()
|
||||||
// print(c.crc32c_hex("313233343536373839"))
|
// print(c.crc32c_hex("313233343536373839"))
|
||||||
|
|
||||||
|
#include <hex.fun>
|
||||||
#include <strings.fun>
|
#include <strings.fun>
|
||||||
|
|
||||||
class CRC32C()
|
class CRC32C()
|
||||||
|
|
@ -48,80 +49,23 @@ class CRC32C()
|
||||||
return band(this.u32(a), this.u32(b))
|
return band(this.u32(a), this.u32(b))
|
||||||
|
|
||||||
// hex helpers (mirroring style from lib/crypt/md5.fun)
|
// 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))
|
|
||||||
return hi * 16 + lo
|
|
||||||
|
|
||||||
fun from_hex(this, hex)
|
fun from_hex(this, hex)
|
||||||
arr = []
|
arr = []
|
||||||
i = 0
|
i = 0
|
||||||
n = len(hex)
|
n = len(hex)
|
||||||
while i + 1 < n
|
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)
|
push(arr, b)
|
||||||
i = i + 2
|
i = i + 2
|
||||||
return arr
|
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)
|
fun u32_to_hex8(this, n)
|
||||||
// big-endian printing (MSB first), common for CRC displays
|
// big-endian printing (MSB first), common for CRC displays
|
||||||
b3 = this.and32(this.shr32(n, 24), 255)
|
b3 = this.and32(this.shr32(n, 24), 255)
|
||||||
b2 = this.and32(this.shr32(n, 16), 255)
|
b2 = this.and32(this.shr32(n, 16), 255)
|
||||||
b1 = this.and32(this.shr32(n, 8), 255)
|
b1 = this.and32(this.shr32(n, 8), 255)
|
||||||
b0 = this.and32(n, 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
|
// Bitwise update (no table needed) using reflected polynomial 0x82F63B78
|
||||||
POLY = 2197175160 // 0x82F63B78
|
POLY = 2197175160 // 0x82F63B78
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,7 @@
|
||||||
|
|
||||||
// Class wrapper to avoid global name collisions and show class usage
|
// Class wrapper to avoid global name collisions and show class usage
|
||||||
|
|
||||||
|
#include <hex.fun>
|
||||||
#include <strings.fun>
|
#include <strings.fun>
|
||||||
|
|
||||||
class MD5()
|
class MD5()
|
||||||
|
|
@ -79,73 +80,16 @@ class MD5()
|
||||||
return this.u32(this.u32(this.u32(a + b) + c) + d)
|
return this.u32(this.u32(this.u32(a + b) + c) + d)
|
||||||
|
|
||||||
// hex helpers
|
// 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)
|
fun from_hex(this, hex)
|
||||||
arr = []
|
arr = []
|
||||||
i = 0
|
i = 0
|
||||||
n = len(hex)
|
n = len(hex)
|
||||||
while i + 1 < n
|
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)
|
push(arr, b)
|
||||||
i = i + 2
|
i = i + 2
|
||||||
return arr
|
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, "")
|
|
||||||
|
|
||||||
// MD5 aux
|
// MD5 aux
|
||||||
fun F(this, x, y, z)
|
fun F(this, x, y, z)
|
||||||
return this.or32(this.and32(x, y), this.and32(this.not32(x), z))
|
return this.or32(this.and32(x, y), this.and32(this.not32(x), z))
|
||||||
|
|
@ -261,9 +205,9 @@ class MD5()
|
||||||
fun md5_hex(this, hexStr)
|
fun md5_hex(this, hexStr)
|
||||||
bytes = this.from_hex(hexStr)
|
bytes = this.from_hex(hexStr)
|
||||||
digest = this.md5_bytes(bytes)
|
digest = this.md5_bytes(bytes)
|
||||||
return this.bytes_to_hex(digest)
|
return bytes_to_hex(digest)
|
||||||
|
|
||||||
fun md5_str(this, str)
|
fun md5_str(this, str)
|
||||||
bytes = string_to_bytes_ascii(str)
|
bytes = string_to_bytes_ascii(str)
|
||||||
digest = this.md5_bytes(bytes)
|
digest = this.md5_bytes(bytes)
|
||||||
return this.bytes_to_hex(digest)
|
return bytes_to_hex(digest)
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@
|
||||||
* Added: 2025-10-01
|
* Added: 2025-10-01
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#include <hex.fun>
|
||||||
#include <strings.fun>
|
#include <strings.fun>
|
||||||
|
|
||||||
// Legacy global API and helpers. Please use the MD5 class (see lib/crypt/md5.fun).
|
// 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)
|
fun add32_4(a, b, c, d)
|
||||||
return u32(u32(u32(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)
|
fun byte_from_hex_pair(hh)
|
||||||
// hh is 2-char string
|
// hh is 2-char string
|
||||||
hi = hex_val(substr(hh, 0, 1))
|
hi = hex_val(substr(hh, 0, 1))
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@
|
||||||
|
|
||||||
// THIS IS BROKEN ACTUALLY! IT DOES NOT CALCULATE THE EXPECTED HASHES!
|
// THIS IS BROKEN ACTUALLY! IT DOES NOT CALCULATE THE EXPECTED HASHES!
|
||||||
|
|
||||||
|
#include <hex.fun>
|
||||||
#include <strings.fun>
|
#include <strings.fun>
|
||||||
|
|
||||||
class RIPEMD160()
|
class RIPEMD160()
|
||||||
|
|
@ -79,45 +80,9 @@ class RIPEMD160()
|
||||||
else
|
else
|
||||||
return this.u32(bxor(x, bor(y, bnot(z))))
|
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)
|
fun byte_from_hex_pair(this, hh)
|
||||||
hi = this.hex_val(substr(hh, 0, 1))
|
hi = hex_val(substr(hh, 0, 1))
|
||||||
lo = this.hex_val(substr(hh, 1, 1))
|
lo = hex_val(substr(hh, 1, 1))
|
||||||
return hi * 16 + lo
|
return hi * 16 + lo
|
||||||
|
|
||||||
fun from_hex(this, hex)
|
fun from_hex(this, hex)
|
||||||
|
|
@ -129,16 +94,11 @@ class RIPEMD160()
|
||||||
i = i + 2
|
i = i + 2
|
||||||
return arr
|
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)
|
fun bytes_to_hex(this, arr)
|
||||||
i = 0
|
i = 0
|
||||||
out = []
|
out = []
|
||||||
while i < len(arr)
|
while i < len(arr)
|
||||||
push(out, this.two_hex(arr[i]))
|
push(out, two_hex(arr[i]))
|
||||||
i = i + 1
|
i = i + 1
|
||||||
return join(out, "")
|
return join(out, "")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,7 @@
|
||||||
// rip.ripemd160_hex(hexStr) -> digest hex string (lowercase)
|
// rip.ripemd160_hex(hexStr) -> digest hex string (lowercase)
|
||||||
// rip.ripemd160_str("abc") -> digest hex string of ASCII bytes
|
// rip.ripemd160_str("abc") -> digest hex string of ASCII bytes
|
||||||
|
|
||||||
|
#include <hex.fun>
|
||||||
#include <strings.fun>
|
#include <strings.fun>
|
||||||
|
|
||||||
class RIPEMD160()
|
class RIPEMD160()
|
||||||
|
|
@ -53,45 +54,9 @@ class RIPEMD160()
|
||||||
return bnot(this.u32(x))
|
return bnot(this.u32(x))
|
||||||
|
|
||||||
// hex helpers (same as md5/sha files)
|
// 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)
|
fun byte_from_hex_pair(this, hh)
|
||||||
hi = this.hex_val(substr(hh, 0, 1))
|
hi = hex_val(substr(hh, 0, 1))
|
||||||
lo = this.hex_val(substr(hh, 1, 1))
|
lo = hex_val(substr(hh, 1, 1))
|
||||||
return hi * 16 + lo
|
return hi * 16 + lo
|
||||||
|
|
||||||
fun from_hex(this, hex)
|
fun from_hex(this, hex)
|
||||||
|
|
@ -104,19 +69,11 @@ class RIPEMD160()
|
||||||
i = i + 2
|
i = i + 2
|
||||||
return arr
|
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)
|
fun bytes_to_hex(this, arr)
|
||||||
i = 0
|
i = 0
|
||||||
out = []
|
out = []
|
||||||
while i < len(arr)
|
while i < len(arr)
|
||||||
push(out, this.two_hex(arr[i]))
|
push(out, two_hex(arr[i]))
|
||||||
i = i + 1
|
i = i + 1
|
||||||
return join(out, "")
|
return join(out, "")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -17,6 +17,7 @@
|
||||||
// sha.sha1_hex(hexStr) -> digest hex string (lowercase)
|
// sha.sha1_hex(hexStr) -> digest hex string (lowercase)
|
||||||
// sha.sha1_str("abc") -> digest hex string of ASCII bytes
|
// sha.sha1_str("abc") -> digest hex string of ASCII bytes
|
||||||
|
|
||||||
|
#include <hex.fun>
|
||||||
#include <strings.fun>
|
#include <strings.fun>
|
||||||
|
|
||||||
class SHA1()
|
class SHA1()
|
||||||
|
|
@ -37,45 +38,9 @@ class SHA1()
|
||||||
return rol(x, s)
|
return rol(x, s)
|
||||||
|
|
||||||
// hex helpers
|
// 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)
|
fun byte_from_hex_pair(this, hh)
|
||||||
hi = this.hex_val(substr(hh, 0, 1))
|
hi = hex_val(substr(hh, 0, 1))
|
||||||
lo = this.hex_val(substr(hh, 1, 1))
|
lo = hex_val(substr(hh, 1, 1))
|
||||||
return hi * 16 + lo
|
return hi * 16 + lo
|
||||||
|
|
||||||
fun from_hex(this, hex)
|
fun from_hex(this, hex)
|
||||||
|
|
@ -88,22 +53,6 @@ class SHA1()
|
||||||
i = i + 2
|
i = i + 2
|
||||||
return arr
|
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, "")
|
|
||||||
|
|
||||||
// padding (SHA-1): append 0x80, then zeros until length ≡ 56 (mod 64), then 64-bit length big-endian
|
// padding (SHA-1): append 0x80, then zeros until length ≡ 56 (mod 64), then 64-bit length big-endian
|
||||||
fun pad_bytes(this, bytes)
|
fun pad_bytes(this, bytes)
|
||||||
L = len(bytes)
|
L = len(bytes)
|
||||||
|
|
@ -207,9 +156,9 @@ class SHA1()
|
||||||
fun sha1_hex(this, hexStr)
|
fun sha1_hex(this, hexStr)
|
||||||
bytes = this.from_hex(hexStr)
|
bytes = this.from_hex(hexStr)
|
||||||
digest = this.sha1_bytes(bytes)
|
digest = this.sha1_bytes(bytes)
|
||||||
return this.bytes_to_hex(digest)
|
return bytes_to_hex(digest)
|
||||||
|
|
||||||
fun sha1_str(this, str)
|
fun sha1_str(this, str)
|
||||||
bytes = string_to_bytes_ascii(str)
|
bytes = string_to_bytes_ascii(str)
|
||||||
digest = this.sha1_bytes(bytes)
|
digest = this.sha1_bytes(bytes)
|
||||||
return this.bytes_to_hex(digest)
|
return bytes_to_hex(digest)
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,7 @@
|
||||||
// Example:
|
// Example:
|
||||||
// print(SHA256().sha256_hex("616263")) // "abc" => ba7816bf...
|
// print(SHA256().sha256_hex("616263")) // "abc" => ba7816bf...
|
||||||
|
|
||||||
|
#include <hex.fun>
|
||||||
#include <strings.fun>
|
#include <strings.fun>
|
||||||
|
|
||||||
class SHA256()
|
class SHA256()
|
||||||
|
|
@ -86,45 +87,9 @@ class SHA256()
|
||||||
]
|
]
|
||||||
|
|
||||||
// hex helpers
|
// 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)
|
fun byte_from_hex_pair(this, hh)
|
||||||
hi = this.hex_val(substr(hh, 0, 1))
|
hi = hex_val(substr(hh, 0, 1))
|
||||||
lo = this.hex_val(substr(hh, 1, 1))
|
lo = hex_val(substr(hh, 1, 1))
|
||||||
return hi * 16 + lo
|
return hi * 16 + lo
|
||||||
|
|
||||||
fun from_hex(this, hex)
|
fun from_hex(this, hex)
|
||||||
|
|
@ -137,22 +102,6 @@ class SHA256()
|
||||||
i = i + 2
|
i = i + 2
|
||||||
return arr
|
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, "")
|
|
||||||
|
|
||||||
// padding (SHA-256)
|
// padding (SHA-256)
|
||||||
fun pad_bytes(this, bytes)
|
fun pad_bytes(this, bytes)
|
||||||
L = len(bytes)
|
L = len(bytes)
|
||||||
|
|
@ -260,10 +209,10 @@ class SHA256()
|
||||||
fun sha256_hex(this, hexStr)
|
fun sha256_hex(this, hexStr)
|
||||||
bytes = this.from_hex(hexStr)
|
bytes = this.from_hex(hexStr)
|
||||||
digest = this.sha256_bytes(bytes)
|
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...
|
// Hash raw string bytes (printable ASCII). Example: sha256_str("616263") -> ee2109...
|
||||||
fun sha256_str(this, str)
|
fun sha256_str(this, str)
|
||||||
bytes = string_to_bytes_ascii(str)
|
bytes = string_to_bytes_ascii(str)
|
||||||
digest = this.sha256_bytes(bytes)
|
digest = this.sha256_bytes(bytes)
|
||||||
return this.bytes_to_hex(digest)
|
return bytes_to_hex(digest)
|
||||||
|
|
|
||||||
|
|
@ -23,49 +23,14 @@
|
||||||
// cb00753f45a35e8bb5a03d699ac65007272c32ab0eded163
|
// cb00753f45a35e8bb5a03d699ac65007272c32ab0eded163
|
||||||
// 1a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7
|
// 1a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7
|
||||||
|
|
||||||
|
#include <hex.fun>
|
||||||
#include <strings.fun>
|
#include <strings.fun>
|
||||||
|
|
||||||
class SHA384()
|
class SHA384()
|
||||||
// -------- hex helpers --------
|
// -------- 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)
|
fun byte_from_hex_pair(this, hh)
|
||||||
number hi = this.hex_val(substr(hh, 0, 1))
|
number hi = hex_val(substr(hh, 0, 1))
|
||||||
number lo = this.hex_val(substr(hh, 1, 1))
|
number lo = hex_val(substr(hh, 1, 1))
|
||||||
return hi * 16 + lo
|
return hi * 16 + lo
|
||||||
|
|
||||||
fun from_hex(this, hex)
|
fun from_hex(this, hex)
|
||||||
|
|
@ -79,24 +44,6 @@ class SHA384()
|
||||||
i = i + 2
|
i = i + 2
|
||||||
return arr
|
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 --------
|
// -------- 32/64 helpers --------
|
||||||
fun u32(this, x)
|
fun u32(this, x)
|
||||||
m = 4294967296
|
m = 4294967296
|
||||||
|
|
@ -359,10 +306,10 @@ class SHA384()
|
||||||
fun sha384_hex(this, hexStr)
|
fun sha384_hex(this, hexStr)
|
||||||
bytes = this.from_hex(hexStr)
|
bytes = this.from_hex(hexStr)
|
||||||
digest = this.sha384_bytes(bytes)
|
digest = this.sha384_bytes(bytes)
|
||||||
return this.bytes_to_hex(digest)
|
return bytes_to_hex(digest)
|
||||||
|
|
||||||
// Hash raw string bytes (printable ASCII)
|
// Hash raw string bytes (printable ASCII)
|
||||||
fun sha384_str(this, str)
|
fun sha384_str(this, str)
|
||||||
bytes = string_to_bytes_ascii(str)
|
bytes = string_to_bytes_ascii(str)
|
||||||
digest = this.sha384_bytes(bytes)
|
digest = this.sha384_bytes(bytes)
|
||||||
return this.bytes_to_hex(digest)
|
return bytes_to_hex(digest)
|
||||||
|
|
|
||||||
|
|
@ -24,49 +24,14 @@
|
||||||
// ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a
|
// ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a
|
||||||
// 2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f
|
// 2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f
|
||||||
|
|
||||||
|
#include <hex.fun>
|
||||||
#include <strings.fun>
|
#include <strings.fun>
|
||||||
|
|
||||||
class SHA512()
|
class SHA512()
|
||||||
// -------- hex helpers --------
|
// -------- 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)
|
fun byte_from_hex_pair(this, hh)
|
||||||
number hi = this.hex_val(substr(hh, 0, 1))
|
number hi = hex_val(substr(hh, 0, 1))
|
||||||
number lo = this.hex_val(substr(hh, 1, 1))
|
number lo = hex_val(substr(hh, 1, 1))
|
||||||
return hi * 16 + lo
|
return hi * 16 + lo
|
||||||
|
|
||||||
fun from_hex(this, hex)
|
fun from_hex(this, hex)
|
||||||
|
|
@ -80,24 +45,6 @@ class SHA512()
|
||||||
i = i + 2
|
i = i + 2
|
||||||
return arr
|
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 --------
|
// -------- 32/64 helpers --------
|
||||||
fun u32(this, x)
|
fun u32(this, x)
|
||||||
m = 4294967296
|
m = 4294967296
|
||||||
|
|
@ -360,10 +307,10 @@ class SHA512()
|
||||||
fun sha512_hex(this, hexStr)
|
fun sha512_hex(this, hexStr)
|
||||||
bytes = this.from_hex(hexStr)
|
bytes = this.from_hex(hexStr)
|
||||||
digest = this.sha512_bytes(bytes)
|
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...
|
// Hash raw string bytes (printable ASCII). Example: sha512_str("616263") -> ee2109...
|
||||||
fun sha512_str(this, str)
|
fun sha512_str(this, str)
|
||||||
bytes = string_to_bytes_ascii(str)
|
bytes = string_to_bytes_ascii(str)
|
||||||
digest = this.sha512_bytes(bytes)
|
digest = this.sha512_bytes(bytes)
|
||||||
return this.bytes_to_hex(digest)
|
return bytes_to_hex(digest)
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,10 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Hex utility functions
|
// 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)
|
fun hex_val(ch)
|
||||||
if (ch == "0")
|
if (ch == "0")
|
||||||
|
|
|
||||||
|
|
@ -17,11 +17,9 @@
|
||||||
|
|
||||||
include <hex.fun>
|
include <hex.fun>
|
||||||
|
|
||||||
/*
|
// Unified PCSC class API
|
||||||
class PCSC()
|
class PCSC()
|
||||||
// ---- hex helpers moved to lib/hex.fun ----
|
// ---- Context management ----
|
||||||
|
|
||||||
// ---- PCSC wrappers ----
|
|
||||||
fun establish(this)
|
fun establish(this)
|
||||||
// returns ctx id (>0) or 0
|
// returns ctx id (>0) or 0
|
||||||
return pcsc_establish()
|
return pcsc_establish()
|
||||||
|
|
@ -36,6 +34,16 @@ class PCSC()
|
||||||
return []
|
return []
|
||||||
return readers
|
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)
|
fun connect(this, ctx, reader_name)
|
||||||
// returns handle id (>0) or 0
|
// returns handle id (>0) or 0
|
||||||
return pcsc_connect(ctx, to_string(reader_name))
|
return pcsc_connect(ctx, to_string(reader_name))
|
||||||
|
|
@ -44,6 +52,7 @@ class PCSC()
|
||||||
// returns 1 on success or 0
|
// returns 1 on success or 0
|
||||||
return pcsc_disconnect(handle)
|
return pcsc_disconnect(handle)
|
||||||
|
|
||||||
|
// ---- Transmit helpers ----
|
||||||
// Transmit raw APDU bytes (array of numbers 0..255). Returns map {"data":[], "sw1":n, "sw2":n, "code":n}
|
// Transmit raw APDU bytes (array of numbers 0..255). Returns map {"data":[], "sw1":n, "sw2":n, "code":n}
|
||||||
fun transmit_bytes(this, handle, bytes)
|
fun transmit_bytes(this, handle, bytes)
|
||||||
res = pcsc_transmit(handle, bytes)
|
res = pcsc_transmit(handle, bytes)
|
||||||
|
|
@ -77,22 +86,12 @@ class PCSC()
|
||||||
m["sw2"] = res["sw2"]
|
m["sw2"] = res["sw2"]
|
||||||
m["code"] = res["code"]
|
m["code"] = res["code"]
|
||||||
return m
|
return m
|
||||||
*/
|
|
||||||
|
|
||||||
// This class is in a very early stage of development.
|
// Convenience: Transmit a raw hex APDU to the first available reader and return the result map
|
||||||
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
|
|
||||||
fun transmit(this, hex_apdu)
|
fun transmit(this, hex_apdu)
|
||||||
ctx = pcsc_establish()
|
ctx = pcsc_establish()
|
||||||
readers = pcsc_list_readers(ctx)
|
readers = pcsc_list_readers(ctx)
|
||||||
if (readers == nil)
|
if (readers == nil)
|
||||||
print([])
|
|
||||||
_ = pcsc_release(ctx)
|
_ = pcsc_release(ctx)
|
||||||
// return a default result map instead of 0, so callers can index fields safely
|
// return a default result map instead of 0, so callers can index fields safely
|
||||||
m = {}
|
m = {}
|
||||||
|
|
@ -102,7 +101,6 @@ class PCSC()
|
||||||
m["code"] = -2
|
m["code"] = -2
|
||||||
return m
|
return m
|
||||||
if (len(readers) == 0)
|
if (len(readers) == 0)
|
||||||
print([])
|
|
||||||
_ = pcsc_release(ctx)
|
_ = pcsc_release(ctx)
|
||||||
m = {}
|
m = {}
|
||||||
m["data"] = []
|
m["data"] = []
|
||||||
|
|
@ -110,50 +108,19 @@ class PCSC()
|
||||||
m["sw2"] = -1
|
m["sw2"] = -1
|
||||||
m["code"] = -2
|
m["code"] = -2
|
||||||
return m
|
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])
|
handle = pcsc_connect(ctx, readers[1])
|
||||||
apdu = this.hex_to_bytes(hex_apdu)
|
apdu_bytes = hex_to_bytes(hex_apdu)
|
||||||
res = pcsc_transmit(handle, apdu)
|
res = pcsc_transmit(handle, apdu_bytes)
|
||||||
_ = pcsc_disconnect(handle)
|
_ = pcsc_disconnect(handle)
|
||||||
_ = pcsc_release(ctx)
|
_ = pcsc_release(ctx)
|
||||||
return res
|
if res == nil
|
||||||
|
|
||||||
fun hex_digit(this, ch)
|
|
||||||
m = {}
|
m = {}
|
||||||
m["0"] = 0
|
m["data"] = []
|
||||||
m["1"] = 1
|
m["sw1"] = -1
|
||||||
m["2"] = 2
|
m["sw2"] = -1
|
||||||
m["3"] = 3
|
m["code"] = -2
|
||||||
m["4"] = 4
|
return m
|
||||||
m["5"] = 5
|
if res["data"] == nil
|
||||||
m["6"] = 6
|
res["data"] = []
|
||||||
m["7"] = 7
|
return res
|
||||||
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
|
|
||||||
|
|
|
||||||
36
lib/utils/match.fun
Normal file
36
lib/utils/match.fun
Normal file
|
|
@ -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
|
||||||
71
lib/utils/option.fun
Normal file
71
lib/utils/option.fun
Normal file
|
|
@ -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()
|
||||||
74
lib/utils/result.fun
Normal file
74
lib/utils/result.fun
Normal file
|
|
@ -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()
|
||||||
62
make
62
make
|
|
@ -31,6 +31,9 @@ if [ "$target" = "all" ]; then
|
||||||
-DFUN_WITH_TCLTK=ON \
|
-DFUN_WITH_TCLTK=ON \
|
||||||
-DFUN_WITH_INI=ON \
|
-DFUN_WITH_INI=ON \
|
||||||
-DFUN_WITH_NOTCURSES=ON \
|
-DFUN_WITH_NOTCURSES=ON \
|
||||||
|
-DFUN_WITH_CPP=ON \
|
||||||
|
-DFUN_WITH_OPENSSL=ON \
|
||||||
|
-DFUN_WITH_LIBRESSL=ON \
|
||||||
&& cmake --build build --target fun
|
&& cmake --build build --target fun
|
||||||
elif [ "$target" = "all_debug" ]; then
|
elif [ "$target" = "all_debug" ]; then
|
||||||
rm -rf build \
|
rm -rf build \
|
||||||
|
|
@ -46,6 +49,8 @@ elif [ "$target" = "all_debug" ]; then
|
||||||
-DFUN_WITH_TCLTK=ON \
|
-DFUN_WITH_TCLTK=ON \
|
||||||
-DFUN_WITH_INI=ON \
|
-DFUN_WITH_INI=ON \
|
||||||
-DFUN_WITH_NOTCURSES=ON \
|
-DFUN_WITH_NOTCURSES=ON \
|
||||||
|
-DFUN_WITH_CPP=ON \
|
||||||
|
-DFUN_WITH_OPENSSL=ON \
|
||||||
-DFUN_DEBUG=ON \
|
-DFUN_DEBUG=ON \
|
||||||
&& cmake --build build --target fun
|
&& cmake --build build --target fun
|
||||||
elif [ "$target" = "alpine" ]; then
|
elif [ "$target" = "alpine" ]; then
|
||||||
|
|
@ -59,7 +64,37 @@ elif [ "$target" = "alpine" ]; then
|
||||||
-DFUN_WITH_XML2=ON \
|
-DFUN_WITH_XML2=ON \
|
||||||
-DFUN_WITH_JSON=ON \
|
-DFUN_WITH_JSON=ON \
|
||||||
-DFUN_WITH_INI=ON \
|
-DFUN_WITH_INI=ON \
|
||||||
|
-DFUN_WITH_CPP=ON \
|
||||||
|
-DFUN_WITH_OPENSSL=ON \
|
||||||
&& cmake --build build --target fun
|
&& 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 \
|
||||||
|
-DFUN_WITH_OPENSSL=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" = "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
|
elif [ "$target" = "debug" ]; then
|
||||||
rm -rf build \
|
rm -rf build \
|
||||||
&& cmake -S . -B build \
|
&& cmake -S . -B build \
|
||||||
|
|
@ -88,17 +123,44 @@ elif [ "$target" = "repl" ]; then
|
||||||
&& cmake -S . -B build \
|
&& cmake -S . -B build \
|
||||||
-DFUN_WITH_REPL=ON \
|
-DFUN_WITH_REPL=ON \
|
||||||
&& cmake --build build --target fun
|
&& 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_WITH_CPP=ON \
|
||||||
|
-DFUN_WITH_OPENSSL=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
|
else
|
||||||
echo "Build target $target not found... aborting!";
|
echo "Build target $target not found... aborting!";
|
||||||
echo "Available targets:";
|
echo "Available targets:";
|
||||||
echo " - all";
|
echo " - all";
|
||||||
echo " - all_debug";
|
echo " - all_debug";
|
||||||
echo " - alpine";
|
echo " - alpine";
|
||||||
|
echo " - cpp_all";
|
||||||
|
echo " - cpp_minimal";
|
||||||
echo " - debug";
|
echo " - debug";
|
||||||
echo " - freebsd";
|
echo " - freebsd";
|
||||||
echo " - install";
|
echo " - install";
|
||||||
echo " - minimal";
|
echo " - minimal";
|
||||||
echo " - musl";
|
echo " - musl";
|
||||||
echo " - repl";
|
echo " - repl";
|
||||||
|
echo " - rust_all";
|
||||||
|
echo " - rust_minimal";
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|
|
||||||
156
play.fun
156
play.fun
|
|
@ -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 <strings.fun>
|
|
||||||
|
|
||||||
#include <io/console.fun>
|
|
||||||
#include <io/process.fun>
|
|
||||||
|
|
||||||
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()
|
|
||||||
|
|
@ -86,6 +86,7 @@ if (( ${#files[@]} == 0 )); then
|
||||||
fi
|
fi
|
||||||
|
|
||||||
rc=0
|
rc=0
|
||||||
|
fail_count=0
|
||||||
for f in "${files[@]}"; do
|
for f in "${files[@]}"; do
|
||||||
base_name="$(basename "$f")"
|
base_name="$(basename "$f")"
|
||||||
# If INI support is disabled, skip INI examples to avoid expected failures
|
# 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/}"
|
echo "FAILED: ${f#$ROOT/}"
|
||||||
# Intentionally do not move files on failure; leave control to the user
|
# Intentionally do not move files on failure; leave control to the user
|
||||||
rc=1
|
rc=1
|
||||||
|
((fail_count++))
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
if (( rc == 0 )); then
|
if (( rc == 0 )); then
|
||||||
echo "All examples ran successfully."
|
echo "All examples ran successfully. Failed: ${fail_count}"
|
||||||
else
|
else
|
||||||
echo "Some examples failed."
|
echo "Some examples failed. Failed: ${fail_count}"
|
||||||
fi
|
fi
|
||||||
exit $rc
|
exit $rc
|
||||||
|
|
|
||||||
|
|
@ -169,6 +169,14 @@ static const char *opcode_name(OpCode op) {
|
||||||
case OP_PCRE2_TEST: return "PCRE2_TEST";
|
case OP_PCRE2_TEST: return "PCRE2_TEST";
|
||||||
case OP_PCRE2_MATCH: return "PCRE2_MATCH";
|
case OP_PCRE2_MATCH: return "PCRE2_MATCH";
|
||||||
case OP_PCRE2_FINDALL: return "PCRE2_FINDALL";
|
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_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_LOAD: return "INI_LOAD";
|
||||||
case OP_INI_FREE: return "INI_FREE";
|
case OP_INI_FREE: return "INI_FREE";
|
||||||
case OP_INI_GET_STRING: return "INI_GET_STRING";
|
case OP_INI_GET_STRING: return "INI_GET_STRING";
|
||||||
|
|
@ -207,6 +215,10 @@ static const char *opcode_name(OpCode op) {
|
||||||
case OP_FMIN: return "FMIN";
|
case OP_FMIN: return "FMIN";
|
||||||
case OP_FMAX: return "FMAX";
|
case OP_FMAX: return "FMAX";
|
||||||
case OP_RUST_HELLO: return "RUST_HELLO";
|
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 "???";
|
default: return "???";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -181,6 +181,18 @@ typedef enum {
|
||||||
OP_PCRE2_MATCH, // pops flags, text, pattern; pushes match map or Nil
|
OP_PCRE2_MATCH, // pops flags, text, pattern; pushes match map or Nil
|
||||||
OP_PCRE2_FINDALL, // pops flags, text, pattern; pushes array of match maps
|
OP_PCRE2_FINDALL, // pops flags, text, pattern; pushes array of match maps
|
||||||
|
|
||||||
|
// 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
|
||||||
|
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
|
// INI (iniparser 4.2.6) optional
|
||||||
OP_INI_LOAD, // pops path; pushes handle (>0) or 0
|
OP_INI_LOAD, // pops path; pushes handle (>0) or 0
|
||||||
OP_INI_FREE, // pops handle; pushes 1/0
|
OP_INI_FREE, // pops handle; pushes 1/0
|
||||||
|
|
@ -265,6 +277,13 @@ typedef enum {
|
||||||
|
|
||||||
// Rust FFI demo opcode(s)
|
// Rust FFI demo opcode(s)
|
||||||
OP_RUST_HELLO, // pushes string returned from Rust (hello world)
|
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)
|
||||||
|
|
||||||
|
// C++ demo opcode(s)
|
||||||
|
OP_CPP_ADD, // pops b, a; pushes (a + b)
|
||||||
|
|
||||||
/* Notcurses TUI (optional) */
|
/* Notcurses TUI (optional) */
|
||||||
OP_NC_INIT, // initializes Notcurses; returns 1 on success, 0 on failure
|
OP_NC_INIT, // initializes Notcurses; returns 1 on success, 0 on failure
|
||||||
|
|
|
||||||
172
src/external/libressl.c
vendored
Normal file
172
src/external/libressl.c
vendored
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
/*
|
||||||
|
* This file is part of the Fun programming language.
|
||||||
|
* https://fun-lang.xyz/
|
||||||
|
*
|
||||||
|
* Copyright 2026 Johannes Findeisen <you@hanez.org>
|
||||||
|
* 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 <openssl/...>` inside these headers resolves to the
|
||||||
|
* corresponding LibreSSL headers as well (not the system OpenSSL 3.x ones).
|
||||||
|
*/
|
||||||
|
#include <libressl/openssl/evp.h>
|
||||||
|
/* 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 <stdlib.h>
|
||||||
|
|
||||||
|
/* 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
|
||||||
|
}
|
||||||
173
src/external/openssl.c
vendored
Normal file
173
src/external/openssl.c
vendored
Normal file
|
|
@ -0,0 +1,173 @@
|
||||||
|
/*
|
||||||
|
* This file is part of the Fun programming language.
|
||||||
|
* https://fun-lang.xyz/
|
||||||
|
*
|
||||||
|
* Copyright 2026 Johannes Findeisen <you@hanez.org>
|
||||||
|
* 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, RIPEMD-160, SHA-256, SHA-512)
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifdef FUN_WITH_OPENSSL
|
||||||
|
#include <openssl/evp.h>
|
||||||
|
/* 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 <stdlib.h>
|
||||||
|
|
||||||
|
/* 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
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 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
|
||||||
|
}
|
||||||
107
src/parser.c
107
src/parser.c
|
|
@ -793,6 +793,47 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos)
|
||||||
free(name);
|
free(name);
|
||||||
return 1;
|
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, "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; }
|
||||||
|
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, "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) {
|
if (strcmp(name, "os_list_dir") == 0) {
|
||||||
(*pos)++; /* '(' */
|
(*pos)++; /* '(' */
|
||||||
if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "os_list_dir expects (path)"); free(name); return 0; }
|
if (!emit_expression(bc, src, len, pos)) { parser_fail(*pos, "os_list_dir expects (path)"); free(name); return 0; }
|
||||||
|
|
@ -1156,6 +1197,72 @@ static int emit_primary(Bytecode *bc, const char *src, size_t len, size_t *pos)
|
||||||
free(name);
|
free(name);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
/* 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; }
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
/* 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 */
|
/* PCSC builtins */
|
||||||
if (strcmp(name, "pcsc_establish") == 0) {
|
if (strcmp(name, "pcsc_establish") == 0) {
|
||||||
(*pos)++; /* '(' */
|
(*pos)++; /* '(' */
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,9 @@ edition = "2021"
|
||||||
[lib]
|
[lib]
|
||||||
crate-type = ["staticlib"]
|
crate-type = ["staticlib"]
|
||||||
|
|
||||||
|
[profile.dev]
|
||||||
|
panic = "abort"
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
panic = "abort"
|
panic = "abort"
|
||||||
# Optimize for minimal size
|
# Optimize for minimal size
|
||||||
|
|
|
||||||
2
src/rust/eh_personality.c
Normal file
2
src/rust/eh_personality.c
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
/* Workaround for linking Rust staticlib in no_std/abort mode on some toolchains */
|
||||||
|
void rust_eh_personality(void) {}
|
||||||
|
|
@ -2,17 +2,15 @@
|
||||||
* This file is part of the Fun programming language.
|
* This file is part of the Fun programming language.
|
||||||
* https://fun-lang.xyz/
|
* https://fun-lang.xyz/
|
||||||
*
|
*
|
||||||
* Copyright 2025 Johannes Findeisen <you@hanez.org>
|
* Copyright 2026 Johannes Findeisen <you@hanez.org>
|
||||||
* Licensed under the terms of the Apache-2.0 license.
|
* Licensed under the terms of the Apache-2.0 license.
|
||||||
* https://opensource.org/license/apache-2-0
|
* https://opensource.org/license/apache-2-0
|
||||||
*
|
*
|
||||||
* Added: 2026-01-27
|
* Added: 2026-01-27
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#![no_std]
|
// Use an FFI-safe opaque handle for the VM pointer
|
||||||
|
pub type Vm = core::ffi::c_void;
|
||||||
#[repr(C)]
|
|
||||||
pub struct Vm;
|
|
||||||
|
|
||||||
extern "C" {
|
extern "C" {
|
||||||
fn vm_pop_i64(vm: *mut Vm) -> i64;
|
fn vm_pop_i64(vm: *mut Vm) -> i64;
|
||||||
|
|
@ -37,8 +35,59 @@ pub extern "C" fn fun_rust_get_string() -> *const core::ffi::c_char {
|
||||||
b"Hello from Rust ops!\0".as_ptr() as *const _
|
b"Hello from Rust ops!\0".as_ptr() as *const _
|
||||||
}
|
}
|
||||||
|
|
||||||
// Minimal panic handler for no_std; abort behavior requested via Cargo profile
|
// Print a C string via libc printf to stdout
|
||||||
#[panic_handler]
|
#[no_mangle]
|
||||||
fn panic(_info: &core::panic::PanicInfo) -> ! {
|
pub extern "C" fn fun_rust_print_string(msg: *const core::ffi::c_char) -> i32 {
|
||||||
loop {}
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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::<u8>::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<u8> 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
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
* This file is part of the Fun programming language.
|
* This file is part of the Fun programming language.
|
||||||
* https://fun-lang.xyz/
|
* https://fun-lang.xyz/
|
||||||
*
|
*
|
||||||
* Copyright 2025 Johannes Findeisen <you@hanez.org>
|
* Copyright 2026 Johannes Findeisen <you@hanez.org>
|
||||||
* Licensed under the terms of the Apache-2.0 license.
|
* Licensed under the terms of the Apache-2.0 license.
|
||||||
* https://opensource.org/license/apache-2-0
|
* https://opensource.org/license/apache-2-0
|
||||||
*
|
*
|
||||||
|
|
@ -16,10 +16,18 @@
|
||||||
//! ABI helpers declared on the C side (`vm_pop_i64`, `vm_push_i64`).
|
//! ABI helpers declared on the C side (`vm_pop_i64`, `vm_push_i64`).
|
||||||
|
|
||||||
use super::Vm;
|
use super::Vm;
|
||||||
|
//use core::mem::size_of;
|
||||||
|
use core::ptr;
|
||||||
|
|
||||||
extern "C" {
|
extern "C" {
|
||||||
fn vm_pop_i64(vm: *mut Vm) -> i64;
|
fn vm_pop_i64(vm: *mut Vm) -> i64;
|
||||||
fn vm_push_i64(vm: *mut Vm, v: 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.
|
/// 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
|
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
|
||||||
|
}
|
||||||
|
|
|
||||||
68
src/vm.c
68
src/vm.c
|
|
@ -22,6 +22,7 @@
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <stdarg.h>
|
#include <stdarg.h>
|
||||||
|
#include <stddef.h>
|
||||||
#include <time.h>
|
#include <time.h>
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
|
||||||
|
|
@ -72,6 +73,8 @@
|
||||||
#include "external/sqlite.c"
|
#include "external/sqlite.c"
|
||||||
#include "external/tcltk.c"
|
#include "external/tcltk.c"
|
||||||
#include "external/xml2.c"
|
#include "external/xml2.c"
|
||||||
|
#include "external/openssl.c"
|
||||||
|
#include "external/libressl.c"
|
||||||
|
|
||||||
/* forward declarations for include mapping used in error reporting */
|
/* forward declarations for include mapping used in error reporting */
|
||||||
extern char *preprocess_includes(const char *src);
|
extern char *preprocess_includes(const char *src);
|
||||||
|
|
@ -488,6 +491,35 @@ void vm_push_i64(VM *vm, int64_t v) {
|
||||||
push_value(vm, make_int(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) {
|
static void frame_init(Frame *f) {
|
||||||
f->fn = NULL;
|
f->fn = NULL;
|
||||||
f->ip = 0;
|
f->ip = 0;
|
||||||
|
|
@ -758,6 +790,10 @@ void vm_run(VM *vm, Bytecode *entry) {
|
||||||
|
|
||||||
/* Rust FFI demo opcode(s) */
|
/* Rust FFI demo opcode(s) */
|
||||||
#include "vm/rust/hello.c"
|
#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"
|
||||||
|
|
||||||
#include "vm/os/env.c"
|
#include "vm/os/env.c"
|
||||||
#include "vm/os/env_all.c"
|
#include "vm/os/env_all.c"
|
||||||
|
|
@ -834,6 +870,22 @@ void vm_run(VM *vm, Bytecode *entry) {
|
||||||
#include "vm/curl/download.c"
|
#include "vm/curl/download.c"
|
||||||
#endif
|
#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 */
|
/* Tk (Tcl/Tk) ops */
|
||||||
#ifdef FUN_WITH_TCLTK
|
#ifdef FUN_WITH_TCLTK
|
||||||
#include "vm/tk/eval.c"
|
#include "vm/tk/eval.c"
|
||||||
|
|
@ -863,6 +915,22 @@ void vm_run(VM *vm, Bytecode *entry) {
|
||||||
#include "vm/sqlite/query.c"
|
#include "vm/sqlite/query.c"
|
||||||
#endif
|
#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) */
|
/* libsql ops (independent) */
|
||||||
#ifdef FUN_WITH_LIBSQL
|
#ifdef FUN_WITH_LIBSQL
|
||||||
#include "vm/libsql/open.c"
|
#include "vm/libsql/open.c"
|
||||||
|
|
|
||||||
33
src/vm.h
33
src/vm.h
|
|
@ -11,6 +11,7 @@
|
||||||
#define FUN_VM_H
|
#define FUN_VM_H
|
||||||
|
|
||||||
#include "bytecode.h"
|
#include "bytecode.h"
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
#define MAX_FRAMES 128
|
#define MAX_FRAMES 128
|
||||||
#define MAX_FRAME_LOCALS 64
|
#define MAX_FRAME_LOCALS 64
|
||||||
|
|
@ -56,7 +57,9 @@ static const char *opcode_names[] = {
|
||||||
"TRY_PUSH","TRY_POP","THROW",
|
"TRY_PUSH","TRY_POP","THROW",
|
||||||
"FMIN","FMAX",
|
"FMIN","FMAX",
|
||||||
/* Rust FFI demo */
|
/* Rust FFI demo */
|
||||||
"RUST_HELLO",
|
"RUST_HELLO","RUST_HELLO_ARGS","RUST_HELLO_ARGS_RETURN","RUST_GET_SP","RUST_SET_EXIT",
|
||||||
|
/* C++ demo */
|
||||||
|
"CPP_ADD",
|
||||||
/* Notcurses TUI (optional) */
|
/* Notcurses TUI (optional) */
|
||||||
"NC_INIT","NC_SHUTDOWN","NC_CLEAR","NC_DRAW_TEXT","NC_GETCH"
|
"NC_INIT","NC_SHUTDOWN","NC_CLEAR","NC_DRAW_TEXT","NC_GETCH"
|
||||||
};
|
};
|
||||||
|
|
@ -157,5 +160,33 @@ int fun_op_radd(VM *vm);
|
||||||
|
|
||||||
/* Example Rust function returning a demo C string (null-terminated). */
|
/* Example Rust function returning a demo C string (null-terminated). */
|
||||||
const char *fun_rust_get_string(void);
|
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);
|
||||||
|
|
||||||
|
/* 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);
|
||||||
|
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
|
#endif
|
||||||
|
|
|
||||||
28
src/vm/cpp/add.cpp
Normal file
28
src/vm/cpp/add.cpp
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
/*
|
||||||
|
* This file is part of the Fun programming language.
|
||||||
|
* https://fun-lang.xyz/
|
||||||
|
*
|
||||||
|
* Copyright 2026 Johannes Findeisen <you@hanez.org>
|
||||||
|
* 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 <cstdint>
|
||||||
|
|
||||||
|
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 a = vm_pop_i64(vm);
|
||||||
|
int64_t b = vm_pop_i64(vm);
|
||||||
|
vm_push_i64(vm, a + b);
|
||||||
|
return 0; // success
|
||||||
|
}
|
||||||
27
src/vm/libressl/md5.c
Normal file
27
src/vm/libressl/md5.c
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
/*
|
||||||
|
* This file is part of the Fun programming language.
|
||||||
|
* https://fun-lang.xyz/
|
||||||
|
*
|
||||||
|
* Copyright 2026 Johannes Findeisen <you@hanez.org>
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
27
src/vm/libressl/ripemd160.c
Normal file
27
src/vm/libressl/ripemd160.c
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
/*
|
||||||
|
* This file is part of the Fun programming language.
|
||||||
|
* https://fun-lang.xyz/
|
||||||
|
*
|
||||||
|
* Copyright 2026 Johannes Findeisen <you@hanez.org>
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
27
src/vm/libressl/sha256.c
Normal file
27
src/vm/libressl/sha256.c
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
/*
|
||||||
|
* This file is part of the Fun programming language.
|
||||||
|
* https://fun-lang.xyz/
|
||||||
|
*
|
||||||
|
* Copyright 2026 Johannes Findeisen <you@hanez.org>
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
27
src/vm/libressl/sha512.c
Normal file
27
src/vm/libressl/sha512.c
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
/*
|
||||||
|
* This file is part of the Fun programming language.
|
||||||
|
* https://fun-lang.xyz/
|
||||||
|
*
|
||||||
|
* Copyright 2026 Johannes Findeisen <you@hanez.org>
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
27
src/vm/openssl/md5.c
Normal file
27
src/vm/openssl/md5.c
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
/*
|
||||||
|
* This file is part of the Fun programming language.
|
||||||
|
* https://fun-lang.xyz/
|
||||||
|
*
|
||||||
|
* Copyright 2026 Johannes Findeisen <you@hanez.org>
|
||||||
|
* 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: {
|
||||||
|
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;
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue