Standard Library Overview & API
Complete reference for NextViper built-in standard library modules and APIs.
NextViper Standard Library API Reference
Comprehensive specification and API reference for the NextViper 1.0 Standard Library.
Table of Contents
std.io
Standard stream input and output primitives.
import std.ioFunctions
| Function | Signature | Description | |
|---|---|---|---|
| `print` | `(...args) -> nil` | Prints values separated by spaces to stdout with a trailing newline. | |
| `println` | `(...args) -> nil` | Alias for `print`. | |
| `eprint` | `(...args) -> nil` | Prints values separated by spaces to stderr with a trailing newline. | |
| `eprintln` | `(...args) -> nil` | Alias for `eprint`. | |
| `write` | `(text: str) -> nil` | Writes raw string to stdout without a trailing newline. | |
| `flush` | `() -> nil` | Flushes the stdout buffer. | |
| `read_line` | `() -> str | nil` | Reads one line from stdin. Returns `nil` on EOF. |
| `read_all` | `() -> str` | Reads entire input stream from stdin until EOF. |
std.fs
Safe cross-platform filesystem operations.
import std.fsFunctions
| Function | Signature | Description |
|---|---|---|
| `read_text` / `read_file` | `(path: str) -> str` | Reads entire file contents as UTF-8 string. |
| `write_text` / `write_file` | `(path: str, content: str) -> bool` | Overwrites or creates file with given text content. |
| `append_text` / `append_file` | `(path: str, content: str) -> bool` | Appends text content to file. |
| `exists` | `(path: str) -> bool` | Returns `true` if path exists. |
| `is_file` | `(path: str) -> bool` | Returns `true` if path is a regular file. |
| `is_dir` | `(path: str) -> bool` | Returns `true` if path is a directory. |
| `list` / `read_dir` | `(path: str = ".") -> List<str>` | Returns sorted list of file and directory names. |
| `make_dir` / `mkdir` | `(path: str) -> bool` | Creates directory recursively. |
| `remove` / `delete_file` | `(path: str) -> bool` | Removes a single file. |
| `remove_dir` | `(path: str) -> int` | Removes directory and all children recursively. |
| `copy` | `(src: str, dst: str) -> bool` | Copies file to destination. |
| `move` / `rename` | `(src: str, dst: str) -> bool` | Moves or renames file to destination. |
| `size` | `(path: str) -> int` | Returns file size in bytes. |
std.path
Path manipulation, normalization, and inspection.
import std.pathFunctions & Properties
| Name | Type / Signature | Description |
|---|---|---|
| `join` | `(...parts: str) -> str` | Joins path components using the system separator. |
| `dirname` | `(path: str) -> str` | Returns the directory name of the path. |
| `basename` | `(path: str) -> str` | Returns the filename/basename component of path. |
| `extname` | `(path: str) -> str` | Returns the extension (including `.`, e.g. `.nv`). |
| `is_absolute` | `(path: str) -> bool` | Returns `true` if path is absolute. |
| `normalize` | `(path: str) -> str` | Canonicalizes `.` and `..` relative path segments. |
| `separator` | `str` | Platform path separator (`/` on Unix, `\` on Windows). |
std.string
High-performance string routines and Unicode helpers.
import std.stringFunctions
| Function | Signature | Description |
|---|---|---|
| `split` | `(s: str, delim: str) -> List<str>` | Splits string by delimiter. |
| `join` | `(arr: List<str>, delim: str) -> str` | Joins list of strings by delimiter. |
| `trim` | `(s: str) -> str` | Strips leading and trailing whitespace. |
| `trim_start` | `(s: str) -> str` | Strips leading whitespace. |
| `trim_end` | `(s: str) -> str` | Strips trailing whitespace. |
| `to_upper` | `(s: str) -> str` | Converts string to uppercase. |
| `to_lower` | `(s: str) -> str` | Converts string to lowercase. |
| `starts_with` | `(s: str, prefix: str) -> bool` | Returns `true` if string starts with prefix. |
| `ends_with` | `(s: str, suffix: str) -> bool` | Returns `true` if string ends with suffix. |
| `contains` | `(s: str, substr: str) -> bool` | Returns `true` if string contains substring. |
| `index_of` | `(s: str, substr: str) -> int` | Returns 0-based index of substring or `-1`. |
| `replace` | `(s: str, old_s: str, new_s: str) -> str` | Replaces occurrences of `old_s` with `new_s`. |
| `len` | `(s: str) -> int` | Returns string character length. |
std.collections
Collection transformations, sorting, and data structure utilities.
import std.collectionsFunctions
| Function | Signature | Description |
|---|---|---|
| `chunk` | `(arr: List<T>, size: int) -> List<List<T>>` | Splits list into chunks of given size. |
| `flatten` | `(arr: List<Any>) -> List<Any>` | Flattens 1 level of nested lists. |
| `unique` | `(arr: List<T>) -> List<T>` | Returns elements with duplicates removed. |
| `reverse` | `(arr: List<T>) -> List<T>` | Returns reversed copy of list. |
| `sort` | `(arr: List<T>) -> List<T>` | Returns numerically or alphabetically sorted copy. |
| `zip` | `(a: List<A>, b: List<B>) -> List<[A, B]>` | Zips two lists into pairs. |
| `merge` | `(a: Map<K, V>, b: Map<K, V>) -> Map<K, V>` | Merges two maps. |
| `keys` | `(m: Map<K, V>) -> List<str>` | Returns list of map keys. |
| `values` | `(m: Map<K, V>) -> List<V>` | Returns list of map values. |
std.math
Mathematical functions, trigonometry, and constants.
import std.mathFunctions & Constants
| Function | Signature | Description |
|---|---|---|
| `pi` | `float` | Archimedes constant (3.141592653589793...). |
| `e` | `float` | Euler constant (2.718281828459045...). |
| `sqrt` | `(x: num) -> float` | Square root. |
| `cbrt` | `(x: num) -> float` | Cube root. |
| `pow` | `(base: num, exp: num) -> float` | Power / exponentiation. |
| `abs` | `(x: num) -> num` | Absolute value. |
| `sin` / `cos` / `tan` | `(rad: num) -> float` | Trigonometric functions. |
| `asin` / `acos` / `atan` | `(x: num) -> float` | Inverse trigonometric functions. |
| `atan2` | `(y: num, x: num) -> float` | Arc tangent of two variables. |
| `floor` | `(x: num) -> int` | Floor rounding to integer. |
| `ceil` | `(x: num) -> int` | Ceiling rounding to integer. |
| `round` | `(x: num) -> int` | Nearest integer rounding. |
| `min` / `max` | `(a: num, b: num) -> num` | Minimum and maximum values. |
| `clamp` | `(v: num, lo: num, hi: num) -> float` | Clamps value between lower and upper bounds. |
| `deg2rad` / `rad2deg` | `(x: num) -> float` | Angle unit conversion. |
std.json
High-speed recursive JSON parser and serializer.
import std.jsonFunctions
| Function | Signature | Description |
|---|---|---|
| `stringify` | `(value: Any, indent: int = 0) -> str` | Serializes NextViper value to JSON string. |
| `parse` | `(text: str) -> Any` | Parses JSON string into NextViper primitives, maps, and lists. |
std.csv
Tabular CSV file and data stream processing.
import std.csvFunctions
| Function | Signature | Description |
|---|---|---|
| `parse` | `(text: str) -> List<List<str>>` | Parses CSV text into rows of columns. |
| `stringify` | `(rows: List<List<Any>>) -> str` | Serializes tabular rows into CSV string. |
| `read` | `(path: str) -> List<List<str>>` | Reads and parses CSV file. |
std.time
High-resolution clock, durations, and timestamps.
import std.timeFunctions
| Function | Signature | Description |
|---|---|---|
| `now` | `() -> float` | Current Unix timestamp in fractional seconds. |
| `now_ms` | `() -> int` | Current Unix timestamp in integer milliseconds. |
| `sleep` | `(ms: int) -> nil` | Sleeps the current thread for specified milliseconds. |
| `elapsed` | `(start_time: float) -> float` | Returns seconds elapsed since `start_time`. |
| `format` | `(time: float, fmt: str = "%Y-%m-%d %H:%M:%S") -> str` | Formats timestamp via `strftime`. |
std.http
Full HTTP client supporting GET, POST, PUT, DELETE, custom headers, and JSON responses.
import std.httpFunctions & Response Structure
| Function | Signature | Description |
|---|---|---|
| `get` | `(url: str, headers: Map = {}) -> Response` | Performs HTTP GET request. |
| `post` | `(url: str, body: Any = "", headers: Map = {}) -> Response` | Performs HTTP POST request. |
| `put` | `(url: str, body: Any = "", headers: Map = {}) -> Response` | Performs HTTP PUT request. |
| `delete` | `(url: str, headers: Map = {}) -> Response` | Performs HTTP DELETE request. |
| `request` | `(method: str, url: str, body: Any = "", headers: Map = {}) -> Response` | Performs generic HTTP request. |
#### Response Object Properties & Methods:
response.status: int (e.g. 200, 404)response.text / response.body: strresponse.headers: Map<str, str>response.ok: bool (true if status in [200, 299])response.json(): () -> Any (parses body text directly as JSON)std.process
Process management, shell execution, and environment variables.
import std.processFunctions
| Function | Signature | Description | |
|---|---|---|---|
| `exec` | `(command: str) -> Map` | Runs shell command, returning `{"exit_code": int, "stdout": str, "stderr": str}`. | |
| `exit` | `(code: int = 0) -> nil` | Terminates process with exit code. | |
| `env` | `(name: str) -> str | nil` | Reads environment variable. |
| `cwd` | `() -> str` | Returns current working directory. | |
| `pid` | `() -> int` | Returns current process ID. |
std.crypto
Cryptographic hash algorithms, encodings, and secure random byte generation.
import std.cryptoFunctions
| Function | Signature | Description |
|---|---|---|
| `sha256` | `(text: str) -> str` | Computes 64-character SHA-256 hexadecimal digest. |
| `md5` | `(text: str) -> str` | Computes 32-character MD5 hexadecimal digest. |
| `base64_encode` | `(text: str) -> str` | Base64 encodes string. |
| `base64_decode` | `(encoded: str) -> str` | Base64 decodes string. |
| `random_bytes` | `(count: int) -> str` | Generates `count` bytes formatted as hex string. |
std.regex
Regular expression pattern matching and substitutions.
import std.regexFunctions
| Function | Signature | Description | |
|---|---|---|---|
| `test` | `(pattern: str, text: str) -> bool` | Checks if pattern matches text. | |
| `match` | `(pattern: str, text: str) -> List<str> | nil` | Returns captured match groups or `nil`. |
| `find_all` | `(pattern: str, text: str) -> List<str>` | Returns list of all substring matches. | |
| `replace` | `(pattern: str, repl: str, text: str) -> str` | Replaces regex matches with replacement string. |
std.random
Pseudo-random numbers and collection sampling.
import std.randomFunctions
| Function | Signature | Description |
|---|---|---|
| `random` | `() -> float` | Returns random float in `[0.0, 1.0)`. |
| `randint` | `(min: int, max: int) -> int` | Returns random integer in `[min, max]`. |
| `uniform` | `(low: float, high: float) -> float` | Returns random float in `[low, high)`. |
| `choice` | `(arr: List<T>) -> T` | Selects a random element from non-empty list. |
| `shuffle` | `(arr: List<T>) -> List<T>` | Returns a shuffled copy of the list. |
| `seed` | `(val: int) -> nil` | Seeds the PRNG generator. |
std.concurrency
Message-passing channel communication.
import std.concurrencyFunctions & Channel Object
| Function | Signature | Description |
|---|---|---|
| `sleep` | `(ms: int) -> nil` | Sleeps current thread for `ms` milliseconds. |
| `channel` | `(capacity: int = 1024) -> Channel` | Creates a thread-safe message passing channel. |
#### Channel Object Methods:
ch.send(val: Any) -> bool: Sends a value to the channel (blocks if full).ch.recv() -> Any: Receives value from channel (blocks until available).ch.try_recv() -> Any | nil: Non-blocking receive (returns nil if empty).ch.len() -> int: Returns current queue length.ch.close() -> nil: Closes the channel.NextViper Standard Library Architecture Specification
Architectural Philosophy
NextViper’s standard library is designed as a stable, modular, and high-performance API layer that sits directly on top of the NextViper runtime. It adheres strictly to the following foundational principles:
Layered Architecture
+-------------------------------------------------------------------------+
| User NextViper Source Code (*.nv) |
| import std.fs import std.json import std.http ... |
+------------------------------------+------------------------------------+
|
v
+-------------------------------------------------------------------------+
| Module Manager & Name Resolution Layer |
| - Canonical Search Path Resolution ("./std", "./modules", "./packages")|
| - Circular Dependency Detection & Caching |
| - Namespace Isolation & Export Packaging |
+------------------------------------+------------------------------------+
|
+---------------------+---------------------+
| |
v v
+-----------------------------+ +-----------------------------+
| Interpreter Runtime | | Native AOT Compiler |
| - Value Tagged Union | | - 3AC Typed IR Lowering |
| - Native C++ Function Thunks| | - C Runtime Linkage Library |
| - First-Class Closures | | - Machine Binary Generation |
+-----------------------------+ +-----------------------------+
| |
+---------------------+---------------------+
|
v
+-------------------------------------------------------------------------+
| Standard Platform & OS Abstraction Layer |
| POSIX / Win32 / Libc / Sockets / Filesystem / Microsecond Clocks |
+-------------------------------------------------------------------------+Standard Library Modules
The standard library encompasses 15 core domains organized under std/:
| Module | Canonical Import | Description |
|---|---|---|
| **`std.io`** | `import std.io` | Standard stream I/O (`print`, `println`, `eprint`, `eprintln`, `read_line`, `read_all`, `flush`). |
| **`std.fs`** | `import std.fs` | Safe filesystem operations (`read_text`, `write_text`, `append_text`, `exists`, `is_file`, `is_dir`, `list`, `make_dir`, `remove`, `copy`, `move`, `size`). |
| **`std.path`** | `import std.path` | Path normalization and manipulation (`join`, `dirname`, `basename`, `extname`, `is_absolute`, `normalize`). |
| **`std.string`** | `import std.string` | High-speed string routines (`split`, `join`, `trim`, `to_upper`, `to_lower`, `starts_with`, `ends_with`, `contains`, `replace`, `len`). |
| **`std.collections`** | `import std.collections` | Data structure utilities (`chunk`, `flatten`, `unique`, `reverse`, `sort`, `zip`, `merge`, `keys`, `values`). |
| **`std.math`** | `import std.math` | Mathematical functions & constants (`sqrt`, `cbrt`, `pow`, `sin`, `cos`, `tan`, `log`, `floor`, `ceil`, `round`, `min`, `max`, `clamp`, `pi`, `e`). |
| **`std.json`** | `import std.json` | High-speed JSON serialization and recursive descent parsing (`stringify`, `parse`). |
| **`std.csv`** | `import std.csv` | Tabular CSV serialization and parsing (`parse`, `stringify`, `read`). |
| **`std.time`** | `import std.time` | Timestamps, durations, formatting, and sleeping (`now`, `now_ms`, `sleep`, `elapsed`, `format`). |
| **`std.http`** | `import std.http` | HTTP client with status codes, headers, response text, and native `.json()` body parser (`get`, `post`, `put`, `delete`, `request`). |
| **`std.process`** | `import std.process` | Process spawning, environment variables, working directory, and PID (`exec`, `exit`, `env`, `cwd`, `pid`). |
| **`std.crypto`** | `import std.crypto` | Cryptographic digests and encodings (`sha256`, `md5`, `base64_encode`, `base64_decode`, `random_bytes`). |
| **`std.regex`** | `import std.regex` | Regular expressions pattern matching and replacement (`test`, `match`, `find_all`, `replace`). |
| **`std.random`** | `import std.random` | High-quality pseudo-random number distributions (`random`, `randint`, `uniform`, `choice`, `shuffle`, `seed`). |
| **`std.concurrency`** | `import std.concurrency` | Message passing channels and task synchronization (`channel`, `sleep`). |
Module Resolution & Security Model
The [ModuleManager](file:///root/nextviper/src/module.cpp) enforces security boundaries during import resolution:
../ escaping project roots).loading_modules_ detecting circular import dependencies at compile/load time.std.*)./std)./modules, ./nextviper_modules, ./packages)Value::OBJECT preventing namespace pollution.Dual-Engine Equivalence & Integration
Both execution backends provide identical access to standard library functions:
NativeFunction objects in Value with typed argument validation.nv_fn_math_*, nv_fn_string_*, nv_fn_time_*).tests/test_stdlib.cpp](file:///root/nextviper/tests/test_stdlib.cpp) assert exact stdout and return value parity across both engines.
