### Brainfuck Plugin Example Source: https://github.com/z-libs/zen-c/blob/main/docs/PLUGINS.md Provides a step-by-step guide to creating a Brainfuck transpiler plugin for Zen C, including implementation, registration, and building instructions. ```APIDOC ## Brainfuck Plugin Example ### Description This example demonstrates how to create a Zen C plugin that transpiles Brainfuck code into equivalent C code at compile time. It covers the implementation of the transpiler function, plugin registration, and the process of building the plugin as a shared object. ### Method Plugin Implementation and Registration ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```c #include "zprep_plugin.h" void bf_transpile(const char *input_body, const ZApi *api) { FILE *out = api->out; // Initialize tape and pointer in a local block. fprintf(out, "{\n"); fprintf(out, " static unsigned char tape[30000] = {0};\n"); fprintf(out, " unsigned char *ptr = tape;\n"); const char *c = input_body; while (*c) { switch (*c) { case '>': fprintf(out, " ++ptr;\n"); break; case '<': fprintf(out, " --ptr;\n"); break; case '+': fprintf(out, " ++*ptr;\n"); break; case '-': fprintf(out, " --*ptr;\n"); break; case '.': fprintf(out, " putchar(*ptr);\n"); break; case ',': fprintf(out, " *ptr = getchar();\n"); break; case '[': fprintf(out, " while (*ptr) {\n"); break; case ']': fprintf(out, " }\n"); break; } c++; } fprintf(out, "}\n"); } ZPlugin brainfuck_plugin = { .name = "brainfuck", .fn = bf_transpile }; // Entry point for the dynamic loader ZPlugin *z_plugin_init(void) { return &brainfuck_plugin; } ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Setup Lua Dependencies Source: https://github.com/z-libs/zen-c/blob/main/examples/scripting/lua/README.md This command downloads and installs the necessary Lua 5.4 headers and library files required for integrating Lua with Zen-C. The output is placed in a local 'lua' directory. ```sh ./deps.sh ``` -------------------------------- ### Using a Plugin Source: https://github.com/z-libs/zen-c/blob/main/docs/PLUGINS.md Demonstrates how to import and use a Zen C plugin with the `import plugin` syntax and the `alias! { ... }` invocation. ```APIDOC ## Using a Plugin ### Description This section explains how to import and utilize existing Zen C plugins to extend the language's capabilities. Plugins are imported using the `import plugin` statement and invoked using a custom syntax. ### Method Import and invocation ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```zc import plugin "regex" as re // or simple: import plugin "regex" (uses "regex" as identifier) fn main() { let valid = re! { ^[a-z]+$ }; } ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Zen C Compiler Usage Examples Source: https://github.com/z-libs/zen-c/blob/main/README.md Demonstrates common Zen C compiler commands for running, building, and entering the interactive Read-Eval-Print Loop (REPL). ```bash # Compile and run zc run hello.zc # Build executable zc build hello.zc -o hello # Interactive Shell zc repl ``` -------------------------------- ### Using a Compiled Zen C Plugin Source: https://github.com/z-libs/zen-c/blob/main/docs/PLUGINS.md Illustrates how to import and use a compiled Zen C plugin within Zen C code. It shows both relative and system-wide import methods, followed by an example of invoking the plugin using the `alias! { ... }` syntax. ```zc // Relative import (finds .so relative to this file) import plugin "./brainfuck.so" as bf // System import (finds .so in CWD or library path) import plugin "brainfuck.so" as bf2 fn main() { bf! { ++++++++++[>+++++++>++++++++++>+++<<<-]>++. } } ``` -------------------------------- ### Example: Building and Serializing JSON in Zen-C Source: https://github.com/z-libs/zen-c/blob/main/docs/std/json.md This example demonstrates creating a JSON object, setting key-value pairs, serializing it to a string, printing it, and freeing the allocated memory in Zen-C. ```Zen-C let obj = JsonValue::object(); obj.set("name", JsonValue::string("Alice")); obj.set("age", JsonValue::number(30.0)); let json_str = obj.to_string(); println "{json_str.c_str()}"; // {"name":"Alice","age":30} json_str.free(); obj.free(); ``` -------------------------------- ### Queue Usage Example (Z-C) Source: https://github.com/z-libs/zen-c/blob/main/docs/std/queue.md Demonstrates how to create, push elements to, and pop elements from a generic `Queue` in Z-C. It highlights the use of `Option` for pop operations. ```zc import "std/queue.zc" fn main() { let q = Queue::new(); q.push(1); q.push(2); q.push(3); // Pop returns an Option if (q.pop().is_some()) { println "Popped: {q.pop().unwrap()}"; // 1 } } ``` -------------------------------- ### Building and Using the Plugin Source: https://github.com/z-libs/zen-c/blob/main/docs/PLUGINS.md Instructions on how to compile a Zen C plugin into a shared object and how to import and use it within Zen C code. ```APIDOC ## Building and Using the Plugin ### Description This section provides the necessary commands to compile a C plugin into a shared object (`.so`) file and demonstrates how to import and utilize this plugin within your Zen C source code. ### Method Compilation and Import ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example **Building the plugin:** ```bash # If building from source repository: gcc -shared -fPIC -o brainfuck.so brainfuck.c -I./plugins # If Zen C is installed system-wide: gcc -shared -fPIC -o brainfuck.so brainfuck.c -I/usr/local/include/zenc ``` **Using the plugin in Zen C:** ```zc // Relative import (finds .so relative to this file) import plugin "./brainfuck.so" as bf // System import (finds .so in CWD or library path) import plugin "brainfuck.so" as bf2 fn main() { bf! { ++++++++++[>+++++++>++++++++++>+++<<<-]>++. } } ``` ### Response #### Success Response (200) N/A #### Response Example **Generated C code:** ```c { static unsigned char tape[30000] = {0}; unsigned char *ptr = tape; ++*ptr; ++*ptr; // ... (logic for + and [ ) while (*ptr) { ++ptr; // ... } ptr++; // ... putchar(*ptr); } ``` ``` -------------------------------- ### Variadic Functions in Zen C Source: https://github.com/z-libs/zen-c/blob/main/README.md Demonstrates how to define and use variadic functions in Zen C, which accept a variable number of arguments using `...` and `va_list`. Includes an example using C's `vprintf` for formatted output. ```zc fn log(lvl: int, fmt: char*, ...) { let ap: va_list; va_start(ap, fmt); vprintf(fmt, ap); // Use C stdio va_end(ap); } ``` -------------------------------- ### Example: Safe indexed access Source: https://github.com/z-libs/zen-c/blob/main/docs/std/slice.md Illustrates how to create a slice manually and use the `get` method for safe, bounds-checked access to elements. ```APIDOC ## Example: Safe indexed access ```zc import "std/slice.zc" let arr: int[3] = [1, 2, 3]; let slice = Slice::from_array((int*)(&arr), 3); let opt = slice.get(1); if (!opt.is_none()) { println "Value: {opt.unwrap()}"; // Prints: Value: 2 } ``` ### Description This example demonstrates creating a `Slice` from a fixed-size array `arr`. It then uses the `get(1)` method to safely access the element at index 1. The result is an `Option`, which is checked for `None` before unwrapping to retrieve the value. This prevents potential out-of-bounds errors. ``` -------------------------------- ### Plugin API Reference (`zprep_plugin.h`) Source: https://github.com/z-libs/zen-c/blob/main/docs/PLUGINS.md Details the C API provided for creating Zen C plugins, including the `ZApi` struct and the `ZPluginTranspileFn` function signature. ```APIDOC ## Plugin API Reference (`zprep_plugin.h`) ### Description This section outlines the core C API available for developing Zen C plugins. It defines the necessary structures and function types that a plugin must implement to interact with the Zen C compiler. ### Method C API Definition ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```c typedef struct { // -> Context information const char *filename; // Current file being compiled int current_line; // Line number of the invocation FILE *out; // Output stream (injects code at call site) FILE *hoist_out; // Hoisted output (injects code at file scope) } ZApi; // -> The transpiler function // input_body: The raw text inside the plugin block { ... } // api: Access to transpiler context and output streams typedef void (*ZPluginTranspileFn)(const char *input_body, const ZApi *api); typedef struct { char name[32]; ZPluginTranspileFn fn; } ZPlugin; ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### String Usage Example Source: https://github.com/z-libs/zen-c/blob/main/docs/std/string.md Demonstrates basic usage of the String type, including creation from a C string, appending other strings, and printing the C-compatible string representation. It also shows how to ensure memory is freed using `defer`. ```zc import "std/string.zc" fn main() { let s = String::from("Hello"); // Ensure memory is freed defer { s.free(); } // Append requires a pointer to another String let part = String::from(" World"); defer { part.free(); } s.append(&part); // Use c_str() to print println "{s.c_str()}"; // Prints "Hello World" if (s.starts_with("Hello")) { // ... } } ``` -------------------------------- ### Zen-C Path Module Usage Example Source: https://github.com/z-libs/zen-c/blob/main/docs/std/path.md Demonstrates how to import and use the Path module for creating, joining, and extracting information from file paths. It shows path construction, joining with other path components, and retrieving file extensions. ```zc import "std/path.zc" fn main() { let p = Path::new("/home/user"); let full_path = p.join("docs/file.txt"); println "Full path: {full_path.c_str()}"; if (full_path.extension().is_some()) { println "Extension: {full_path.extension().unwrap()}"; } } ``` -------------------------------- ### Conditional Statements in Zen C Source: https://github.com/z-libs/zen-c/blob/main/README.md Shows the syntax for conditional execution in Zen C, including `if-else if-else` chains and the ternary operator. Provides examples for basic conditional logic. ```zc if x > 10 { print("Large"); } else if x > 5 { print("Medium"); } else { print("Small"); } // Ternary let y = x > 10 ? 1 : 0; ``` -------------------------------- ### Extending Syntax with Compiler Plugins Source: https://github.com/z-libs/zen-c/blob/main/README.md Zen C supports importing compiler plugins to extend the language's syntax. This example shows importing a 'regex' plugin to use regular expression literals. ```zc import plugin "regex" let re = regex! { ^[a-z]+$ }; ``` -------------------------------- ### Zen C Language Server Command Source: https://github.com/z-libs/zen-c/blob/main/README.md Starts the Zen C Language Server (LSP) for editor integration. This command facilitates features like code completion, go-to-definition, and diagnostics by communicating over standard I/O using JSON-RPC 2.0. ```bash zc lsp ``` -------------------------------- ### Importing a Zen C Plugin Source: https://github.com/z-libs/zen-c/blob/main/docs/PLUGINS.md Demonstrates how to import and use a Zen C plugin using the `import plugin` syntax. The `alias! { ... }` syntax invokes the plugin, passing the content within the braces as a raw string to the plugin's transpiler function. ```zc import plugin "regex" as re // or simple: import plugin "regex" (uses "regex" as identifier) fn main() { let valid = re! { ^[a-z]+$ }; } ``` -------------------------------- ### Objective-C Interoperability in Zen C Source: https://github.com/z-libs/zen-c/blob/main/README.md Zen C allows direct use of Objective-C syntax and frameworks. Headers are included using `include`, and Objective-C code snippets are placed within `raw` blocks. This example demonstrates basic Objective-C usage with Foundation framework and string interpolation. ```zc //> macos: framework: Foundation //> linux: cflags: -fconstant-string-class=NSConstantString -D_NATIVE_OBJC_EXCEPTIONS //> linux: link: -lgnustep-base -lobjc include fn main() { raw { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSLog(@"Hello from Objective-C!"); [pool drain]; } println "Zen C works too!"; } ``` -------------------------------- ### Lambdas (Closures) in Zen C Source: https://github.com/z-libs/zen-c/blob/main/README.md Shows the definition of anonymous functions (lambdas or closures) in Zen C, which can capture their environment. Provides examples using both arrow and block syntax. ```zc let factor = 2; let double = x -> x * factor; // Arrow syntax let full = fn(x: int) -> int { return x * factor; }; // Block syntax ``` -------------------------------- ### Build Directives and Raylib Integration in Zen C Source: https://context7.com/z-libs/zen-c/llms.txt Illustrates Zen C's build directives for configuring compilation, including linking libraries, setting include paths, defining preprocessor macros, and handling platform-specific settings. It also shows a basic example of integrating the Raylib library. ```zc //> include: ./include //> lib: ./libs //> link: -lraylib -lm //> cflags: -O3 -Wall //> pkg-config: gtk+-3.0 //> define: DEBUG=1 // Platform-specific directives //> linux: link: -lpthread //> windows: link: -lws2_32 //> macos: framework: Cocoa // Environment variable expansion //> include: ${HOME}/mylib/include //> lib: ${ZC_ROOT}/std // Download dependencies //> get: https://example.com/lib.h -> deps/lib.h import "raylib.h" fn main() { InitWindow(800, 600, "Hello Raylib"); while !WindowShouldClose() { BeginDrawing(); ClearBackground(RAYWHITE); DrawText("Hello, World!", 190, 200, 20, LIGHTGRAY); EndDrawing(); } CloseWindow(); } ``` -------------------------------- ### Zen C C++ Interoperability Example Source: https://github.com/z-libs/zen-c/blob/main/README.md This Zen C code demonstrates C++ interoperability by including C++ headers and using raw blocks for C++ code. It shows how to define and use C++ functions within Zen C. ```zc include include raw { std::vector make_vec(int a, int b) { return {a, b}; } } fn main() { let v = make_vec(1, 2); raw { std::cout << "Size: " << v.size() << std::endl; } } ``` -------------------------------- ### Zen C CUDA Kernel Example Source: https://github.com/z-libs/zen-c/blob/main/README.md This Zen C code defines and launches a CUDA kernel for element-wise addition. It demonstrates the use of `@global` attribute for kernel functions, `thread_id()`, `cuda_alloc`, `cuda_free`, and `cuda_sync`. ```zc import "std/cuda.zc" @global fn add_kernel(a: float*, b: float*, c: float*, n: int) { let i = thread_id(); if i < n { c[i] = a[i] + b[i]; } } fn main() { def N = 1024; let d_a = cuda_alloc(N); let d_b = cuda_alloc(N); let d_c = cuda_alloc(N); defer cuda_free(d_a); defer cuda_free(d_b); defer cuda_free(d_c); // ... init data ... launch add_kernel(d_a, d_b, d_c, N) with { grid: (N + 255) / 256, block: 256 }; cuda_sync(); } ``` -------------------------------- ### TCP Server and Client in Z-Lang Source: https://context7.com/z-libs/zen-c/llms.txt Provides examples for creating a TCP server that listens for connections and echoes received data, and a TCP client that connects to a server, sends a message, and prints the response. It utilizes the `std/net.zc` module. ```zc import "std/net.zc" // TCP Server Example fn run_server() { let listener_res = TcpListener::bind("127.0.0.1", 8080); guard listener_res.is_ok() else { eprintln "Failed to bind: {listener_res.err}"; return; } let listener = listener_res.unwrap(); println "Server listening on 127.0.0.1:8080"; loop { let client_res = listener.accept(); if client_res.is_ok() { let stream = client_res.unwrap(); println "Client connected"; let buf: char[1024]; // Echo loop while true { let read_res = stream.read(&buf[0], 1024); if read_res.is_err() || read_res.unwrap() == 0 { break; } let bytes = read_res.unwrap(); stream.write(&buf[0], bytes); } println "Client disconnected"; // stream auto-closed via Drop } } } // TCP Client Example fn run_client() { let conn_res = TcpStream::connect("127.0.0.1", 8080); guard conn_res.is_ok() else { eprintln "Failed to connect: {conn_res.err}"; return; } let stream = conn_res.unwrap(); println "Connected to server"; // Send message let msg = "Hello, Server!"; stream.write(msg, strlen(msg)); // Receive response let buf: char[1024]; let read_res = stream.read(&buf[0], 1024); if read_res.is_ok() { let bytes = read_res.unwrap(); buf[bytes] = 0; println "Received: {&buf[0]}"; } // stream auto-closed via Drop } fn main() { // Run either server or client run_client(); } ``` -------------------------------- ### Zen C Option Type Usage Example Source: https://github.com/z-libs/zen-c/blob/main/docs/std/option.md Demonstrates how to use the `Option` type in Zen C for handling optional values. It shows creating `Some` and `None` variants and using methods like `is_some` and `unwrap_or`. ```zc import "std/option.zc" fn main() { let val = Option::Some(10); if (val.is_some()) { println "{val.unwrap()}"; } let nothing = Option::None(); println "{nothing.unwrap_or(0)}"; // Prints 0 } ``` -------------------------------- ### Building a Zen C Plugin Shared Object Source: https://github.com/z-libs/zen-c/blob/main/docs/PLUGINS.md Provides GCC commands for compiling a C plugin into a shared object (`.so`) file. It includes flags for creating a shared library (`-shared`, `-fPIC`) and specifying the include path for Zen C headers. ```bash # If building from source repository: gcc -shared -fPIC -o brainfuck.so brainfuck.c -I./plugins # If Zen C is installed system-wide: gcc -shared -fPIC -o brainfuck.so brainfuck.c -I/usr/local/include/zenc ``` -------------------------------- ### Map Usage Example in Zen-C Source: https://github.com/z-libs/zen-c/blob/main/docs/std/map.md Demonstrates the basic usage of the `Map` generic hash map in Zen-C. This includes creating a new map, inserting key-value pairs, checking for key existence, retrieving values, and removing entries. Note that the map's internal storage is freed automatically, but values (especially pointers) are not. ```zc import "std/map.zc" fn main() { let m = Map::new(); m.put("one", 1); m.put("two", 2); if (m.contains("one")) { let val = m.get("one"); println "{val.unwrap()}"; } m.remove("two"); } // m is freed automatically (but values are NOT freed automatically if they are pointers) ``` -------------------------------- ### Registering a Zen C Plugin in C Source: https://github.com/z-libs/zen-c/blob/main/docs/PLUGINS.md Shows how to register a C plugin for Zen C. It defines a `ZPlugin` struct with the plugin's name and transpiler function, and exports a `z_plugin_init` function that returns a pointer to this struct, making the plugin discoverable by the dynamic loader. ```c ZPlugin brainfuck_plugin = { .name = "brainfuck", .fn = bf_transpile }; // Entry point for the dynamic loader ZPlugin *z_plugin_init(void) { return &brainfuck_plugin; } ``` -------------------------------- ### Zen C Plugin API Reference (zprep_plugin.h) Source: https://github.com/z-libs/zen-c/blob/main/docs/PLUGINS.md Defines the core C API for Zen C plugins. It includes the `ZApi` struct for context information (filename, line number, output streams) and the `ZPluginTranspileFn` function pointer type for the transpiler logic. ```c typedef struct { // -> Context information const char *filename; // Current file being compiled int current_line; // Line number of the invocation FILE *out; // Output stream (injects code at call site) FILE *hoist_out; // Hoisted output (injects code at file scope) } ZApi; // -> The transpiler function // input_body: The raw text inside the plugin block { ... } // api: Access to transpiler context and output streams typedef void (*ZPluginTranspileFn)(const char *input_body, const ZApi *api); typedef struct { char name[32]; ZPluginTranspileFn fn; } ZPlugin; ``` -------------------------------- ### Implementing a Brainfuck Transpiler Plugin in C Source: https://github.com/z-libs/zen-c/blob/main/docs/PLUGINS.md Provides the C code for a Brainfuck transpiler plugin. The `bf_transpile` function takes Brainfuck code as input and generates equivalent C code, writing it to the provided output stream. ```c #include "zprep_plugin.h" void bf_transpile(const char *input_body, const ZApi *api) { FILE *out = api->out; // Initialize tape and pointer in a local block. fprintf(out, "{\n"); fprintf(out, " static unsigned char tape[30000] = {0};\n"); fprintf(out, " unsigned char *ptr = tape;\n"); const char *c = input_body; while (*c) { switch (*c) { case '>': fprintf(out, " ++ptr;\n"); break; case '<': fprintf(out, " --ptr;\n"); break; case '+': fprintf(out, " ++*ptr;\n"); break; case '-': fprintf(out, " --*ptr;\n"); break; case '.': fprintf(out, " putchar(*ptr);\n"); break; case ',': fprintf(out, " *ptr = getchar();\n"); break; case '[': fprintf(out, " while (*ptr) {\n"); break; case ']': fprintf(out, " }\n"); break; } c++; } fprintf(out, "}\n"); } ``` -------------------------------- ### Zen-C Vector Usage Example Source: https://github.com/z-libs/zen-c/blob/main/docs/std/vec.md Demonstrates the basic usage of the `Vec` type in Zen-C, including creating a new vector, pushing elements, and iterating over its contents. The example highlights automatic memory management when the vector goes out of scope. ```Zen-C import "std/vec.zc" fn main() { let v = Vec::new(); v.push(10); v.push(20); // Iteration for x in &v { println "{(*x)}"; } } // v is freed automatically here ``` -------------------------------- ### Time Utilities Source: https://github.com/z-libs/zen-c/blob/main/docs/std/time.md This section covers the Time struct and its associated methods for getting the current time and sleeping. ```APIDOC ## Time Utilities ### Description Provides utilities for time manipulation, including getting the current system time and pausing execution. ### Methods #### `fn now() -> U64` - **Description**: Returns the current system time in milliseconds since the epoch. - **Method**: N/A (Function within a module) - **Endpoint**: N/A #### `fn sleep(d: Duration)` - **Description**: Sleeps for the specified duration. - **Method**: N/A (Function within a module) - **Endpoint**: N/A - **Parameters**: - **Path Parameters**: None - **Query Parameters**: None - **Request Body**: None - **Request Example**: None - **Response**: None #### `fn sleep_ms(ms: U64)` - **Description**: Sleeps for the specified number of milliseconds. - **Method**: N/A (Function within a module) - **Endpoint**: N/A - **Parameters**: - **Path Parameters**: None - **Query Parameters**: None - **Request Body**: None - **Request Example**: None - **Response**: None ``` -------------------------------- ### Build Zen C Compiler with Zig Source: https://github.com/z-libs/zen-c/blob/main/README.md This command shows how to build the Zen C compiler itself using Zig. This is useful for leveraging Zig's build system and cross-compilation capabilities. ```bash make zig ``` -------------------------------- ### Zen-C Get Current Time Source: https://github.com/z-libs/zen-c/blob/main/docs/std/time.md Retrieves the current system time in milliseconds since the epoch using the `now()` function from the `std/time` module. ```zc let current_time = Time.now() ``` -------------------------------- ### Example: Iterating over fixed-size arrays Source: https://github.com/z-libs/zen-c/blob/main/docs/std/slice.md Demonstrates how to iterate over a fixed-size array using the `for-in` loop, which implicitly uses `std/slice.zc`. ```APIDOC ## Example: Iterating over fixed-size arrays ```zc // std/slice.zc is auto-imported when using for-in on arrays let numbers: int[3] = [10, 20, 30]; for n in numbers { println "Number: {n}"; } ``` ### Description This example shows the convenience of iterating directly over fixed-size arrays in Zen-C. The `for-in` loop automatically handles the creation of a slice and iteration, making the code concise. `std/slice.zc` does not need to be explicitly imported in this case. ``` -------------------------------- ### Zen-C File Static Utility Methods Source: https://github.com/z-libs/zen-c/blob/main/docs/std/fs.md Lists static utility methods for file system operations. These include `exists` to check path existence, `metadata` to retrieve file/directory information, `create_dir` and `remove_dir` for directory management, `remove_file` for deleting files, and `read_dir` for listing directory contents. ```zc // Checks if a path exists. File::exists(path: char*) -> bool // Retrieves metadata for a path. File::metadata(path: char*) -> Result // Creates a new directory. File::create_dir(path: char*) -> Result // Deletes a file. File::remove_file(path: char*) -> Result // Deletes a directory. File::remove_dir(path: char*) -> Result // Reads the contents of a directory. Returns a vector of `DirEntry`. File::read_dir(path: char*) -> Result> ``` -------------------------------- ### Compile and Run Zen C with Different C Compilers Source: https://github.com/z-libs/zen-c/blob/main/README.md This command demonstrates how to compile and run a Zen C program using different C compilers as backends. The `--cc` flag allows you to specify the desired compiler, such as clang or zig. ```bash zc run app.zc --cc clang zc run app.zc --cc zig ``` -------------------------------- ### Retrieving Values from JSON Objects in Zen-C Source: https://github.com/z-libs/zen-c/blob/main/docs/std/json.md This snippet shows how to retrieve a value from a JSON object by its key using the `get` method in Zen-C. It returns an `Option`. ```Zen-C fn get(self, key: char*) -> Option ``` -------------------------------- ### Raw Function Pointers in Zen C Source: https://github.com/z-libs/zen-c/blob/main/README.md Illustrates the use of raw C function pointers in Zen C via the `fn*` syntax for seamless C library interop. Demonstrates functions taking and returning function pointers, and pointer-to-pointer support. ```zc // Function taking a raw function pointer fn set_callback(cb: fn*(int)) { cb(42); } // Function returning a raw function pointer fn get_callback() -> fn*(int) { return my_handler; } // Pointers to function pointers are supported (fn**) let pptr: fn**(int) = &ptr; ``` -------------------------------- ### Function Definitions and Calls in Zen C Source: https://github.com/z-libs/zen-c/blob/main/README.md Illustrates basic function definition with typed arguments and return values in Zen C. Shows support for named arguments, emphasizing the strict parameter order requirement. ```zc fn add(a: int, b: int) -> int { return a + b; } // Named arguments supported in calls add(a: 10, b: 20); ``` -------------------------------- ### Map Iteration Example in Zen-C Source: https://github.com/z-libs/zen-c/blob/main/docs/std/map.md Illustrates how to iterate over key-value pairs in a Zen-C `Map` using a `for` loop. Each iteration yields a `MapEntry` struct containing the key and its associated value. ```zc let m = Map::new(); m.put("a", 1); for entry in m { println "Key: {entry.key}, Val: {entry.val}"; } ``` -------------------------------- ### Zen-C File Open and Close Methods Source: https://github.com/z-libs/zen-c/blob/main/docs/std/fs.md Provides the signatures for opening and closing files using the `File::open` and `close` methods. `File::open` takes a path and mode, returning a `Result`, while `close` takes a file handle to release resources. ```zc // Opens a file with the specified mode (e.g., "r", "w", "rb"). Returns a `Result`. File::open(path: char*, mode: char*) -> Result // Closes the file handle. close(self) ``` -------------------------------- ### Zen-C Identifier Definition Source: https://github.com/z-libs/zen-c/blob/main/docs/lex.md Specifies the structure of identifiers in Zen-C, which are used to name variables, functions, and types. An identifier must start with a letter or underscore, followed by zero or more alphanumeric characters or underscores. ```text Identifier ::= IdentifierStart IdentifierPart* IdentifierStart ::= [a-zA-Z_] IdentifierPart ::= [a-zA-Z0-9_] ``` -------------------------------- ### Import Zen-C Set Module Source: https://github.com/z-libs/zen-c/blob/main/docs/std/set.md Demonstrates how to import the generic hash set module in Zen-C. This is the first step to using set functionalities. ```zc import "std/set.zc" ``` -------------------------------- ### Spawn and Interact with Child Processes using std/process.zc Source: https://github.com/z-libs/zen-c/blob/main/docs/std/process.md This snippet demonstrates how to use the `std/process.zc` module to spawn a child process, execute a command (e.g., 'echo'), and capture its standard output. It checks the exit code to ensure successful execution before printing the output. ```zc import "std/process.zc" fn main() { let output = Command::new("echo") .arg("hello") .output(); if (output.exit_code == 0) { output.stdout.print(); // Or access raw C string: output.stdout.c_str() } } ``` -------------------------------- ### Access Environment Variables with Zen-C std/env.zc Source: https://github.com/z-libs/zen-c/blob/main/docs/std/env.md Demonstrates basic usage of the `std/env.zc` library to set an environment variable, retrieve its value, and print it. This example showcases the `Env::set` and `Env::get` functions. ```zc import "std/env.zc" fn main() { Env::set("HELLO", "world"); let hello = Env::get("HELLO"); if (hello.is_some()) { println "Hello {hello.unwrap()}"; } } ``` -------------------------------- ### Running Zen C Test Suite Source: https://github.com/z-libs/zen-c/blob/main/README.md The Zen C project includes a comprehensive test suite to ensure code quality and functionality. Tests can be run using `make test` for all tests, or specific tests can be executed using `./zc run`. The test runner also supports specifying different backend compilers like clang, zig, or tcc. ```bash # Run all tests (GCC) make test # Run specific test ./zc run tests/test_match.zc # Run with different compiler ./tests/run_tests.sh --cc clang ./tests/run_tests.sh --cc zig ./tests/run_tests.sh --cc tcc ``` -------------------------------- ### Pattern Matching in Zen C Source: https://github.com/z-libs/zen-c/blob/main/README.md Illustrates Zen C's powerful pattern matching capabilities as an alternative to switch statements. Covers various matching constructs including OR operators, ranges (exclusive and inclusive), and destructuring enums. ```zc match val { 1 => { print "One" }, 2 || 3 => { print "Two or Three" }, // OR with || 4 or 5 => { print "Four or Five" }, // OR with 'or' 6, 7, 8 => { print "Six to Eight" }, // OR with comma 10 .. 15 => { print "10 to 14" }, // Exclusive range (Legacy) 10 ..< 15 => { print "10 to 14" }, // Exclusive range (Explicit) 20 ..= 25 => { print "20 to 25" }, // Inclusive range _ => { print "Other" }, } // Destructuring Enums match shape { Shape::Circle(r) => println "Radius: {r}", Shape::Rect(w, h) => println "Area: {w*h}", Shape::Point => println "Point" } ``` -------------------------------- ### Result Type Usage Example (zc) Source: https://github.com/z-libs/zen-c/blob/main/docs/std/result.md Demonstrates how to use the Result type for error handling in z-c. It shows function definition returning a Result, checking the result's state, and extracting values or errors. ```zc import "std/result.zc" fn divide(a: int, b: int) -> Result { if (b == 0) { return Result::Err("Division by zero"); } return Result::Ok(a / b); } fn main() { let res = divide(10, 2); if (res.is_ok()) { println "Result: {res.unwrap()}"; } else { println "Error: {res.err}"; } } ``` -------------------------------- ### File System Operations in Zen-C Source: https://github.com/z-libs/zen-c/blob/main/docs/std/fs.md Demonstrates common file system interactions using the `std/fs.zc` module. This includes opening, reading, and closing files, as well as checking for file existence. It highlights the use of `Result` for handling potential errors during file operations. ```zc import "std/fs.zc" fn main() { // Reading a file let res = File::open("example.txt", "r"); if (res.is_ok()) { let file = res.unwrap(); let content = file.read_to_string(); if (content.is_ok()) { println "{content.unwrap()}"; } file.close(); } // Static utilities if (File::exists("data")) { println "Data directory exists"; } } ``` -------------------------------- ### Zen-C Path Parsing Methods Source: https://github.com/z-libs/zen-c/blob/main/docs/std/path.md Offers methods to extract specific parts of a file path. `extension` gets the file extension, `file_name` retrieves the last component, and `parent` returns the directory path. ```zc // Returns the file extension (without the dot), or `None` if no extension. // extension(self) -> Option // Returns the last component of the path. // file_name(self) -> Option // Returns the path without its final component. // parent(self) -> Option ``` -------------------------------- ### Basic IO Operations in Z-C Source: https://github.com/z-libs/zen-c/blob/main/docs/std/io.md Demonstrates fundamental input and output operations using the std/io module. This includes printing messages, formatting strings into new buffers, and reading a line of text from the user. Note that functions like `format_new` and `readln` return heap-allocated strings that require manual deallocation. ```zc import "std/io.zc" fn main() { // Printing io.println("Hello %s", "World"); // Formatting strings autofree let s = io.format_new("Value: %d", 42); // Reading input io.print("Enter name: "); autofree let name = io.readln(); } ``` -------------------------------- ### Zen-C std/env.zc Method Signatures Source: https://github.com/z-libs/zen-c/blob/main/docs/std/env.md Provides the function signatures for key methods within the `std/env.zc` library. These include `get` for borrowed retrieval, `get_dup` for owned retrieval, `set` for setting variables, and `unset` for removing them. ```zc fn get(name: string) -> Option fn get_dup(name: string) -> Option fn set(name: string, value: string) -> EnvRes fn unset(name: string) -> EnvRes ``` -------------------------------- ### Zen C Functions and Lambdas Source: https://context7.com/z-libs/zen-c/llms.txt Illustrates function definitions, including named arguments, default parameters, and multiple return values. Also covers lambda expressions (closures) with both arrow and block syntax. ```zc // Basic function with return type fn add(a: int, b: int) -> int { return a + b; } // Function with default arguments fn greet(name: string, prefix: string = "Hello") { println "{prefix}, {name}!"; } // Const parameters (read-only) fn print_value(v: const int) { println "Value: {v}"; } // Multiple return values with tuples fn divmod(a: int, b: int) -> (int, int) { return (a / b, a % b); } // Lambda (closure) syntax fn apply(x: int, f: fn(int) -> int) -> int { return f(x); } fn main() { // Named arguments (must follow parameter order) let sum = add(a: 10, b: 20); // Default arguments greet("World"); // "Hello, World!" greet("Zen", "Welcome"); // "Welcome, Zen!" // Tuple destructuring let (quot, rem) = divmod(17, 5); println "17 / 5 = {quot} remainder {rem}"; // Arrow lambda syntax let double = x -> x * 2; // Block lambda syntax let square = fn(x: int) -> int { return x * x; }; // Using lambdas let result = apply(5, double); println "5 * 2 = {result}"; // Closure capturing environment let factor = 3; let triple = x -> x * factor; println "4 * 3 = {triple(4)}"; } ``` -------------------------------- ### Safe Indexed Access Using Slice.get in Zen C Source: https://github.com/z-libs/zen-c/blob/main/docs/std/slice.md Demonstrates how to safely access elements of a slice using the `get()` method, which returns an `Option`. This prevents out-of-bounds errors by returning `None` if the index is invalid. ```zc import "std/slice.zc" let arr: int[3] = [1, 2, 3]; let slice = Slice::from_array((int*)(&arr), 3); let opt = slice.get(1); if (!opt.is_none()) { println "Value: {opt.unwrap()}"; // Prints: Value: 2 } ``` -------------------------------- ### Generated C Code from Brainfuck Plugin Source: https://github.com/z-libs/zen-c/blob/main/docs/PLUGINS.md Shows the C code generated by the Brainfuck Zen C plugin when processing a specific Brainfuck input. This demonstrates how the plugin translates Brainfuck operations into equivalent C code for execution. ```c { static unsigned char tape[30000] = {0}; unsigned char *ptr = tape; ++*ptr; ++*ptr; // ... (logic for + and [ ) while (*ptr) { ++ptr; // ... } ptr++; // ... putchar(*ptr); } ``` -------------------------------- ### Build Portable Executable (APE) with Cosmopolitan Libc Source: https://github.com/z-libs/zen-c/blob/main/README.md Compiles Zen C into an Actually Portable Executable (APE) using the Cosmopolitan Libc toolchain. This results in a single binary that runs on multiple operating systems and architectures. Prerequisites include the `cosmocc` toolchain. ```bash make ape sudo env "PATH=$PATH" make install-ape ``` -------------------------------- ### Zen-C Whitespace and Comment Definitions Source: https://github.com/z-libs/zen-c/blob/main/docs/lex.md Defines the lexical rules for whitespace and comments in Zen-C. Whitespace is used to separate tokens and is generally ignored, while comments are treated as whitespace. This includes line comments starting with '//' and block comments enclosed in '/* ... */'. ```text Whitespace ::= [ \t\n\r]+ Comment ::= LineComment | BlockComment LineComment ::= "//" ~[\n]* BlockComment ::= "/*" (BlockComment | ~(\"*/\"))* "*/" ``` -------------------------------- ### Zen C REPL Command Source: https://github.com/z-libs/zen-c/blob/main/README.md Launches the Zen C Read-Eval-Print Loop (REPL) for interactive code experimentation. This tool allows developers to quickly test snippets and explore language features in real-time. ```bash zc repl ``` -------------------------------- ### Zen-C Set Methods Source: https://github.com/z-libs/zen-c/blob/main/docs/std/set.md Illustrates common operations on the Set data structure in Zen-C, including creation, addition, checking for containment, removal, and size. ```zc fn new() -> Set fn add(self, val: T) -> bool fn contains(self, val: T) -> bool fn remove(self, val: T) -> bool fn length(self) -> usize fn is_empty(self) -> bool fn clear(self) ``` -------------------------------- ### Threads and Synchronization in Z-Lang Source: https://context7.com/z-libs/zen-c/llms.txt Illustrates how to spawn multiple threads and use a mutex for synchronization to safely increment a shared counter. It includes joining threads to wait for their completion and a utility for pausing execution. ```zc import "std/thread.zc" static let counter: int = 0; static let mutex: Mutex; fn worker() { for i in 0..1000 { mutex.lock(); counter = counter + 1; mutex.unlock(); } println "Worker done"; } fn main() { mutex = Mutex::new(); // Spawn multiple threads let t1_res = Thread::spawn(worker); let t2_res = Thread::spawn(worker); let t3_res = Thread::spawn(worker); guard t1_res.is_ok() && t2_res.is_ok() && t3_res.is_ok() else { eprintln "Failed to spawn threads"; return; } let t1 = t1_res.unwrap(); let t2 = t2_res.unwrap(); let t3 = t3_res.unwrap(); // Wait for threads to complete t1.join(); t2.join(); t3.join(); println "Final counter: {counter}"; // Expected: 3000 (3 threads * 1000 increments) // Sleep utility sleep_ms(100); // Sleep for 100 milliseconds } ``` -------------------------------- ### String Construction Source: https://github.com/z-libs/zen-c/blob/main/docs/std/string.md Methods for creating new String instances. ```APIDOC ## String Construction ### Description Methods for creating new String instances. ### Methods #### `String::new(s: char*) -> String` Creates a new String from a C string primitive. #### `String::from(s: char*) -> String` Alias for `new`. ### Request Example ```zc let s = String::new("Hello"); let s_alias = String::from("World"); ``` ### Response #### Success Response (200) - **String** (String) - The newly created String object. #### Response Example ```json { "example": "String object" } ``` ``` -------------------------------- ### Zen-C File Read and Write Methods Source: https://github.com/z-libs/zen-c/blob/main/docs/std/fs.md Details the methods for reading and writing file content. `read_to_string` reads the entire file into a `String`, returning a `Result`. `File::read_all` is a static utility for one-off reads, and `write_string` writes a string to the file. ```zc // Reads the entire file content into a String. read_to_string(self) -> Result // Static utility to open, read, and close a file in one go. File::read_all(path: char*) -> Result // Writes a string to the file. write_string(self, content: char*) -> Result ``` -------------------------------- ### Zen C CUDA Kernel Launch Syntax Source: https://github.com/z-libs/zen-c/blob/main/README.md This Zen C code snippet illustrates the syntax for launching CUDA kernels. It uses the `launch` statement with options for grid, block, shared memory, and stream. ```zc launch kernel_name(args) with { grid: num_blocks, block: threads_per_block, shared_mem: 1024, // Optional stream: my_stream // Optional }; ``` -------------------------------- ### Zen C Build Directives: OS Guarding and Environment Variables Source: https://github.com/z-libs/zen-c/blob/main/README.md Zen C supports OS-specific build directives and environment variable expansion within comments. Directives like `link:`, `include:`, and `lib:` can be prefixed with OS names (linux, windows, macos) or use `${VAR}` syntax for dynamic paths. ```zc //> linux: link: -lm //> windows: link: -lws2_32 //> macos: framework: Cocoa ``` ```zc //> include: ${HOME}/mylib/include //> lib: ${ZC_ROOT}/std ``` ```zc //> include: ./include //> lib: ./libs //> link: -lraylib -lm //> cflags: -Ofast //> pkg-config: gtk+-3.0 import "raylib.h" fn main() { ... } ``` -------------------------------- ### Bind TCP Listener (`std/net.zc`) Source: https://github.com/z-libs/zen-c/blob/main/docs/std/net.md Demonstrates how to create a TCP listener bound to a specific host and port using the `std/net.zc` module. This function is essential for setting up a server to accept incoming client connections. ```zc import "std/net.zc" fn main() { let listener_result = std/net.TcpListener.bind("127.0.0.1", 8080) if listener_result.is_ok() { let listener = listener_result.unwrap() // Listener is ready to accept connections listener.close() } else { // Handle error } } ```