### Basic Zero Workflow Examples Source: https://zerolang.ai/examples Demonstrates fundamental Zero commands for checking, building, and running a simple 'hello world' example, as well as building a direct WASM module. ```bash bin/zero check examples/hello.0 ``` ```bash bin/zero build --emit exe --target linux-musl-x64 examples/add.0 --out .zero/out/add ``` ```bash ./.zero/out/add ``` ```bash bin/zero build --emit wasm --target wasm32-wasi examples/direct-wasm-add.0 --out .zero/out/direct-wasm-add.wasm ``` -------------------------------- ### Parse Primitives Example Source: https://zerolang.ai/modules/parse Demonstrates the usage of various parsing primitives including ASCII digit checking, identifier start checking, scanning digits, and parsing unsigned 16-bit integers. This example verifies the correct functionality of these primitives. ```zero use std.parse pub fun main(world: World) -> Void raises { let digit = std.parse.isAsciiDigit("7") let ident = std.parse.isIdentifierStart("_") let scanned = std.parse.scanDigits("123abc") let parsed = std.parse.parseU16("8080") if digit && ident && scanned == 3 && parsed.has && parsed.value == 8080 { check world.out.write("parse primitives ok\n") } } ``` -------------------------------- ### Install Latest Zero Compiler Source: https://zerolang.ai/install Installs the latest Zero release using a curl script and adds it to the PATH. Verifies the installation by checking the version. ```bash curl -fsSL https://zerolang.ai/install.sh | bash export PATH="$HOME/.zero/bin:$PATH" zero --version ``` -------------------------------- ### Check Multiple Zero Examples Source: https://zerolang.ai/getting-started Runs the `zero check` command on various example files to demonstrate core Zero syntax features. ```bash zero check examples/hello.0 zero check examples/hello-let.0 zero check examples/functions.0 zero check examples/branch.0 zero check examples/point.0 zero check examples/result-choice.0 ``` -------------------------------- ### Quick Command Loop Examples Source: https://zerolang.ai/native-compiler Demonstrates common commands for checking code, building executables for specific targets, and running the built application. ```bash bin/zero check examples/hello.0 bin/zero build --emit exe --target linux-musl-x64 examples/add.0 --out .zero/out/add ./.zero/out/add ``` -------------------------------- ### Build Profiles for Debug, Fast, and Small Source: https://zerolang.ai/examples Illustrates building the 'hello.0' example with different build profiles (debug, fast, small) and outputting JSON build reports. ```bash bin/zero build --json --profile debug --target linux-musl-x64 examples/hello.0 --out .zero/out/hello-debug ``` ```bash bin/zero build --json --profile fast --target linux-musl-x64 examples/hello.0 --out .zero/out/hello-fast ``` ```bash bin/zero build --json --profile small --target linux-musl-x64 examples/hello.0 --out .zero/out/hello-small ``` ```bash bin/zero size --json --profile tiny --target linux-musl-x64 examples/fixed-vec.0 ``` -------------------------------- ### Build Compiler from Local Checkout Source: https://zerolang.ai/install Installs dependencies, builds the Zero compiler from a local repository checkout, and verifies the build by checking the version. ```bash npm install make -C native/zero-c bin/zero --version ``` -------------------------------- ### HTTP Client and Server Initialization Source: https://zerolang.ai/modules/http Demonstrates creating an HTTP client and server instance using network capabilities and an address. This setup is for metadata creation and does not include request/response handling. ```zig pub fun main(world: World) -> Void raises { let net = std.net.host() let addr = std.net.address("localhost", 8080_u16) let _client = std.http.client(net) let _server = std.http.server(net, addr) // ... rest of the code } ``` -------------------------------- ### File System Operations Example Source: https://zerolang.ai/modules/fs Demonstrates creating, writing to, checking the length of, renaming, and removing a file using std.fs functions. It also verifies file existence. ```zero pub fun main(world: World) -> Void raises { NotFound, TooLarge, Io } { let fs = std.fs.host() let mut file: owned = check std.fs.createOrRaise(fs, ".zero/out/example.txt") check std.fs.writeAllOrRaise(&mut file, std.mem.span("hello\n")) let len = check std.fs.fileLenOrRaise(&mut file) std.fs.close(&mut file) if len == 6 && std.fs.exists(".zero/out/example.txt") { if std.fs.rename(".zero/out/example.txt", ".zero/out/example-renamed.txt") { if std.fs.remove(".zero/out/example-renamed.txt") { check world.out.write("fs ok\n") } } } } ``` -------------------------------- ### Tiny Profile Build and Size Check Source: https://zerolang.ai/examples Shows how to build a 'tiny' profile artifact for a 'hello world' example and then check its size using the 'zero size' command. ```bash bin/zero build --release tiny --target linux-musl-x64 examples/hello.0 --out .zero/out/hello-tiny ``` ```bash bin/zero size --json --release tiny --target linux-musl-x64 --out .zero/out/hello-tiny examples/hello.0 ``` -------------------------------- ### Run Native Test for Zero-Hash Source: https://zerolang.ai/examples Command to run the native test for the zero-hash example. ```bash npm run native:test ``` -------------------------------- ### Zero Program with Calculation Source: https://zerolang.ai/getting-started An example demonstrating a helper function, local variable binding, and conditional logic (`if`/`else`) to perform a calculation and write a result to output. ```zero fun answer() -> i32 { return 40 + 2 } pub fun main(world: World) -> Void raises { let value = answer() if value == 42 { check world.out.write("math works\n") } else { check world.out.write("math broke\n") } } ``` -------------------------------- ### Benchmark Zero-Hash Source: https://zerolang.ai/examples Command to run the benchmark for the zero-hash example, setting the number of runs. ```bash ZERO_BENCH_RUNS=1 npm run bench ``` -------------------------------- ### Configure Web Target in Project Settings Source: https://zerolang.ai/learn Example of a project configuration file specifying a web target with its runtime and route directory. This enables building and running web applications. ```json { "targets": { "web": { "kind": "web", "runtime": "wasm32-web", "routes": "src/routes" } } } ``` -------------------------------- ### Build Zero-Hash CLI Source: https://zerolang.ai/examples Command to build the zero-hash CLI example, emitting WASM for wasm32-wasi target. ```bash bin/zero build --emit wasm --target wasm32-wasi examples/zero-hash --out .zero/out/zero-hash ``` -------------------------------- ### Expected Output for Zero-Hash Source: https://zerolang.ai/examples The expected output when running the zero-hash example. ```text zero-hash ok ``` -------------------------------- ### Get Zero-Hash Size Report Source: https://zerolang.ai/examples Command to generate a JSON size report for the zero-hash example targeting wasm32-wasi. ```bash bin/zero size --json --target wasm32-wasi examples/zero-hash --out .zero/out/zero-hash-size.json ``` -------------------------------- ### Import std.parse Module Source: https://zerolang.ai/learn Imports the `std.parse` module for string parsing utilities. This example checks if a character is an ASCII digit and if a character can start an identifier. ```zero use std.parse pub fun main(world: World) -> Void raises { let digit = std.parse.isAsciiDigit("7") let ident = std.parse.isIdentifierStart("_") if digit && ident { check world.out.write("parse primitives ok\n") } } ``` -------------------------------- ### Deterministic Exit Status Example Source: https://zerolang.ai/examples Builds a tiny direct native executable that is designed to return a specific exit status (42). ```bash examples/direct-exe-return.0 ``` -------------------------------- ### Zero Package Manifest Source: https://zerolang.ai/getting-started An example of a `zero.json` manifest file, defining package metadata and target configurations for a Zero project. ```json { "package": { "name": "systems-package", "version": "0.1.0" }, "targets": { "cli": { "kind": "exe", "main": "src/main.0" } } } ``` -------------------------------- ### Fuzzing Formatter Commands Source: https://zerolang.ai/testing Example of fuzzing the formatter by comparing `zero fmt` output against stable source snapshots. ```bash zero fmt ``` -------------------------------- ### Zero Bindings with `let` Source: https://zerolang.ai/learn Introduce local bindings using `let`. Use `let mut` only when the value is intentionally reassigned. This example binds a message string and writes it to output. ```zero pub fun main(world: World) -> Void raises { let message = "hello from a binding\n" check world.out.write(message) } ``` -------------------------------- ### Memory Span and Copy Example Source: https://zerolang.ai/modules/mem Demonstrates creating memory spans from string literals, copying data between spans, and checking lengths and equality. This is useful for basic memory manipulation and verification. ```zero shape SliceView { bytes: Span, values: Span, } pub fun main(world: World) -> Void raises { let bytes: Span = std.mem.span("zero-memory") let same = std.mem.span("zero-memory") let mut scratch: [11]u8 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] let copied = std.mem.copy(scratch, bytes) let mut ints: [3]i32 = [1, 2, 3] let intSpan: MutSpan = ints intSpan[1] = 20 let view = SliceView { bytes: bytes, values: intSpan } if copied == 11 && std.mem.len(view.bytes) == 11 && std.mem.eqlBytes(view.bytes, same) && std.mem.len(view.values) == 3 && std.mem.eqlBytes(view.values, intSpan) { check world.out.write("memory type forms runnable\n") } } ``` -------------------------------- ### Fuzzing Checker Commands Source: https://zerolang.ai/testing Example of fuzzing the checker using `zero check --json` and asserting diagnostics. ```bash zero check --json ``` -------------------------------- ### Fuzzing Parser Commands Source: https://zerolang.ai/testing Examples of fuzzing the parser using `zero tokens --json` and `zero parse --json` with generated files. ```bash zero tokens --json ``` ```bash zero parse --json ``` -------------------------------- ### Codec Primitives Example Source: https://zerolang.ai/modules/codec Demonstrates the usage of `encodedVarintLen`, `crc32`, and `crc32Bytes` functions. It verifies the expected lengths and checksums, and checks if the CRC-32 of a string matches the CRC-32 of its byte representation. ```zero use std.codecuse std.mem pub fun main(world: World) -> Void raises { let len = std.codec.encodedVarintLen(300) let checksum = std.codec.crc32("zero") let bytes = std.mem.span("zero") let byte_checksum = std.codec.crc32Bytes(bytes) if len == 2 && checksum == byte_checksum { check world.out.write("codec primitives ok\n") } } ``` -------------------------------- ### Basic World Capability Usage Source: https://zerolang.ai/primitives Demonstrates a basic interaction with the `World` capability to write to standard output. This is an example of using a capability surface. ```rust pub fun main(world: World) -> Void raises { check world.out.write("hello\n") } ``` -------------------------------- ### Inspect Web Route Manifest with Zero CLI Source: https://zerolang.ai/learn Command-line instruction to inspect the route manifest and web bundle audit metadata for a given example directory. This helps in understanding the web application's structure and dependencies. ```bash zero routes --json examples/web/hello ``` -------------------------------- ### Zero Test Block Syntax Source: https://zerolang.ai/learn Defines a test case using the `test` keyword followed by a description and an assertion. This example tests basic addition. ```zero test "addition is stable" { expect(40 + 2 == 42) } ``` -------------------------------- ### Importing Modules in ZeroLang Source: https://zerolang.ai/reference Use the `use` keyword to import modules. For example, `use std.codec` imports the `codec` module from the `std` library. ```zerolang use std.codec use std.parse ``` -------------------------------- ### Get Zero CLI Version Source: https://zerolang.ai/cli Display the current version of the Zero CLI. Use the --json flag for machine-readable output. ```bash zero --version [--json] ``` -------------------------------- ### Fixed Buffer Allocation Example Source: https://zerolang.ai/modules/mem Illustrates using `std.mem.fixedBufAlloc` to create an allocator that uses a pre-defined buffer. This is suitable for scenarios where memory must be managed within a specific, caller-owned storage. ```zero pub fun main(world: World) -> Void raises { let mut storage: [8]u8 = [0, 0, 0, 0, 0, 0, 0, 0] let mut alloc: FixedBufAlloc = std.mem.fixedBufAlloc(storage) let bytes = std.mem.allocBytes(alloc, 4) if bytes.has { bytes.value[0] = 90 check world.out.write("fixed buffer allocated\n") } } ``` -------------------------------- ### Create a Web Handler with GET function Source: https://zerolang.ai/learn Defines a simple web handler function that returns a text response. This handler is intended to be exported by a web route. ```zero pub fun GET(req: Request) -> Response { return Response.text("hello from zero web\n") } ``` -------------------------------- ### Import std.codec Module Source: https://zerolang.ai/learn Imports the `std.codec` module to use its functions for encoding and checksum calculations. This example demonstrates reading encoded varints and calculating CRC32 checksums. ```zero use std.codec pub fun main(world: World) -> Void raises { let len = std.codec.encodedVarintLen(300) let checksum = std.codec.crc32("zero") if len == 2 && checksum > 0 { check world.out.write("codec primitives ok\n") } } ``` -------------------------------- ### Defining a Struct with Span and Maybe References Source: https://zerolang.ai/primitives Example of defining a struct `BufferView` that uses `Span` for a memory view and `Maybe>` for an optional owner. ```zero shape BufferView { bytes: Span, owner: Maybe>, } pub fun len(view: BufferView) -> usize { return std.mem.len(view.bytes) } ``` -------------------------------- ### Zero Project Workflow Source: https://zerolang.ai/getting-started Demonstrates the initial steps for creating a new Zero project using `zero new`, followed by checking, testing, running, and building the project. ```bash zero new cli hello cd hello zero check . zero test . zero run . zero build --target linux-musl-x64 --out .zero/out/hello . ``` -------------------------------- ### Standard Library Symbol Metadata Example Source: https://zerolang.ai/standard-library Public standard library symbols document metadata fields required for safe invocation, including effects, allocation behavior, target support, error behavior, ownership notes, and example usage. ```text symbol: std.fs.readAllOrRaise effects: fs allocation behavior: caller allocator target support: host error behavior: raises { NotFound, TooLarge, Io } ownership notes: returns owned example: examples/readall-cli/ ``` -------------------------------- ### Connect to a Localhost Server Source: https://zerolang.ai/modules/net Creates a hosted network capability, builds an address with a timeout, and attempts to establish a connection. Verifies the connection and the hostname. ```zero pub fun main(world: World) -> Void raises { let net = std.net.host() let addr = std.net.withTimeout(std.net.address("localhost", 8080_u16), std.time.ms(250)) let conn = std.net.connect(net, addr) if conn.has && std.mem.eql(std.net.dnsName(addr), "localhost") { check world.out.write("net ok\n") }} ``` -------------------------------- ### Create New Zero Project Source: https://zerolang.ai/cli Initialize a new Zero project. Specify the project type (cli, lib, package) and the destination path. ```bash zero new cli|lib|package ``` -------------------------------- ### Get File Length (Maybe) Source: https://zerolang.ai/modules/fs Reports the length of the file in bytes, if available. ```APIDOC ## std.fs.fileLen ### Description Reports file length when available. ### Parameters #### Path Parameters - **file** (Mut) - Required - A mutable reference to the file handle. ### Return - **Maybe** - The file length in bytes, or `null` if unavailable. ``` -------------------------------- ### Get File Length or Raise Source: https://zerolang.ai/modules/fs Reports the length of the file in bytes or raises an error. ```APIDOC ## std.fs.fileLenOrRaise ### Description Reports the file length or raises. ### Parameters #### Path Parameters - **file** (Mut) - Required - A mutable reference to the file handle. ### Return - **usize** - The file length in bytes. ``` -------------------------------- ### Building Different Output Formats Source: https://zerolang.ai/cli Commands to build Zero programs into various output formats like native executables, object files, or WebAssembly modules. Specify the desired format with '--emit' and the target platform with '--target'. ```bash zero build --emit exe --target linux-musl-x64 ``` ```bash zero build --emit obj --target linux-musl-x64 ``` ```bash zero build --emit wasm --target wasm32-wasi ``` -------------------------------- ### Check Cross-Target Status for Zero-Hash Source: https://zerolang.ai/examples Command to check the cross-target status of the zero-hash example for wasm32-web. ```bash bin/zero check --json --target wasm32-web examples/zero-hash ``` -------------------------------- ### Inspect Zero-Hash Graph Metadata Source: https://zerolang.ai/examples Command to inspect the JSON graph metadata for the zero-hash example. ```bash bin/zero graph --json examples/zero-hash ``` -------------------------------- ### Zero Hello World Program Source: https://zerolang.ai/getting-started A basic Zero program that writes 'hello from zero' to standard output. It demonstrates the entry point `pub fun main` and capability-based output using `world.out.write`. ```zero pub fun main(world: World) -> Void raises { check world.out.write("hello from zero\n") } ``` -------------------------------- ### Ship Zero Project Source: https://zerolang.ai/cli Prepare a Zero project for deployment, with options for JSON output, targeting, specific release profiles, and output files. ```bash zero ship [--json] [--target ] [--profile release-small|tiny|audit] [--out ] ``` -------------------------------- ### Explain Diagnostic Code (JSON Output) Source: https://zerolang.ai/diagnostics Use to get a machine-readable explanation for a specific diagnostic code. ```bash zero explain --json TYP009 ``` -------------------------------- ### Basic Math and Output in Zero Source: https://zerolang.ai/ Demonstrates a simple function returning an integer and a main function that checks the result and writes to standard output. Requires a 'World' type for I/O. ```zero fun answer() -> i32 { return 40 + 2 } pub fun main(world: World) -> Void raises { if answer() == 42 { check world.out.write("math works\n") } } ``` -------------------------------- ### Using std.io.bufferedReader and std.io.copy Source: https://zerolang.ai/modules/io Demonstrates creating a buffered reader and copying data using std.io.copy. Verifies reader capacity and copied byte count. ```zero pub fun main(world: World) -> Void raises { let mut copy_dst: [4]u8 = [0, 0, 0, 0] let mut reader_buf: [8]u8 = [0, 0, 0, 0, 0, 0, 0, 0] let reader = std.io.bufferedReader(reader_buf) let copied = std.io.copy(copy_dst, std.mem.span("abcd")) if std.io.readerCapacity(&reader) == 8 && copied == 4 { check world.out.write("io ok\n") }} ``` -------------------------------- ### Copy Bytes Between Mutable Arrays Source: https://zerolang.ai/diagnostics Example of copying bytes between two arrays. This requires mutable storage for the destination. ```zerolang let dst: [4]u8 = [0, 0, 0, 0]let src: [4]u8 = [122, 101, 114, 111]let _copied = std.mem.copy(dst, src) ``` -------------------------------- ### Generate Zero Project Documentation Source: https://zerolang.ai/cli Create documentation for a Zero project. Supports JSON output and targeting specific build configurations. ```bash zero doc [--json] [--target ] ``` -------------------------------- ### Explain Zero Diagnostic Code Source: https://zerolang.ai/cli Get an explanation for a specific Zero diagnostic code. Supports JSON output. ```bash zero explain [--json] ``` -------------------------------- ### ASCII Character Checks Source: https://zerolang.ai/modules/parse Functions to check if a character is an ASCII digit, alphabetic, a valid identifier start, or whitespace. ```APIDOC ## std.parse.isAsciiDigit(value) ### Description Checks whether the first byte is `0` through `9`. ### Parameters #### Path Parameters - **value** (string) - Required - The input string to check. ### Return - **Bool** - True if the first byte is an ASCII digit, false otherwise. ## std.parse.isAsciiAlpha(value) ### Description Checks whether the first byte is ASCII alphabetic. ### Parameters #### Path Parameters - **value** (string) - Required - The input string to check. ### Return - **Bool** - True if the first byte is ASCII alphabetic, false otherwise. ## std.parse.isIdentifierStart(value) ### Description Checks whether the first byte can start a Zero identifier. ### Parameters #### Path Parameters - **value** (string) - Required - The input string to check. ### Return - **Bool** - True if the first byte can start a Zero identifier, false otherwise. ## std.parse.isWhitespace(value) ### Description Checks for ASCII whitespace. ### Parameters #### Path Parameters - **value** (string) - Required - The input string to check. ### Return - **Bool** - True if the first byte is ASCII whitespace, false otherwise. ``` -------------------------------- ### Cross-Compilation for Linux and Windows Source: https://zerolang.ai/examples Demonstrates building a 'tiny' release artifact for both Linux (musl) and Windows (win32) targets from a macOS host, and checking the size of the Linux artifact. ```bash bin/zero build --release tiny --target linux-musl-x64 examples/hello.0 --out .zero/out/hello-linux-musl ``` ```bash bin/zero build --release tiny --target win32-x64.exe examples/hello.0 --out .zero/out/hello-win32 ``` ```bash bin/zero size --json --release tiny --target linux-musl-x64 --out .zero/out/hello-linux-musl examples/hello.0 ``` -------------------------------- ### List Available Targets and Check Compatibility Source: https://zerolang.ai/cross-compilation Use `zero targets` to see available build targets and `zero check` to verify package compatibility with a specific target. ```bash bin/zero targets ``` ```bash bin/zero check --target linux-musl-x64 examples/memory-package ``` -------------------------------- ### Build Zero Project Source: https://zerolang.ai/cli Compile a Zero project, specifying the output format (exe, obj, wasm), target, profile, and output file. ```bash zero build [--emit exe|obj|wasm] [--target ] [--profile dev|release] [--out ] ``` -------------------------------- ### Use std.args and std.fs for CLI Arguments Source: https://zerolang.ai/learn Demonstrates using `std.args.get` to retrieve command-line arguments and `std.fs.write` to write to a file. `std.args.get` returns `Maybe` as the argument might not exist. ```zero pub fun main(world: World) -> Void raises { let first = std.args.get(1) if first.has { let written = std.fs.write(".zero/out/name.txt", first.value) if written > 0 { check world.out.write("wrote argument\n") } } } ``` -------------------------------- ### Create File or Raise Source: https://zerolang.ai/modules/fs Creates a file at the given path or raises an error if it cannot be created. ```APIDOC ## std.fs.createOrRaise ### Description Creates a file or raises `{ NotFound, TooLarge, Io }`. ### Parameters #### Path Parameters - **fs** (Fs) - Required - The filesystem capability. - **path** (string) - Required - The path for the new file. ### Return - **owned** - An owned file handle. ``` -------------------------------- ### Build with Tiny Profile Source: https://zerolang.ai/optimization Builds a project using the 'tiny' profile, prioritizing minimal artifact size. Includes detailed profile information via the --json flag. ```bash bin/zero build --json --profile tiny --target linux-musl-x64 examples/hello.0 --out .zero/out/hello-tiny ``` -------------------------------- ### Declare Public Constant Type Source: https://zerolang.ai/diagnostics Public constants require explicit API shape. This example shows a constant without a type annotation. ```zerolang pub const answer = 42 ``` -------------------------------- ### std.net.listen Source: https://zerolang.ai/modules/net Returns a bootstrap listener handle when available. ```APIDOC ## std.net.listen ### Description Returns a bootstrap listener handle when available. ### Signature `std.net.listen(net: Net, address: Address) -> Maybe` ``` -------------------------------- ### std.net.host Source: https://zerolang.ai/modules/net Creates the hosted network capability. ```APIDOC ## std.net.host ### Description Creates the hosted network capability. ### Signature `std.net.host() -> Net` ``` -------------------------------- ### Define Type Alias Without Cycles Source: https://zerolang.ai/diagnostics Type aliases cannot cycle. This example defines a type alias `A` that refers to `B`, and `B` refers back to `A`. ```zerolang type A = Btype B = A ``` -------------------------------- ### Build with Small Profile Source: https://zerolang.ai/optimization Builds a project using the 'small' profile for optimized release artifacts. The --json flag includes detailed profile information in the output. ```bash bin/zero build --json --profile small --target linux-musl-x64 examples/hello.0 --out .zero/out/hello-small ``` -------------------------------- ### Define and Use FixedVec Source: https://zerolang.ai/diagnostics Defines a fixed-size vector structure and a function to retrieve its first element. This example demonstrates a type conflict that triggers a static-value diagnostic. ```zerolang shape FixedVec { len: usize, items: [N]T, } fun first(vec: ref>) -> T { return vec.items[0] } let vec: FixedVec = FixedVec { len: 4, items: [1, 2, 3, 4] } let bad = first(&vec) ``` -------------------------------- ### Basic Zero CLI Commands Source: https://zerolang.ai/cli Common commands for checking, running, testing, formatting, building, and inspecting Zero programs. Use these for everyday development tasks. ```bash zero check examples/hello.0 ``` ```bash zero run examples/add.0 ``` ```bash zero test conformance/native/pass/test-blocks.0 ``` ```bash zero fmt examples/hello.0 ``` ```bash zero build --emit exe --target linux-musl-x64 examples/add.0 --out .zero/out/add ``` ```bash zero build --emit wasm --target wasm32-wasi examples/direct-wasm-add.0 --out .zero/out/add.wasm ``` ```bash zero graph --json examples/systems-package ``` ```bash zero size --json examples/point.0 ``` ```bash zero ship --json --target linux-musl-x64 examples/hello.0 --out .zero/ship/hello ``` ```bash zero doctor --json ``` -------------------------------- ### Inspect Helper Metadata with zero size Source: https://zerolang.ai/standard-library Use `zero size --json ` to check helper metadata and the cost of retained helpers. ```bash zero size --json ``` -------------------------------- ### Create File with Explicit Error Flow Source: https://zerolang.ai/diagnostics Named-error `std.fs` calls require explicit error flow. This example shows creating a file using `createOrRaise`. ```zerolang let file = std.fs.createOrRaise(fs, ".zero/out.txt") ``` -------------------------------- ### std.net.connect Source: https://zerolang.ai/modules/net Returns a bootstrap connection handle when available. ```APIDOC ## std.net.connect ### Description Returns a bootstrap connection handle when available. ### Signature `std.net.connect(net: Net, address: Address) -> Maybe` ``` -------------------------------- ### ZeroLang Package Manifest Source: https://zerolang.ai/reference A ZeroLang package is defined by a `zero.json` file, specifying metadata, targets, dependencies, and build profiles. This example shows a basic executable target. ```json { "package": { "name": "systems-package", "version": "0.1.0", "license": "MIT" }, "targets": { "cli": { "kind": "exe", "main": "src/main.0" } }, "deps": {}, "profiles": { "dev": { "inherits": "dev" }, "release-small": { "inherits": "release-small" } } } ``` -------------------------------- ### Define Generic Shape Method Source: https://zerolang.ai/diagnostics This example defines a generic shape `FixedVec` with a static method `cap`. It fails when `cap` is called without explicit shape arguments. ```zerolang shape FixedVec { fun cap() -> usize { return N }} let cap = FixedVec.cap() ``` -------------------------------- ### List Available Zero Targets Source: https://zerolang.ai/cli Display a list of all available build targets for the Zero project. ```bash zero targets ``` -------------------------------- ### Build Executable with Zero Source: https://zerolang.ai/install Builds an executable for a specific target (e.g., linux-musl-x64) from a Zero source file. This command uses direct emitters and does not require an external C toolchain for WASM targets. ```bash zero build --emit exe --target linux-musl-x64 examples/hello.0 --out .zero/out/hello ``` -------------------------------- ### Get Environment Variable Source: https://zerolang.ai/modules/env Retrieves the value of a hosted environment variable named 'ZERO_MODE'. If the variable is present, its value is written to standard output; otherwise, 'default\n' is written. ```zero pub fun main(world: World) -> Void raises { let mode = std.env.get("ZERO_MODE") if mode.has { check world.out.write(mode.value) check world.out.write("\n") } else { check world.out.write("default\n") } } ``` -------------------------------- ### Run Zero Project in Development Mode Source: https://zerolang.ai/cli Execute a Zero project in development mode, enabling tracing and targeting specific build configurations. ```bash zero dev [--json] [--trace] [--target ] ``` -------------------------------- ### Using std.crypto Functions Source: https://zerolang.ai/modules/crypto Demonstrates the usage of hash32, hmac32, and constantTimeEql functions from the std.crypto module. Ensure the target supports random number generation if using secureRandomU32. ```zero pub fun main(world: World) -> Void raises { let hash = std.crypto.hash32(std.mem.span("message")) let hmac = std.crypto.hmac32(std.mem.span("key"), std.mem.span("message")) if hash > 0 && hmac > 0 && std.crypto.constantTimeEql(std.mem.span("same"), std.mem.span("same")) { check world.out.write("crypto ok\n") } } ``` -------------------------------- ### Create Directory Source: https://zerolang.ai/modules/fs Creates a hosted directory at the specified path. Returns `true` if the directory was created successfully. ```APIDOC ## std.fs.makeDir ### Description Creates a hosted directory. ### Parameters #### Path Parameters - **path** (string) - Required - The path of the directory to create. ### Return - **Bool** - `true` if the directory was created, `false` otherwise. ``` -------------------------------- ### Run Zero Project Source: https://zerolang.ai/cli Execute a Zero project with specified targets, profiles, and output files. Allows passing arguments to the executed program. ```bash zero run [--target ] [--profile dev|release] [--out ] [-- args...] ``` -------------------------------- ### Use Zero Diagnostics Tools Source: https://zerolang.ai/learn Commands for interacting with Zero's diagnostic system. `zero check --json` outputs diagnostics in JSON, `zero explain` provides details for a diagnostic code, and `zero fix --plan` suggests fixes. ```bash zero check --json conformance/check/fail/unknown-name.0 ``` ```bash zero explain NAM003 ``` ```bash zero fix --plan --json conformance/check/fail/unknown-name.0 ``` -------------------------------- ### Propose Fixes for Code Issues (JSON Output) Source: https://zerolang.ai/diagnostics Use to get proposed typed fixes for code issues without directly editing files. Includes a plan and JSON output. ```bash zero fix --plan --json conformance/native/fail/mem-copy-immutable-dst.0 ``` -------------------------------- ### Run Benchmarks Locally Source: https://zerolang.ai/benchmarks Execute the benchmark suite locally using npm. The report is generated in .zero/bench/latest.json. ```bash npm run bench ``` -------------------------------- ### Inspect Memory Budgets with zero mem Source: https://zerolang.ai/standard-library Use `zero mem --json ` to inspect `memoryBudgets`, `allocatorFacts`, `allocationInstrumentation`, and `collectionFacts`. ```bash zero mem --json ``` -------------------------------- ### Zero Data Modeling with `shape` Source: https://zerolang.ai/learn Use `shape` to define named records with fields. Shape literals name their fields, and field access uses dot notation (`value.field`). This example defines a `Point` shape and uses it. ```zero shape Point { x: i32, y: i32, } fun sum(point: Point) -> i32 { return point.x + point.y } pub fun main(world: World) -> Void raises { let point = Point { x: 40, y: 2 } let total = sum(point) if total == 42 { check world.out.write("point works\n") } } ``` -------------------------------- ### Run Benchmarks in Sandbox Mode Source: https://zerolang.ai/benchmarks Explicitly run the benchmark suite using the sandbox backend by setting the ZERO_BENCH_MODE environment variable. Sandbox mode is useful for CI environments. ```bash ZERO_BENCH_MODE=sandbox npm run bench ``` -------------------------------- ### Get Argument Count and First Argument Source: https://zerolang.ai/modules/args Retrieves the total number of command-line arguments and the value of the first argument (index 1). It checks if there are more than one argument and if the first argument exists before attempting to write it to standard output. ```zero pub fun main(world: World) -> Void raises { let count = std.args.len() let first = std.args.get(1) if count > 1 && first.has { check world.out.write(first.value) check world.out.write("\n") } } ``` -------------------------------- ### Inspect Required Capabilities with zero graph Source: https://zerolang.ai/standard-library Use `zero graph --json ` to view the required capabilities and imported helpers for a program. ```bash zero graph --json ``` -------------------------------- ### Example Compiler Error Output Source: https://zerolang.ai/diagnostics A typical compiler error message includes a stable code, a short title, a detailed message, the source code span, and explanations for the rule, expected, and actual outcomes, along with a suggested fix and an explanation link. ```text error[NAM003]: Unknown identifier unknown identifier 'message' examples/hello.0:2:27 2 | check world.out.write(message) | ^^^^^^^ rule: Names must be declared before use in the current lexical scope. expected: local binding, parameter, function, builtin value actual: no visible symbol named 'message' fix: Introduce a local binding before this use (local-edit) explain: zero explain NAM003 ``` -------------------------------- ### Inspect Build Information with JSON Output Source: https://zerolang.ai/cross-compilation Use JSON modes with build, graph, and size commands to inspect target support, required capabilities, emitters, and artifact facts. ```bash bin/zero build --json --emit exe --target linux-musl-x64 examples/direct-exe-return.0 ``` ```bash bin/zero graph --json --target wasm32-web examples/memory-package ``` ```bash bin/zero size --json --target wasm32-web examples/direct-wasm-add.0 ``` -------------------------------- ### Array and Span Slicing in Zero Source: https://zerolang.ai/reference Illustrates array and span slicing with various syntaxes, including full ranges, start/end omissions, and string slicing. Slices are half-open and bounds are checked at runtime. ```zero let bytes: [4]u8 = [65, 66, 67, 68] let first: u8 = bytes[0] let tail: Span = bytes[1..4] let view: Span = std.mem.span("ABCD") let second: u8 = view[1] let pair: Span = view[1..3] let suffix: Span = view[1..] let prefix: Span = view[..3] let all: Span = view[..] ``` ```zero let values: [4]i32 = [10, 20, 30, 40] let numbers: Span = values let third: i32 = numbers[2] let middle: Span = values[1..3] ``` ```zero let mut writableValues: [3]i32 = [1, 2, 3] let writable: MutSpan = writableValues writable[1] = 20 ``` ```zero let text: String = "zero" let byte: u8 = text[1] let bytes: Span = text[1..] ``` -------------------------------- ### Create and Add Durations Source: https://zerolang.ai/modules/time Demonstrates creating millisecond and second durations and adding them together. The result is then converted to milliseconds for comparison. ```zero pub fun main(world: World) -> Void raises { let a = std.time.ms(250) let b = std.time.seconds(1) let total = std.time.add(a, b) if std.time.asMsFloor(total) == 1250 { check world.out.write("duration ok\n") } } ``` -------------------------------- ### Create File (Maybe) Source: https://zerolang.ai/modules/fs Creates a file at the given path. Returns `null` if the file cannot be created. ```APIDOC ## std.fs.create ### Description Creates a file and returns `null` when unavailable. ### Parameters #### Path Parameters - **fs** (Fs) - Required - The filesystem capability. - **path** (string) - Required - The path for the new file. ### Return - **Maybe>** - An owned file handle if successful, otherwise `null`. ``` -------------------------------- ### List Zero Project Routes Source: https://zerolang.ai/cli Display the defined routes within a Zero project. Requires JSON output. ```bash zero routes --json ``` -------------------------------- ### Import Multiple Standard Library Modules in a Package Source: https://zerolang.ai/learn Imports `std.codec`, `std.parse`, and `std.time` within a package's main function. It demonstrates reading a U32 value, scanning digits, and adding time durations. ```zero use std.codecuse std.parseuse std.time pub fun main(world: World) -> Void raises { defer cleanup() let current: Status = status() let result: Result = Result.ok let word = std.codec.readU32("abcd") let digits = std.parse.scanDigits("123abc") let duration = std.time.add(std.time.ms(5), std.time.seconds(1)) if digits == 3 && word > 0 && std.time.asMsFloor(duration) > 0 { check world.out.write("systems package\n") } } ``` -------------------------------- ### Running Zero Code Source: https://zerolang.ai/learn To run Zero code, use the `zero check` command followed by the file path. ```bash zero check examples/hello.0 ``` -------------------------------- ### Zero Representing Alternatives with `choice` Source: https://zerolang.ai/learn Use `choice` when alternatives may carry different payloads. `examples/result-choice.0` constructs a payload choice and matches it, handling both `ok` and `err` cases. ```zero choice Result { ok: i32, err: String, } let result: Result = Result.ok(42) match result { .ok => value { if value == 42 { check world.out.write("choice ok\n") } } .err => message { check world.out.write("choice err\n") } } ``` -------------------------------- ### Open File or Raise Source: https://zerolang.ai/modules/fs Opens a file at the given path or raises an error if it cannot be opened. ```APIDOC ## std.fs.openOrRaise ### Description Opens a file or raises `{ NotFound, TooLarge, Io }`. ### Parameters #### Path Parameters - **fs** (Fs) - Required - The filesystem capability. - **path** (string) - Required - The path to the file to open. ### Return - **owned** - An owned file handle. ``` -------------------------------- ### Implement Static Interface Method Source: https://zerolang.ai/diagnostics This snippet provides the concrete static method `read` required by the `Readable` interface, resolving the 'IFC002' diagnostic. ```zerolang fun read(self: ref) -> i32 { return self.value} ``` -------------------------------- ### Build WebAssembly Artifact for Web Runtime Source: https://zerolang.ai/cross-compilation Generate a WebAssembly artifact optimized for the local web runtime, suitable for browser environments. ```bash bin/zero build --emit wasm --target wasm32-web examples/direct-array-sum.0 --out .zero/out/direct-array-sum ``` -------------------------------- ### Explain Diagnostics and Inspect Repair Plans Source: https://zerolang.ai/native-compiler Commands to explain diagnostic codes and inspect repair plans without needing to edit files. ```bash bin/zero explain TAR002 ``` ```bash bin/zero fix --plan --json conformance/native/fail/mem-copy-immutable-dst.0 ``` -------------------------------- ### Spawn Process and Check Exit Code Source: https://zerolang.ai/modules/proc Spawns a process and checks if its exit code is 0. Requires the 'zero-noop' command to be available. ```zero pub fun main(world: World) -> Void raises { let status = std.proc.spawn("zero-noop") if std.proc.exitCode(status) == 0 { check world.out.write("proc ok\n") }} ``` -------------------------------- ### Generate Zero Project Dependency Graph Source: https://zerolang.ai/cli Visualize the dependency graph of a Zero project. Supports JSON output and targeting specific build configurations. ```bash zero graph [--json] [--target ] ``` -------------------------------- ### HTTP Server Creation Source: https://zerolang.ai/modules/http Creates hosted server metadata from a network capability and address. ```APIDOC ## std.http.server(net, address) ### Description Creates hosted server metadata from a network capability and address. ### Parameters #### Path Parameters - **net** (NetworkCapability) - Required - The network capability to use for the server. - **address** (Address) - Required - The network address for the server. ### Return Value - **HttpServer** - The created HTTP server metadata. ``` -------------------------------- ### Host Filesystem Capability Source: https://zerolang.ai/modules/fs Creates and returns the hosted filesystem capability, which is required for other fs operations. ```APIDOC ## std.fs.host ### Description Creates the hosted filesystem capability. ### Return - **Fs** - The hosted filesystem capability. ``` -------------------------------- ### Plan and Fix Zero Diagnostics Source: https://zerolang.ai/cli Generate a plan and apply fixes for Zero diagnostics. Supports JSON output and targeting specific build configurations. ```bash zero fix --plan --json [--target ] ``` -------------------------------- ### HTTP Client Creation Source: https://zerolang.ai/modules/http Creates hosted client metadata from a network capability. ```APIDOC ## std.http.client(net) ### Description Creates hosted client metadata from a network capability. ### Parameters #### Path Parameters - **net** (NetworkCapability) - Required - The network capability to use for the client. ### Return Value - **HttpClient** - The created HTTP client metadata. ``` -------------------------------- ### Check Zero Project Files Source: https://zerolang.ai/cli Perform checks on Zero project files. Supports JSON output and targeting specific build configurations. ```bash zero check [--json] [--target ] ```