### Project Configuration Example Source: https://github.com/c3lang/c3-web.git/blob/main/docs/build-your-project/project-config.md A comprehensive example of a `project.json` file, illustrating various global and target-specific configuration properties. ```json5 { // Language version of C3. "langrev": "1", // Warnings used for all targets. "warnings": [ "no-unused" ], // Directories where C3 library files may be found. "dependency-search-paths": [ "lib" ], // Libraries to use for all targets. "dependencies": [ ], // Authors, optionally with email. "authors": [ "John Doe " ], // Version using semantic versioning. "version": "0.1.0", // Sources compiled for all targets. "sources": [ "src/**" ], // C sources if the project also compiles C sources // relative to the project file. // "c-sources": [ "csource/**" ], // Include directories for C sources relative to the project file. // "c-include-dirs: [ "csource/include" ], // Output location, relative to project file. "output": "../build", "targets": { "my_app": { // Executable or library. "type": "executable", // Architecture and OS target. // You can use 'c3c --list-targets' to list all valid targets, // "target": "linux-x64", // Current Target options: // android-aarch64 // elf-aarch64 elf-riscv32 elf-riscv64 elf-x86 elf-x64 elf-xtensa // mcu-x86 mingw-x64 netbsd-x86 netbsd-x64 openbsd-x86 openbsd-x64 // freebsd-x86 freebsd-x64 ios-aarch64 // linux-aarch64 linux-riscv32 linux-riscv64 linux-x86 linux-x64 // macos-aarch64 macos-x64 // wasm32 wasm64 // windows-aarch64 windows-x64 // Additional libraries, sources // and overrides of global settings here. }, }, // Global settings. // C compiler if the project also compiles C sources // defaults to 'cc'. "cc": "cc", // C compiler flags "cflags": "", // Set the include directories for C sources. "c-include-dirs": "", // CPU name, used for optimizations in the LLVM backend. "cpu": "generic", // Debug information, may be "none", "full" and "line-tables". "debug-info": "full", // FP math behaviour: "strict", "relaxed", "fast". "fp-math": "strict", // Link libc other default libraries. "link-libc": true, // Memory environment: "normal", "small", "tiny", "none". "memory-env": "normal", // Optimization: "O0", "O1", "O2", "O3", "O4", "O5", "Os", "Oz". "opt": "O0", // Code optimization level: "none", "less", "more", "max". "optlevel": "none", // Code size optimization: "none", "small", "tiny". "optsize": "none", // Relocation model: "none", "pic", "PIC", "pie", "PIE". "reloc": "none", // Trap on signed and unsigned integer wrapping for testing. "trap-on-wrap": false, // Turn safety (contracts, runtime bounds checking, null pointer checks etc). "safe": true, // Compile all modules together, enables more inlining. "single-module": true, // Use / don't use soft float, value is otherwise target default. "soft-float": false, // Strip unused code and globals from the output. "strip-unused": true, // The size of the symtab, which limits the amount // of symbols that can be used. Should usually not be changed. "symtab": 1048576, // Use the system linker. "linker": "cc", // Include the standard library. "use-stdlib": true, // Set general level of x64 cpu: "baseline", "ssse3", "sse4", "avx1", "avx2-v1", "avx2-v2", "avx512", "native". "x86cpu": "native", // Set max type of vector use: "none", "mmx", "sse", "avx", "avx512", "native". "x86vec": "sse", // Enable sanitizer: none, address, memory, thread. "sanitize": "none", // Features enabled for all targets. "features": "", } ``` -------------------------------- ### Install Dependencies and Run Server (pip) Source: https://github.com/c3lang/c3-web.git/blob/main/README.md Install project dependencies using pip and run the MkDocs development server. ```bash # Install dependencies from pyproject.toml pip install . # Run server mkdocs serve ``` -------------------------------- ### C3 Test Setup Macro Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Initializes test case context using setup and teardown functions. The teardown function is optional. ```c3 test::@setup(setup_fn: my_setup, teardown_fn: my_teardown); ``` -------------------------------- ### C3 Test Setup and Teardown Macro Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Illustrates the usage of the `@setup` macro for initializing and cleaning up test case contexts. It accepts an initializer function and an optional teardown function. ```c3 fn void test_setup_example(@setup setup_fn: std::core::runtime::TestFn, teardown_fn: std::core::runtime::TestFn = null) { // Test logic here } ``` -------------------------------- ### Install GCC and glibc-devel on openSUSE Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/prebuilt-binaries.md On openSUSE systems, install GCC and glibc-devel to resolve 'cc: not found' errors. ```bash sudo zypper install gcc glibc-devel ``` -------------------------------- ### Generic Type Alias Examples Source: https://github.com/c3lang/c3-web.git/blob/main/docs/implementation-details/specification.md Provides examples of generic type aliases, demonstrating how to create parameterized type aliases for increased flexibility. ```c3 alias IntList = List{int}; alias Stack {Ty} = List{Ty}; ``` -------------------------------- ### Install Build Dependencies on Void Linux Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/compile.md Installs necessary build tools and libraries for compiling C3 on Void Linux systems. ```bash sudo xbps-install git cmake clang libcurl-devel ``` -------------------------------- ### start Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Startup the threads running this ThreadGroup. ```APIDOC ## ThreadGroup.start ### Description Startup the threads running this ThreadGroup. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ``` -------------------------------- ### Install C3 using Arch Linux package manager Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/prebuilt-binaries.md For Arch Linux users, C3 is available in the official extra repository. Install it using pacman. ```bash pacman -S c3c ``` -------------------------------- ### ThreadGroup.set_init_fn Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Registers a function to be executed once on each worker thread before it starts processing any tasks. This is useful for thread-specific setup. ```APIDOC ## ThreadGroup.set_init_fn ### Description Register a function to run once on every worker thread before it processes any tasks. ### Method `set_init_fn(thread_init_fn: ThreadInitFn, init_context: void*) ### Parameters #### In Parameters - **thread_init_fn** (ThreadInitFn) - The function to invoke once on each worker at startup. - **init_context** (void*) - Pointer passed to thread_init_fn. ### Return Value void ``` -------------------------------- ### C3 Macro with Runtime Code Inference Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3.handmade.network/8590-the_downsides_of_compile_time_evaluation.md This example shows how to infer the approximate runtime code from a C3 macro by removing lines starting with '$'. It highlights the readability intention by separating meta-code from runtime logic. ```c macro int performFn(char $prefix_char, int start_value) { int result = start_value; result = CMD_FNS[$i].func(result); return result; } ``` -------------------------------- ### Do: Shortest Permitted Module Paths Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3.handmade.network/9008-some_tips_organizing_code_in_c3.md Illustrates the recommended practice of using the shortest possible module paths for clarity and conciseness. This example imports 'std::io' and uses shorter prefixes like 'file::open' and 'io::read_fully'. ```c3 import std::io; fn void main() { File f = file::open("foo.txt", "rb"); char[]? data = io::read_fully(mem, &f); ... ``` -------------------------------- ### Prefer Unsigned Strategy Example (C Behavior) Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3.handmade.network/7651-overflow_trapping_in_practice.md Shows the 'prefer unsigned' strategy, typical in C, where unsigned arithmetic with wrapping is used. This example highlights potential issues with comparisons and divisions when signed numbers are converted to unsigned, leading to unexpected results. ```C unsigned x = 2; int y = -100; unsigned z = 10 if (z < x + y) unexpectedCall(); ``` -------------------------------- ### C3 Nested Block Comment Example Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3.handmade.network/7908-c3__block_comments_and_mega_comments..md Illustrates C3's proposed nested block comment syntax `/# ... #/`. This syntax requires the comment to start on a new line to avoid ambiguity with regular code. ```c3 /# s = "/#"; <- not recognized #/ ``` -------------------------------- ### std::net::os::getsockopt Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Gets options from a socket. ```APIDOC ## std::net::os::getsockopt ### Description Retrieves the current value of options set on a socket. This can be used to inspect socket configurations. ### Method `getsockopt(socket: NativeSocket, level: CInt, optname: CInt, optval: void*, optlen: Socklen_t*) -> CInt ` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (CInt) - Returns `0` on success. #### Error Response - Returns a non-zero error code on failure. #### Response Example ```json { "example": "0 on success, non-zero error code on failure" } ``` ``` -------------------------------- ### Creating a Start Node Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Creates a new start node (element start tag) within an XmlDocument. ```APIDOC ## new_start_node ### Description Creates a new start node. ### Signature `XmlNode* new_start_node(XmlDocument* doc, String name)` ### Parameters - **doc** (XmlDocument*) - The document to which the node will be added. - **name** (String) - The name of the element. ``` -------------------------------- ### Serve Documentation with uv Source: https://github.com/c3lang/c3-web.git/blob/main/README.md Use uv to serve the MkDocs documentation locally. ```bash uv run mkdocs serve ``` -------------------------------- ### ThreadGroup Initialization Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Initializes a ThreadGroup. The group must be started with start() before tasks are processed and must be paired with destroy(). ```APIDOC ## ThreadGroup::ThreadGroup ### Description Initialize a ThreadGroup. The group must be started with start() before tasks are processed. Must be paired with destroy(). ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **allocator** (Allocator) - inout - The allocator to use internally for creating queues - **task_fn** (Function) - Task function to run - **thread_count** (Integer) - Number of threads for the task group, 0 for max(cpus - 1, 2) - **queue_capacity** (Integer) - Queue size, if 0 - uses an unbounded queue - **context** (Pointer) - Any common context to use - **thread_settings** (ThreadSettings) - Thread settings to apply ``` -------------------------------- ### Build Documentation for Deployment Source: https://github.com/c3lang/c3-web.git/blob/main/README.md Generate static HTML files for deployment using either uv or directly with mkdocs build. ```bash uv run mkdocs build # or mkdocs build ``` -------------------------------- ### Install GCC on Void Linux Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/prebuilt-binaries.md On Void Linux, install the GCC compiler to resolve 'cc: not found' errors. ```bash sudo xbps-install -S gcc ``` -------------------------------- ### Setup and Activate Virtual Environment Source: https://github.com/c3lang/c3-web.git/blob/main/README.md Manually set up a Python virtual environment using venv and activate it. ```bash # Create and activate a virtual environment python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### Good Practice: Shortest Permitted Module Paths Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3.handmade.network/9008-some_tips_organizing_code_in_c3.md Illustrates the recommended approach of using the shortest possible module paths for imports and function calls, improving conciseness and reducing verbosity. ```c3 import std::io; fn void main() { File f = file::open("foo.txt", "rb"); char[]? data = io::read_fully(mem, &f); ... } ``` -------------------------------- ### Install Build Dependencies on Fedora Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/compile.md Installs necessary build tools and libraries for compiling C3 on Fedora systems. ```bash sudo dnf install cmake clang git libcurl-devel ``` -------------------------------- ### std::os::win32::wsaStartup Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Initializes the Windows Sockets library. ```APIDOC ## std::os::win32::wsaStartup ### Description Initializes the Windows Sockets DLL and specifies the version of the Windows Sockets API that the calling process intends to use. ### Method Not applicable (function call) ### Parameters * **wVersionRequired** (CShort) - The version of the Windows Sockets API to use. * **lpWSAData** (LPWSADATA) - A pointer to a `WSADATA` structure that receives details about the Windows Sockets implementation. ### Return Value * **CInt** - If the function succeeds, the return value is zero. If the function fails, the return value is `SOCKET_ERROR`. ``` -------------------------------- ### Install GCC on Arch Linux Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/prebuilt-binaries.md For Arch Linux users, install the GCC compiler to resolve 'cc: not found' errors. ```bash sudo pacman -S gcc ``` -------------------------------- ### Install GCC on Fedora/Rocky Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/prebuilt-binaries.md On Fedora or Rocky Linux systems, install the GCC compiler to resolve 'cc: not found' errors. ```bash sudo dnf install gcc ``` -------------------------------- ### Initialize a New C3 Project Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/projects.md Use the `c3c init` command to create a new project directory with a standard structure. You can specify a project name and optionally a template or custom path. ```bash c3c init myc3project ``` -------------------------------- ### Go-style defer loop example Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3.handmade.network/7641-implementing_defer.md Illustrates a loop with defer statements in Go, explaining that these defers are queued and executed at function end, potentially leading to memory allocation for each defer. ```go for() { ... defer ... ... } ``` -------------------------------- ### Install Build Dependencies on Ubuntu/Debian Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/compile.md Installs necessary build tools and libraries for compiling C3 on Ubuntu or Debian-based systems. ```bash sudo apt-get install cmake git clang libcurl4-openssl-dev ``` -------------------------------- ### Initialize Documentation System Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Initializes the documentation system by fetching 'docs.json' or using embedded data. Handles filtering and rendering of modules and declarations. Sets up event listeners for navigation and popstate events. ```javascript async function init() { document.getElementById('filter-private').classList.toggle('active', filters.private); document.getElementById('filter-local').classList.toggle('active', filters.local); if (EMBEDDED_JSON_LIST.length > 0) { for (const item of EMBEDDED_JSON_LIST) { mergeTargetData(item.data, item.target); } } else { try { const response = await fetch('docs.json'); if (response.ok) { const data = await response.json(); mergeTargetData(data, 'default'); } } catch (e) { console.error("Could not load docs.json", e); } } if (allDecls.length === 0) { document.getElementById('content').innerHTML = '
No documentation data found.
'; return; } allDecls.forEach(d => { d.visibility = d.visibility || 'public'; }); renderModules(); bindEvents(); const hash = location.hash.slice(1); if (hash) { navigateTo(decodeURIComponent(hash), false); } else { renderModuleOverview(); } window.addEventListener('popstate', (e) => { const uid = (e.state && e.state.uid) || decodeURIComponent(location.hash.slice(1)); if (uid) { const target = allDecls.find(d => d.uid === uid); if (target) renderDetails(target, true); else renderModuleOverview(); } else { renderModuleOverview(); } }); } ``` -------------------------------- ### Event Listener for Instant Navigation Source: https://github.com/c3lang/c3-web.git/blob/main/docs/index.md This snippet sets up an event listener to call the setupDownloads function. It prioritizes MkDocs Material's document$ subscribe event for instant navigation and falls back to the DOMContentLoaded event if document$ is not defined. ```javascript // MkDocs Material specific event for instant navigation if (typeof document$ !== "undefined") { document$.subscribe(function () { setupDownloads(); }); } else { window.addEventListener("DOMContentLoaded", setupDownloads); } ``` -------------------------------- ### Extern Global Variable Example Source: https://github.com/c3lang/c3-web.git/blob/main/docs/implementation-details/specification.md An example of an extern global variable declaration, indicating that the 'VERSION' integer is defined elsewhere. ```c extern int VERSION; ``` -------------------------------- ### Install GCC and musl-dev on Alpine Linux Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/prebuilt-binaries.md For Alpine Linux users, install GCC and musl-dev to resolve 'cc: not found' errors. ```bash sudo apk add gcc musl-dev ``` -------------------------------- ### HashSet Initialization Methods Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Provides documentation for various ways to initialize a HashSet, including with an allocator, capacity, load factor, or from existing values or another set. ```APIDOC ## HashSet.init ### Description Initializes a new HashSet with a specified allocator, capacity, and load factor. ### Method `init` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **self** (&mut HashSet) - The HashSet instance to initialize. - **allocator** (Allocator) - The allocator to use for memory management. (inout, by_ref) - **capacity** (sz) - The initial capacity of the HashSet. Defaults to DEFAULT_INITIAL_CAPACITY. - **load_factor** (float) - The load factor for the HashSet. Defaults to DEFAULT_LOAD_FACTOR. ### Request Example ```c let mut mySet: HashSet = HashSet::init(allocator, 100, 0.75); ``` ### Response #### Success Response (200) - **HashSet*** - A pointer to the initialized HashSet. #### Response Example ```json { "example": "pointer_to_initialized_hashset" } ``` ## HashSet.tinit ### Description Initializes a new HashSet with a specified capacity and load factor, using the default allocator. ### Method `tinit` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **self** (&mut HashSet) - The HashSet instance to initialize. - **capacity** (sz) - The initial capacity of the HashSet. Defaults to DEFAULT_INITIAL_CAPACITY. - **load_factor** (float) - The load factor for the HashSet. Defaults to DEFAULT_LOAD_FACTOR. ### Request Example ```c let mut mySet: HashSet = HashSet::tinit(100, 0.75); ``` ### Response #### Success Response (200) - **HashSet*** - A pointer to the initialized HashSet. #### Response Example ```json { "example": "pointer_to_initialized_hashset" } ``` ## HashSet.init_from_values ### Description Initializes a new HashSet from a collection of values, using a specified allocator, capacity, and load factor. ### Method `init_from_values` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **self** (&mut HashSet) - The HashSet instance to initialize. - **values** (Value[]) - An array of values to populate the HashSet with. - **allocator** (Allocator) - The allocator to use for memory management. (inout, by_ref) - **capacity** (sz) - The initial capacity of the HashSet. Defaults to DEFAULT_INITIAL_CAPACITY. - **load_factor** (float) - The load factor for the HashSet. Defaults to DEFAULT_LOAD_FACTOR. ### Request Example ```c let values = [1, 2, 3]; let mut mySet: HashSet = HashSet::init_from_values(values, allocator, 100, 0.75); ``` ### Response #### Success Response (200) - **HashSet*** - A pointer to the initialized HashSet. #### Response Example ```json { "example": "pointer_to_initialized_hashset" } ``` ## HashSet.tinit_from_values ### Description Initializes a new HashSet from a collection of values, using the default allocator, and specified capacity and load factor. ### Method `tinit_from_values` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **self** (&mut HashSet) - The HashSet instance to initialize. - **values** (Value[]) - An array of values to populate the HashSet with. - **capacity** (sz) - The initial capacity of the HashSet. Defaults to DEFAULT_INITIAL_CAPACITY. - **load_factor** (float) - The load factor for the HashSet. Defaults to DEFAULT_LOAD_FACTOR. ### Request Example ```c let values = [1, 2, 3]; let mut mySet: HashSet = HashSet::tinit_from_values(values, 100, 0.75); ``` ### Response #### Success Response (200) - **HashSet*** - A pointer to the initialized HashSet. #### Response Example ```json { "example": "pointer_to_initialized_hashset" } ``` ## HashSet.init_from_set ### Description Initializes a new HashSet by copying elements from another HashSet, using a specified allocator. ### Method `init_from_set` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **self** (&mut HashSet) - The HashSet instance to initialize. - **allocator** (Allocator) - The allocator to use for memory management. (inout, by_ref) - **other_set** (&HashSet) - The HashSet to copy elements from. ### Request Example ```c let mut sourceSet: HashSet = ...; let mut newSet: HashSet = HashSet::init_from_set(allocator, &sourceSet); ``` ### Response #### Success Response (200) - **HashSet*** - A pointer to the initialized HashSet. #### Response Example ```json { "example": "pointer_to_initialized_hashset" } ``` ## HashSet.tinit_from_set ### Description Initializes a new HashSet by copying elements from another HashSet, using the default allocator. ### Method `tinit_from_set` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **self** (&mut HashSet) - The HashSet instance to initialize. - **other_set** (&HashSet) - The HashSet to copy elements from. ### Request Example ```c let mut sourceSet: HashSet = ...; let mut newSet: HashSet = HashSet::tinit_from_set(&sourceSet); ``` ### Response #### Success Response (200) - **HashSet*** - A pointer to the initialized HashSet. #### Response Example ```json { "example": "pointer_to_initialized_hashset" } ``` ``` -------------------------------- ### Initializing List with Heap Allocator Source: https://github.com/c3lang/c3-web.git/blob/main/docs/language-common/memory.md Demonstrates initializing a List with the 'mem' allocator for heap allocation. Remember to call 'free()' when done. ```c3 List{int} list; list.init(mem); // "list" will use the heap allocator list.push(1); list.push(42); io::printn(list); // Prints "{ 1, 42 }" list.free(); // Free the memory in the list ``` -------------------------------- ### C3 Memory Allocation Examples Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3.handmade.network/8864-c3_0.5.4_is_out%2521.md Demonstrates the transition from deprecated `new_zero` to `new` for zero-initialized allocations, and `alloc` for non-zeroing allocations. Also shows the new syntax for allocator-specific allocations. ```c3 int* x = mem::new_zero(int); int* y = mem::new(int); // replaced by: int* x = mem::new(int); int* y = mem::alloc(int); ``` ```c3 Foo* f = my_allocator.new(Foo); // replaced by: Foo* f = allocator::new(my_allocator, Foo) ``` -------------------------------- ### Install Build Dependencies on Arch Linux Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/compile.md Installs necessary build tools and libraries for compiling C3 on Arch Linux systems. ```bash sudo pacman -S curl clang cmake git ``` -------------------------------- ### C2 Module Example with Structs and Functions Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3.handmade.network/8650-a_look_at_modules_in_general__in_the_context_of_c3.md Demonstrates how C2 uses modules, structs, and functions to emulate namespacing, similar to static variables and functions attached to types. ```c2 // File bar.c2 module bar; // Plain function func int get_one() { return 1; } // File foo.c2 module foo; import bar; type Bar struct { int x; } // Static function func int Bar.get_one() { return 1; } func void test() { int a = Bar.get_one(); int b = bar.get_one(); } ``` -------------------------------- ### Initial C3 Error Handling Example Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/dev.to/more-on-error-handling-in-c3-3bee.md An early example of reading input and checking for a non-zero value, which could indicate an error. ```c3 int! index = atoi(readLine()); if (index) { printf("Thx for the number\n"); // Index is now int. ... } ``` -------------------------------- ### Getting the Type of an Interface Method Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3_0_8_0_the_core_language_is_settling.md Shows how to use the `$Typeof` operator to get the type of an interface method, useful for metaprogramming or reflection. ```c3 interface TestInterface { fn void hello_world(String name); } $Typeof(TestInterface.hello_world) x; ``` -------------------------------- ### Static Initializer and Finalizer Functions Source: https://github.com/c3lang/c3-web.git/blob/main/docs/language-fundamentals/functions.md Shows how to define functions that run automatically at program startup (`@init`) and shutdown (`@finalizer`). ```c3 fn void run_at_startup() @init { // Run at startup some_function.init(512); } fn void run_at_shutdown() @finalizer { some_thing.shutdown(); } ``` -------------------------------- ### Original Macro and Function Example Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3.handmade.network/8272-fixing_lexical_scopes..._badly.md This code demonstrates a macro 'testmacro' and a function 'test' that uses it, illustrating a scenario where lexical scopes might become problematic. ```c3 macro int testmacro(int x) { int z = 2; for (int i = 0; i < x; i++) { z *= 2; } return z; } fn int test(int y) { int z = getValue(y); int x = @testmacro(z); return z + x; } ``` -------------------------------- ### Blake3.init Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Initialize a BLAKE3 hashing context with an optional key and flags. ```APIDOC ## Blake3.init ### Description Initialize a BLAKE3 hashing context. This can be done with an optional key and flags. ### Method `init(key: uint[], flags: char)` ### Parameters * `key` (uint[]) - Optional - The key to use for hashing. * `flags` (char) - Optional - Flags to control the hashing behavior. ``` -------------------------------- ### Compile a C3 file on Windows Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/prebuilt-binaries.md After installing the C3 compiler using the Windows installer, you can compile C3 files from any directory by running this command. ```bash c3c compile ./hello.c3 ``` -------------------------------- ### std::crypto::kmac::Kmac.init Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Initialize the vanilla KMAC context. ```APIDOC ## Method: std::crypto::kmac::Kmac.init ### Description Initializes the standard KMAC (Keyed-Message Authentication Code) context. ### Parameters - `key` (in char[]): The secret key used to seed the KMAC cipher. - `customizer` (String, optional): An optional, variable-length customization string used for further domain separation. Defaults to an empty string. ``` -------------------------------- ### Install CMake on macOS using Homebrew Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/compile.md Installs CMake on macOS using the Homebrew package manager. This is a prerequisite for building C3 on macOS with Homebrew. ```bash brew install cmake ``` -------------------------------- ### Using Named Arguments Source: https://github.com/c3lang/c3-web.git/blob/main/docs/language-fundamentals/functions.md Shows how to call functions using named arguments, allowing for more readable calls and flexibility in argument order. ```c3 fn void test_named(int times, double data) { for (int i = 0; i < times; i++) { io::printf("Hello %d\n", i + data); } } fn void test() { // Named only test_named(times: 1, data: 3.0); // Unnamed only test_named(3, 4.0); // Mixing named and unnamed test_named(15, data: 3.141592); } ``` -------------------------------- ### std::compression::deflate::Deflater.init Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Initializes the Deflater with an allocator and an output stream. ```APIDOC ## Deflater.init ### Description Initializes the Deflater with the specified allocator and an optional output stream. ### Parameters * **self** (Deflater*) - A pointer to the Deflater instance. * **allocator** (Allocator) - The allocator to use for memory management. * **output** (OutStream) - The output stream to write compressed data to (defaults to null). ``` -------------------------------- ### Allman Brace Style Example Source: https://github.com/c3lang/c3-web.git/blob/main/docs/language-fundamentals/naming.md An example of the Allman brace style, where opening braces are placed on a new line, as used in the C3 standard library. ```c3 fn int allman(int foo) { if (foo > 2) { foo++; } else { foo *= foo; } return foo; } ``` -------------------------------- ### Process Creation and Configuration Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Details on how to create and configure child processes using C3. ```APIDOC ## Process Creation and Configuration This section covers the functions and types used for creating and configuring child processes. ### `bind(fd: RawFd)` Binds a file descriptor for process I/O. - **Parameters** - `fd` (RawFd) - The file descriptor to bind. - **Returns** - `ProcessStdio` - A `ProcessStdio` object representing the bound file descriptor. ### `SpawnOptions` Enum Defines options for spawning new processes. - **`STDERR_TO_STDOUT`**: Redirects the child's stderr to its stdout. - **`INHERIT_ENV`**: Inherits the environment variables from the parent process. - **`ASYNC_OUTPUT`**: Enables asynchronous reading of the child's output. - **`NO_WINDOW`**: Spawns the process without a console window (on supported platforms). - **`NO_PATH_SEARCH`**: Prevents searching the system's PATH for the executable. - **`INHERIT_STDIO`**: Inherits the standard input, output, and error streams from the parent process. ### `ProcessStdioAction` Enum Defines actions for standard I/O streams of a child process. - **`DEFAULT`**: Use the default action for the stream. - **`CAPTURE`**: Capture the stream's output. - **`INHERIT`**: Inherit the stream from the parent process. - **`BIND`**: Bind the stream to a specific file descriptor. ``` -------------------------------- ### Generic Contract Violation Example Source: https://github.com/c3lang/c3-web.git/blob/main/docs/generic-programming/generics.md An example showing how a generic contract violation would trigger a compile-time error, indicating which parameter constraint failed. ```c3 alias test_function = vector::test_func {Bar, float, int}; // This would give the error // --> Parameter(s) failed validation: // @require "$assignable((TypeB)1, TypeA) && $assignable((TypeC)1, TypeA)" violated. ``` -------------------------------- ### std::os::posix::posix_spawn_file_actions_init Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Initializes a posix_spawn_file_actions_t structure. Returns a CInt. ```APIDOC ## std::os::posix::posix_spawn_file_actions_init ### Description Initializes a `posix_spawn_file_actions_t` structure, which is used to specify file descriptor manipulations for `posix_spawn`. Returns a `CInt` status code. ### Function Signature `posix_spawn_file_actions_init(file_actions: Posix_spawn_file_actions_t*) -> CInt` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - Returns `0` on success. - Returns an error code on failure. #### Response Example ```json { "example": 0 } ``` ``` -------------------------------- ### ThreadGroup.init Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Initializes a ThreadGroup, setting up the necessary resources for task processing. The group must be started using `start()` before tasks can be processed and must be paired with `destroy()`. ```APIDOC ## ThreadGroup.init ### Description Initialize a ThreadGroup. The group must be started with start() before tasks are processed. Must be paired with destroy(). ### Method `init(allocator: Allocator, task_fn: ThreadTaskFn, thread_count: int = 0, queue_capacity: sz = 0, context: void* = null, thread_settings: ThreadSettings = {}) ### Parameters #### In Parameters - **allocator** (Allocator) - The allocator to use internally for creating queues. - **task_fn** (ThreadTaskFn) - Task function to run. - **thread_count** (int) - Number of threads for the task group, 0 for max(cpus - 1, 2). Defaults to 0. - **queue_capacity** (sz) - Queue size, if 0 - uses an unbounded queue. Defaults to 0. - **context** (void*) - Any common context to use. Defaults to null. - **thread_settings** (ThreadSettings) - Thread settings to apply. Defaults to {}. ### Return Value void? ``` -------------------------------- ### Install GCC and libc6-dev on Ubuntu/Debian Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/prebuilt-binaries.md To resolve 'cc: not found' errors on Ubuntu or Debian systems, install the GCC compiler and C library development packages. ```bash sudo apt-get install gcc libc6-dev ``` -------------------------------- ### C2 Module Example: Namespacing with Structs and Functions Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3.handmade.network/8650-a_look_at_modules_in_general__in_the_context_of_c3.md Illustrates how modules can be emulated using structs and functions in the C2 language, demonstrating namespacing capabilities. ```c2 // File bar.c2 module bar; // Plain function func int get_one() { return 1; } // File foo.c2 module foo; import bar; type Bar struct { int x; } // Static function func int Bar.get_one() { return 1; } func void test() { int a = Bar.get_one(); int b = bar.get_one(); } ``` -------------------------------- ### Install C3 nightly build on Arch Linux Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/prebuilt-binaries.md To install the nightly build of C3 on Arch Linux, use the AUR package manager like yay. ```bash yay -S c3c-git ``` -------------------------------- ### Initialize a New C3 Project Source: https://github.com/c3lang/c3-web.git/blob/main/docs/build-your-project/build-commands.md Creates a new C3 project structure in the specified directory. Supports custom templates via the --template option. ```bash c3c init [optional path] ``` -------------------------------- ### Macro Invocation Examples Source: https://github.com/c3lang/c3-web.git/blob/main/docs/implementation-details/specification.md Demonstrates how to invoke macros using AT_IDENT or bare names, similar to function calls. ```c3 int s = @sum(1, 2, 3); ``` ```c3 int y = square(3); ``` -------------------------------- ### HashMap Initialization Methods Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Provides documentation for different ways to initialize a HashMap, including from keys and values, or from another map. ```APIDOC ## HashMap Initialization ### `tinit_from_keys_and_values` Initializes a HashMap with provided keys and values. - **keys**: The keys for the HashMap entries. - **values**: The values for the HashMap entries. - **capacity**: The initial capacity of the HashMap. Defaults to `DEFAULT_INITIAL_CAPACITY`. - **load_factor**: The load factor for the HashMap. Defaults to `DEFAULT_LOAD_FACTOR`. ### `init_from_map` Initializes a HashMap by copying entries from another HashMap. - **allocator**: The allocator to use for the new HashMap. - **other_map**: The map to copy from. ### `tinit_from_map` Initializes a HashMap with the same type as another map, copying entries from the other map. - **other_map**: The map to copy from. ``` -------------------------------- ### String Interpolation Example (Rejected) Source: https://github.com/c3lang/c3-web.git/blob/main/docs/faq/rejected-ideas.md This is an example of the string interpolation syntax that was considered and rejected for C3. It demonstrates how variables would be embedded within a string literal. ```c3 String str1 = "hello"; String str2 = "world"; int val = 3; float pi = 3.14; String str = "{str1}:{str2}:{val}:{pi}"; ``` -------------------------------- ### Install CMake and LLVM on macOS using MacPorts Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/compile.md Installs CMake and specific LLVM/Clang versions using MacPorts. This is for users who prefer MacPorts for package management on macOS. ```bash sudo port install cmake llvm-17 clang-17 ``` -------------------------------- ### Lowered Defer with Return Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3.handmade.network/7641-implementing_defer.md Shows how the initial 'defer' example is lowered to inline the deferred code before the 'return' statement. ```c void test() { if (rand() % 2 == 0) { printf("A"); return; } printf("B"); printf("A"); } ``` -------------------------------- ### C3 Result Type - Bad Example (Should be Fault) Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html This example demonstrates an incorrect use of Result for simple error messages that should be handled by C3's fault system. ```c3 fn Result{int, String} div(int a, int b) { if (b == 0) return result::err("division by zero"); return result::ok(a / b); } fn void print_int(int x) { io::printfn("Integer %d", x); } fn void main() { print_int(div(4, 1).ok())!!; print_int(div(4, 0).ok())!!; } ``` -------------------------------- ### C3 While Loop Examples Source: https://github.com/c3lang/c3-web.git/blob/main/docs/language-overview/examples.md Demonstrates the standard C-like while loop and a declaration-style while loop. ```c3 fn void example_while() { // again exactly the same as C int a = 10; while (a > 0) { a--; } // Declaration while (Point* p = getPoint()) { // .. } } ``` -------------------------------- ### C3 @weak Attribute Example Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3_0_7_11_the_last_of_the_seven.md Provides an example of how the `@weak` attribute can be used to handle multiple definitions of a function, allowing a non-weak definition to override a weak one. ```c3 fn void foo() @if(env::POSIX) { io::printn("Works!"); } fn void foo() @if(!env::POSIX) { abort("Unsupported foo()"); } ``` -------------------------------- ### Array Type Conversion Examples Source: https://github.com/c3lang/c3-web.git/blob/main/docs/language-common/arrays.md Shows examples of type casting between different array and pointer types. Note that these casts are inherently unsafe and rely on compatible underlying types. ```c3 int[4] a; int[4]* b = &a; int* c = b; // Safe cast: int[4]* d = (int[4]*)c; int e = 12; int* f = &e; // Incorrect, but not checked int[4]* g = (int[4]*)f; // Also incorrect but not checked. int[] h = f[0..2]; ``` -------------------------------- ### Setup Download Links Based on OS Source: https://github.com/c3lang/c3-web.git/blob/main/docs/index.md This script detects the user's operating system (Windows, macOS, Linux) and sets the download button's href to the appropriate link. It also updates an element with the detected OS name. This code is intended to be run on page load. ```javascript var mainBtn = document.getElementById("main-download-btn"); if (!mainBtn) return; var os = "Linux"; var userAgent = window.navigator.userAgent; if (userAgent.indexOf("Win") !== -1) os = "Windows"; if (userAgent.indexOf("Mac") !== -1) os = "macOS"; var links = { Windows: "https://github.com/c3lang/c3c/releases/latest/download/c3-windows.zip", macOS: "https://github.com/c3lang/c3c/releases/latest/download/c3-macos.zip", Linux: "https://github.com/c3lang/c3c/releases/latest/download/c3-linux-static.tar.gz", }; document.getElementById("os-name").innerText = os; mainBtn.href = links[os]; } ``` -------------------------------- ### std::hash::fnv32a::Fnv32a.init Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Initializes an FNV32a hash state. ```APIDOC ## std::hash::fnv32a::Fnv32a.init ### Description Initializes an FNV32a hash state. ### Signature `fn init(self: Fnv32a*) -> void` ### Parameters * **self** (Fnv32a*) - A mutable reference to the FNV32a state to initialize. ``` -------------------------------- ### Generic Instantiation Example Source: https://github.com/c3lang/c3-web.git/blob/main/docs/implementation-details/specification.md Demonstrates how to instantiate parameterized types and functions by providing concrete arguments in curly braces. Each distinct argument tuple results in a separate instantiation. ```c3 Foo {int, double} g; // Note: The example in the source text was incomplete for function instantiation. // Assuming a function `test` that takes two arguments: test {int, double} (1.0, &g); ``` -------------------------------- ### stdin Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Get standard in. ```APIDOC ## stdin ### Description Get standard in. ### Parameters None ### Return Value - **File*** - stdin as a File ``` -------------------------------- ### Good Practice: Succinct Module Names for Direct Use Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3.handmade.network/9008-some_tips_organizing_code_in_c3.md Shows the recommended approach of using short, descriptive module names that integrate well with function names, eliminating the need for aliasing. This promotes cleaner code and easier readability. ```c3 module com::mysite::thecanvasrenderinglib::canvas; fn Canvas? create_new_for_rendering() { ... } module foo; import com::mysite::thecanvasrenderinglib; fn void test() { Canvas? c = canvas::create_new_for_rendering(); ... } ``` -------------------------------- ### stdout Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Get standard out. ```APIDOC ## stdout ### Description Get standard out. ### Parameters None ### Return Value - **File*** - stdout as a File ``` -------------------------------- ### K&R Brace Style Example Source: https://github.com/c3lang/c3-web.git/blob/main/docs/language-fundamentals/naming.md An example of the K&R brace style, where opening braces are placed on the same line as the preceding statement, an alternative preferred for canonical C3 code outside the stdlib. ```c3 fn int k_and_r(int foo) { if (foo > 2) { foo++; } else { foo *= foo; } return foo; } ``` -------------------------------- ### Poly1305 Initialization Method Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Initializes the Poly1305 context with the provided key. ```c3 method init(self: Poly1305*, key: char[32]): void ``` -------------------------------- ### C3: Example of Function Using Sub-Modules Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/c3.handmade.network/8417-imports_and_modules.md Illustrates a C3 function that utilizes functions and constants from different sub-modules within the same top-level module. This example highlights the need for visibility between parent and sibling modules. ```c3 fn File* open_filename_for_read(char[] filename) { Path* p = io::path_from_string(foo); defer io::path_free(p); return file::open_file(p, readoptions::READ_ONLY); } ``` -------------------------------- ### Initialization Functions: Replaced by 'init(mem)' Source: https://github.com/c3lang/c3-web.git/blob/main/docs/blog/posts/C3 0.7.0 - One Step Closer To 1.0.md The `new_init` and other `new_*` functions have been removed. Use `init(mem)` for initialization and `s.concat(mem, s2)` for concatenation, explicitly passing the allocator. ```c3 new_init() ``` ```c3 init(mem) ``` ```c3 s.concat(allocator::heap(), s2) ``` ```c3 s.concat(mem, s2) ``` -------------------------------- ### stderr Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Get standard err. ```APIDOC ## stderr ### Description Get standard err. ### Parameters None ### Return Value - **File*** - stderr as a File ``` -------------------------------- ### std::hash::blake3::Blake3.init Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Initializes a BLAKE3 context. This method can optionally take a key for keyed hashing. ```APIDOC ## init ### Description Initialize a BLAKE3 context. ### Method `init(key: char[], explicit_flags: char = 0)` ### Parameters #### Parameters - **key** (char[]) - Required - An optional key initializer to use. - **explicit_flags** (char) - Optional - Flags for explicit control (default: 0). ``` -------------------------------- ### Little-Endian 16-bit Field Example Source: https://github.com/c3lang/c3-web.git/blob/main/docs/implementation-details/specification.md Illustrates a 16-bit unsigned short field occupying the first 16 bits of a 4-byte char array with little-endian byte order. Shows the memory layout for the same value as the big-endian example. ```c3 bitstruct B : char[4] @littleendian { ushort v : 0..15; } // B.v = 0xABCD → memory [CD AB 00 00] ``` -------------------------------- ### C3 Foreach Loop Examples Source: https://github.com/c3lang/c3-web.git/blob/main/docs/language-overview/examples.md Shows how to iterate over slices using foreach, both by value and by reference. ```c3 // Prints the values in the slice. fn void example_foreach(float[] values) { foreach (index, value : values) { io::printfn("%d: %f", index, value); } } ``` ```c3 // Updates each value in the slice // by multiplying it by 2. fn void example_foreach_by_ref(float[] values) { foreach (&value : values) { *value *= 2; } } ``` -------------------------------- ### Static Initialization of Globals with Heap Allocator Source: https://github.com/c3lang/c3-web.git/blob/main/docs/language-common/memory.md Example of statically initializing a global List to use the heap allocator via the 'ONHEAP' constant. ```c3 List {int} l = list::ONHEAP {int}; fn void main() { l.push(1); // Implicitly allocates on the heap, not the temp allocator. } ``` -------------------------------- ### Basic Hello World Program Source: https://github.com/c3lang/c3-web.git/blob/main/docs/getting-started/hello-world.md This is the traditional 'Hello, World!' program in C3. It imports the standard I/O module and prints a message to the console. ```c3 import std::io; fn void main() { io::printn("Hello, World!"); } ``` -------------------------------- ### stdin Source: https://github.com/c3lang/c3-web.git/blob/main/docs/standard-library/docs.html Get standard input as a File. ```APIDOC ## stdin ### Description Get standard in. ### Method Not applicable (function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c3 let file = stdin(); ``` ### Response #### Success Response - **return** (File*) - stdin as a File #### Response Example ```json { "return": "" } ``` ```