From 3a24766d56db8af300f446cb682a66471d59553b Mon Sep 17 00:00:00 2001 From: jow- Date: Wed, 1 Nov 2023 15:35:04 +0000 Subject: [PATCH] deploy: 448c7632dbe12c0cd0385e25503288d54a86c1e7 --- index.html | 4 +- lib.c.html | 9 ++- lib_debug.c.html | 4 +- lib_fs.c.html | 4 +- lib_log.c.html | 4 +- lib_math.c.html | 4 +- lib_struct.c.html | 4 +- lib_uci.c.html | 4 +- module-core.html | 114 ++++++++++++++++++------------------ module-debug.html | 4 +- module-fs.dir.html | 4 +- module-fs.file.html | 4 +- module-fs.html | 4 +- module-fs.proc.html | 4 +- module-log.html | 4 +- module-math.html | 4 +- module-struct.html | 4 +- module-struct.instance.html | 4 +- module-uci.cursor.html | 4 +- module-uci.html | 4 +- tutorial-01-usage.html | 4 +- tutorial-02-syntax.html | 4 +- tutorial-03-memory.html | 4 +- 23 files changed, 105 insertions(+), 102 deletions(-) diff --git a/index.html b/index.html index f1740ca7..fc83731b 100644 --- a/index.html +++ b/index.html @@ -1,6 +1,6 @@ ucode - Reference Documentation

The ucode Language

The ucode language is a tiny general purpose scripting language featuring a syntax closely resembling ECMAScript. It can be used in a stand-alone manner by using the ucode command line interpreter or embedded into host applications by linking libucode and utilizing its C language API. Additionally, ucode can be invoked in template mode where control flow and expression logic statements are embedded in Jinja-like markup blocks.

Besides aiming for small size, the major design goals of ucode are the ability to trivially read and write JSON data, good embeddability into C applications, template capabilities for output formatting, extensiblity through loadable native extension modules and a straightforward set of built-in functions mimicking those found in the Perl 5 language.

History and Motivation

In spring 2021 it has been decided to rewrite the OpenWrt firewall framework on top of nftables with the goal to replace the then current C application with a kind of preprocessor generating nftables rulesets using a set of templates instead of relying on built-in hardcoded rules like its predecessor.

That decision spurred the development of ucode, initially meant to be a simple template processor solely for the OpenWrt nftables firewall but quickly evolving into a general purpose scripting language suitable for a wider range of system scripting tasks.

Despite OpenWrt predominantly relying on POSIX shell and Lua as system scripting languages already, a new solution was needed to accomodate the needs of the new firewall implementation; mainly the ability to efficiently deal with JSON data and complex data structures such as arrays and dictionaries and the ability to closely interface with OpenWrt's ubus message bus system.

Throughout the design process of the new firewall and its template processor, the following design goals were defined for the ucode scripting language:

  • Ability to embed code logic fragments such as control flow statements, function calls or arithmetic expressions into plain text templates, using a block syntax and functionality roughly inspired by Jinja templates
  • Built-in support for JSON data parsing and serialization, without the need for external libraries
  • Distinct array and object types (compared to Lua's single table datatype)
  • Distinct integer and float types and guaranteed 64bit integer range
  • Built-in support for bit operations
  • Built-in support for (POSIX) regular expressions
  • A comprehensive set of built-in standard functions, inspired by the core functions found in the Perl 5 interpreter
  • Staying as close to ECMAScript syntax as possible due to higher developer familiarity and to be able to reuse existing tooling such as editor syntax highlighting
  • Bindings for all relevant Linux and OpenWrt APIs, such as ubus, uci, uloop, netlink etc.
  • Procedural, synchronous programming flow
  • Very small executable size (the interpreter and runtime is currently around 64KB on ARM Cortex A9)
  • Embeddability into C host applications

Summarized, ucode can be described as synchronous ECMAScript without the object oriented standard library.

Installation

OpenWrt

In OpenWrt 22.03 and later, ucode should already be preinstalled. If not, it can be installed via the package manager, using the opkg install ucode command.

MacOS

To build on MacOS, first install cmake and json-c via Homebrew, then clone the ucode repository and execute cmake followed by make:

$ brew install cmake json-c
+    

The ucode Language

The ucode language is a tiny general purpose scripting language featuring a syntax closely resembling ECMAScript. It can be used in a stand-alone manner by using the ucode command line interpreter or embedded into host applications by linking libucode and utilizing its C language API. Additionally, ucode can be invoked in template mode where control flow and expression logic statements are embedded in Jinja-like markup blocks.

Besides aiming for small size, the major design goals of ucode are the ability to trivially read and write JSON data, good embeddability into C applications, template capabilities for output formatting, extensiblity through loadable native extension modules and a straightforward set of built-in functions mimicking those found in the Perl 5 language.

History and Motivation

In spring 2021 it has been decided to rewrite the OpenWrt firewall framework on top of nftables with the goal to replace the then current C application with a kind of preprocessor generating nftables rulesets using a set of templates instead of relying on built-in hardcoded rules like its predecessor.

That decision spurred the development of ucode, initially meant to be a simple template processor solely for the OpenWrt nftables firewall but quickly evolving into a general purpose scripting language suitable for a wider range of system scripting tasks.

Despite OpenWrt predominantly relying on POSIX shell and Lua as system scripting languages already, a new solution was needed to accomodate the needs of the new firewall implementation; mainly the ability to efficiently deal with JSON data and complex data structures such as arrays and dictionaries and the ability to closely interface with OpenWrt's ubus message bus system.

Throughout the design process of the new firewall and its template processor, the following design goals were defined for the ucode scripting language:

  • Ability to embed code logic fragments such as control flow statements, function calls or arithmetic expressions into plain text templates, using a block syntax and functionality roughly inspired by Jinja templates
  • Built-in support for JSON data parsing and serialization, without the need for external libraries
  • Distinct array and object types (compared to Lua's single table datatype)
  • Distinct integer and float types and guaranteed 64bit integer range
  • Built-in support for bit operations
  • Built-in support for (POSIX) regular expressions
  • A comprehensive set of built-in standard functions, inspired by the core functions found in the Perl 5 interpreter
  • Staying as close to ECMAScript syntax as possible due to higher developer familiarity and to be able to reuse existing tooling such as editor syntax highlighting
  • Bindings for all relevant Linux and OpenWrt APIs, such as ubus, uci, uloop, netlink etc.
  • Procedural, synchronous programming flow
  • Very small executable size (the interpreter and runtime is currently around 64KB on ARM Cortex A9)
  • Embeddability into C host applications

Summarized, ucode can be described as synchronous ECMAScript without the object oriented standard library.

Installation

OpenWrt

In OpenWrt 22.03 and later, ucode should already be preinstalled. If not, it can be installed via the package manager, using the opkg install ucode command.

MacOS

To build on MacOS, first install cmake and json-c via Homebrew, then clone the ucode repository and execute cmake followed by make:

$ brew install cmake json-c
 $ git clone https://github.com/jow-/ucode.git
 $ cd ucode/
 $ cmake -DUBUS_SUPPORT=OFF -DUCI_SUPPORT=OFF -DULOOP_SUPPORT=OFF .
@@ -16,4 +16,4 @@
 $ cmake -DUBUS_SUPPORT=OFF -DUCI_SUPPORT=OFF -DULOOP_SUPPORT=OFF .
 $ make
 $ sudo make install
-
Table of Contents
\ No newline at end of file +
Table of Contents
\ No newline at end of file diff --git a/lib.c.html b/lib.c.html index 7114baf3..03d69813 100644 --- a/lib.c.html +++ b/lib.c.html @@ -1,6 +1,6 @@ Source: lib.c

lib.c

/*
+    

lib.c

/*
  * Copyright (C) 2020-2021 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -453,12 +453,15 @@
 					}
 					while (--p != sstr);
 				}
-				else {
+				else if (nlen > 0) {
 					p = (const char *)memmem(sstr, slen, nstr, nlen);
 
 					if (p)
 						ret = (ssize_t)(p - sstr);
 				}
+				else {
+					ret = 0;
+				}
 			}
 		}
 
@@ -5927,4 +5930,4 @@
 
 	return NULL;
 }
-
Table of Contents
\ No newline at end of file +
Table of Contents
\ No newline at end of file diff --git a/lib_debug.c.html b/lib_debug.c.html index 17e3fd9e..83102667 100644 --- a/lib_debug.c.html +++ b/lib_debug.c.html @@ -1,6 +1,6 @@ Source: lib/debug.c

lib_debug.c

/*
+    

lib_debug.c

/*
  * Copyright (C) 2023 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -1633,4 +1633,4 @@
 
 	debug_setup(vm);
 }
-
Table of Contents
\ No newline at end of file +
Table of Contents
\ No newline at end of file diff --git a/lib_fs.c.html b/lib_fs.c.html index 119c7445..f6f072a8 100644 --- a/lib_fs.c.html +++ b/lib_fs.c.html @@ -1,6 +1,6 @@ Source: lib/fs.c

lib_fs.c

/*
+    

lib_fs.c

/*
  * Copyright (C) 2020-2021 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -2653,4 +2653,4 @@
 	ucv_object_add(scope, "stdout", uc_resource_new(file_type, stdout));
 	ucv_object_add(scope, "stderr", uc_resource_new(file_type, stderr));
 }
-
Table of Contents
\ No newline at end of file +
Table of Contents
\ No newline at end of file diff --git a/lib_log.c.html b/lib_log.c.html index 509b716f..9483fbf1 100644 --- a/lib_log.c.html +++ b/lib_log.c.html @@ -1,6 +1,6 @@ Source: lib/log.c

lib_log.c

/*
+    

lib_log.c

/*
  * Copyright (C) 2023 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -1074,4 +1074,4 @@
 	ADD_CONST(ULOG_STDIO);
 #endif
 }
-
Table of Contents
\ No newline at end of file +
Table of Contents
\ No newline at end of file diff --git a/lib_math.c.html b/lib_math.c.html index 6c4e1b7d..52b23b87 100644 --- a/lib_math.c.html +++ b/lib_math.c.html @@ -1,6 +1,6 @@ Source: lib/math.c

lib_math.c

/*
+    

lib_math.c

/*
  * Copyright (C) 2020-2021 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -480,4 +480,4 @@
 {
 	uc_function_list_register(scope, math_fns);
 }
-
Table of Contents
\ No newline at end of file +
Table of Contents
\ No newline at end of file diff --git a/lib_struct.c.html b/lib_struct.c.html index d2e86265..4a1870f0 100644 --- a/lib_struct.c.html +++ b/lib_struct.c.html @@ -1,6 +1,6 @@ Source: lib/struct.c

lib_struct.c

/*
+    

lib_struct.c

/*
  * Binary data packing/unpacking module for ucode.
  * Copyright (C) 2021 Jo-Philipp Wich <jo@mein.io>
  *
@@ -2953,4 +2953,4 @@
 
 	struct_type = uc_type_declare(vm, "struct", struct_inst_fns, uc_struct_gc);
 }
-
Table of Contents
\ No newline at end of file +
Table of Contents
\ No newline at end of file diff --git a/lib_uci.c.html b/lib_uci.c.html index 340c396d..c67ce374 100644 --- a/lib_uci.c.html +++ b/lib_uci.c.html @@ -1,6 +1,6 @@ Source: lib/uci.c

lib_uci.c

/*
+    

lib_uci.c

/*
  * Copyright (C) 2020-2021 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -1873,4 +1873,4 @@
 
 	cursor_type = uc_type_declare(vm, "uci.cursor", cursor_fns, close_uci);
 }
-
Table of Contents
\ No newline at end of file +
Table of Contents
\ No newline at end of file diff --git a/module-core.html b/module-core.html index 19d22c00..b7feb7de 100644 --- a/module-core.html +++ b/module-core.html @@ -1,15 +1,15 @@ Module: core

Builtin functions

The core namespace is not an actual module but refers to the set of builtin functions and properties available to ucode scripts.

Source

Methods

arrtoip(arr) → {string}nullable

Convert the given input array of byte values to an IP address string.

Input arrays of length 4 are converted to IPv4 addresses, arrays of length 16 to IPv6 ones. All other lengths are rejected. If any array element is not an integer or exceeds the range 0..255 (inclusive), the array is rejected.

Returns a string containing the formatted IP address. Returns null if the input array was invalid.

Parameters:
NameTypeDescription
arrnumber[]

The byte array to convert into an IP address string.

Returns: string
Example
arrtoip([ 192, 168, 1, 1 ])   // "192.168.1.1"
+    

Builtin functions

The core namespace is not an actual module but refers to the set of builtin functions and properties available to ucode scripts.

Source

Methods

arrtoip(arr) → {string}nullable

Convert the given input array of byte values to an IP address string.

Input arrays of length 4 are converted to IPv4 addresses, arrays of length 16 to IPv6 ones. All other lengths are rejected. If any array element is not an integer or exceeds the range 0..255 (inclusive), the array is rejected.

Returns a string containing the formatted IP address. Returns null if the input array was invalid.

Parameters:
NameTypeDescription
arrnumber[]

The byte array to convert into an IP address string.

Returns: string
Example
arrtoip([ 192, 168, 1, 1 ])   // "192.168.1.1"
 arrtoip([ 254, 128, 0, 0, 0, 0, 0, 0, 252, 84, 0, 255, 254, 130, 171, 189 ])
                               // "fe80::fc54:ff:fe82:abbd"
 arrtoip([ 1, 2, 3])           // null (invalid length)
 arrtoip([ 1, "2", -5, 300 ])  // null (invalid values)
-arrtoip("123")                // null (not an array)

assert(cond, messageopt)

Raise an exception with the given message parameter when the value in cond is not truish.

When message is omitted, the default value is Assertion failed.

Parameters:
NameTypeAttributesDescription
cond*

The value to check for truthiness.

messagestringoptional(optional)

The message to include in the exception.

Throws: Error

When the condition is falsy.

Example
assert(true, "This is true");  // No exception is raised
-assert(false);                 // Exception is raised with the default message "Assertion failed"

b64dec(str) → {string}nullable

Decodes the given base64 encoded string and returns the decoded result.

  • If non-whitespace, non-base64 characters are encountered, if invalid padding or trailing garbage is found, the function returns null.
  • If a non-string argument is given, the function returns null.
Parameters:
NameTypeDescription
strstring

The base64 encoded string to decode.

Returns: string
Example
b64dec("VGhpcyBpcyBhIHRlc3Q=");         // Returns "This is a test"
+arrtoip("123")                // null (not an array)

assert(cond, messageopt)

Raise an exception with the given message parameter when the value in cond is not truish.

When message is omitted, the default value is Assertion failed.

Parameters:
NameTypeAttributesDescription
cond*

The value to check for truthiness.

messagestringoptional(optional)

The message to include in the exception.

Throws: Error

When the condition is falsy.

Example
assert(true, "This is true");  // No exception is raised
+assert(false);                 // Exception is raised with the default message "Assertion failed"

b64dec(str) → {string}nullable

Decodes the given base64 encoded string and returns the decoded result.

  • If non-whitespace, non-base64 characters are encountered, if invalid padding or trailing garbage is found, the function returns null.
  • If a non-string argument is given, the function returns null.
Parameters:
NameTypeDescription
strstring

The base64 encoded string to decode.

Returns: string
Example
b64dec("VGhpcyBpcyBhIHRlc3Q=");         // Returns "This is a test"
 b64dec(123);                           // Returns null
-b64dec("XXX");                         // Returns null

b64enc(str) → {string}nullable

Encodes the given string into base64 and returns the resulting string.

  • If a non-string argument is given, the function returns null.
Parameters:
NameTypeDescription
strstring

The string to encode.

Returns: string
Example
b64enc("This is a test");  // Returns "VGhpcyBpcyBhIHRlc3Q="
-b64enc(123);               // Returns null

call(fn, ctxopt, scopeopt, …argopt) → {*}

Calls the given function value with a modified environment.

The given ctx argument is used as this context for the invoked function and the given scope value as global environment. Any further arguments are passed to the invoked function as-is.

When ctx is omitted or null, the function will get invoked with this being null.

When scope is omitted or null, the function will get executed with the current global environment of the running program. When scope is set to a dictionary, the dictionary is used as global function environment.

When the scope dictionary has no prototype, the current global environment will be set as prototype, means the scope will inherit from it.

When a scope prototype is set, it is kept. This allows passing an isolated (sandboxed) function scope without access to the global environment.

Any further argument is forwarded as-is to the invoked function as function call argument.

Returns null if the given function value fn is not callable.

Returns the return value of the invoked function in all other cases.

Forwards exceptions thrown by the invoked function.

Parameters:
NameTypeAttributesDefaultDescription
fnfunction

Function value to call.

ctx*optionalnull(optional, default: null)

this context for the invoked function.

scopeObjectoptionalnull(optional, default: null)

Global environment for the invoked function.

arg*optional, repeatable(optional, repeatable)

Additional arguments to pass to the invoked function.

Returns: *
Example
// Override this context
+b64dec("XXX");                         // Returns null

b64enc(str) → {string}nullable

Encodes the given string into base64 and returns the resulting string.

  • If a non-string argument is given, the function returns null.
Parameters:
NameTypeDescription
strstring

The string to encode.

Returns: string
Example
b64enc("This is a test");  // Returns "VGhpcyBpcyBhIHRlc3Q="
+b64enc(123);               // Returns null

call(fn, ctxopt, scopeopt, …argopt) → {*}

Calls the given function value with a modified environment.

The given ctx argument is used as this context for the invoked function and the given scope value as global environment. Any further arguments are passed to the invoked function as-is.

When ctx is omitted or null, the function will get invoked with this being null.

When scope is omitted or null, the function will get executed with the current global environment of the running program. When scope is set to a dictionary, the dictionary is used as global function environment.

When the scope dictionary has no prototype, the current global environment will be set as prototype, means the scope will inherit from it.

When a scope prototype is set, it is kept. This allows passing an isolated (sandboxed) function scope without access to the global environment.

Any further argument is forwarded as-is to the invoked function as function call argument.

Returns null if the given function value fn is not callable.

Returns the return value of the invoked function in all other cases.

Forwards exceptions thrown by the invoked function.

Parameters:
NameTypeAttributesDefaultDescription
fnfunction

Function value to call.

ctx*optionalnull(optional, default: null)

this context for the invoked function.

scopeObjectoptionalnull(optional, default: null)

Global environment for the invoked function.

arg*optional, repeatable(optional, repeatable)

Additional arguments to pass to the invoked function.

Returns: *
Example
// Override this context
 call(function() { printf("%J\n", this) });            // null
 call(function() { printf("%J\n", this) }, null);      // null
 call(function() { printf("%J\n", this) }, { x: 1 });  // { "x": 1 }
@@ -31,13 +31,13 @@
         proto({}, { printf }));                          // null
 
 // Forward arguments
-x = call((x, y, z) => x * y * z, null, null, 2, 3, 4);   // x = 24

chr(…n1) → {string}

Converts each given numeric value to a byte and return the resulting string. Invalid numeric values or values < 0 result in \0 bytes, values larger than 255 are truncated to 255.

Returns a new strings consisting of the given byte values.

Parameters:
NameTypeAttributesDescription
n1numberrepeatable(repeatable)

The numeric values.

Returns: string
Example
chr(65, 98, 99);  // "Abc"
-chr(-1, 300);     // string consisting of an `0x0` and a `0xff` byte

clock(monotonicopt) → {number[]}nullable

Reads the current second and microsecond value of the system clock.

By default, the realtime clock is queried which might skew forwards or backwards due to NTP changes, system sleep modes etc. If a truish value is passed as argument, the monotonic system clock is queried instead, which will return the monotonically increasing time since some arbitrary point in the past (usually the system boot time).

Returns a two element array containing the full seconds as the first element and the nanosecond fraction as the second element.

Returns null if a monotonic clock value is requested and the system does not implement this clock type.

Parameters:
NameTypeAttributesDescription
monotonicbooleanoptional(optional)

Whether to query the monotonic system clock.

Returns: number[]
Example
clock();        // [ 1647954926, 798269464 ]
-clock(true);    // [ 474751, 527959975 ]

die(msg)

Raise an exception with the given message and abort execution.

Parameters:
NameTypeDescription
msgstring

The error message.

Throws: Error

The error with the given message.

Example
die(msg);

exists(obj, key) → {boolean}

Check whether the given key exists within the given object value.

Returns true if the given key is present within the object passed as the first argument, otherwise false.

Parameters:
NameTypeDescription
objObject

The input object.

keystring

The key to check for existence.

Returns: boolean
Example
let x = { foo: true, bar: false, qrx: null };
+x = call((x, y, z) => x * y * z, null, null, 2, 3, 4);   // x = 24

chr(…n1) → {string}

Converts each given numeric value to a byte and return the resulting string. Invalid numeric values or values < 0 result in \0 bytes, values larger than 255 are truncated to 255.

Returns a new strings consisting of the given byte values.

Parameters:
NameTypeAttributesDescription
n1numberrepeatable(repeatable)

The numeric values.

Returns: string
Example
chr(65, 98, 99);  // "Abc"
+chr(-1, 300);     // string consisting of an `0x0` and a `0xff` byte

clock(monotonicopt) → {number[]}nullable

Reads the current second and microsecond value of the system clock.

By default, the realtime clock is queried which might skew forwards or backwards due to NTP changes, system sleep modes etc. If a truish value is passed as argument, the monotonic system clock is queried instead, which will return the monotonically increasing time since some arbitrary point in the past (usually the system boot time).

Returns a two element array containing the full seconds as the first element and the nanosecond fraction as the second element.

Returns null if a monotonic clock value is requested and the system does not implement this clock type.

Parameters:
NameTypeAttributesDescription
monotonicbooleanoptional(optional)

Whether to query the monotonic system clock.

Returns: number[]
Example
clock();        // [ 1647954926, 798269464 ]
+clock(true);    // [ 474751, 527959975 ]

die(msg)

Raise an exception with the given message and abort execution.

Parameters:
NameTypeDescription
msgstring

The error message.

Throws: Error

The error with the given message.

Example
die(msg);

exists(obj, key) → {boolean}

Check whether the given key exists within the given object value.

Returns true if the given key is present within the object passed as the first argument, otherwise false.

Parameters:
NameTypeDescription
objObject

The input object.

keystring

The key to check for existence.

Returns: boolean
Example
let x = { foo: true, bar: false, qrx: null };
 exists(x, 'foo');  // true
 exists(x, 'qrx');  // true
-exists(x, 'baz');  // false

exit(n)

Terminate the interpreter with the given exit code.

This function does not return.

Parameters:
NameTypeDescription
nnumber

The exit code.

Example
exit();
-exit(5);

filter(arr, fn) → {Array}

Filter the array passed as the first argument by invoking the function specified in the second argument for each array item.

If the invoked function returns a truthy result, the item is retained, otherwise, it is dropped. The filter function is invoked with three arguments:

  1. The array value
  2. The current index
  3. The array being filtered

Returns a new array containing only retainted items, in the same order as the input array.

Parameters:
NameTypeDescription
arrArray

The input array.

fnfunction

The filter function.

Returns: Array
Example
// filter out any empty string:
+exists(x, 'baz');  // false

exit(n)

Terminate the interpreter with the given exit code.

This function does not return.

Parameters:
NameTypeDescription
nnumber

The exit code.

Example
exit();
+exit(5);

filter(arr, fn) → {Array}

Filter the array passed as the first argument by invoking the function specified in the second argument for each array item.

If the invoked function returns a truthy result, the item is retained, otherwise, it is dropped. The filter function is invoked with three arguments:

  1. The array value
  2. The current index
  3. The array being filtered

Returns a new array containing only retainted items, in the same order as the input array.

Parameters:
NameTypeDescription
arrArray

The input array.

fnfunction

The filter function.

Returns: Array
Example
// filter out any empty string:
 a = filter(["foo", "", "bar", "", "baz"], length)
 // a = ["foo", "bar", "baz"]
 
@@ -45,9 +45,9 @@
 a = filter(["foo", 1, true, null, 2.2], function(v) {
     return (type(v) == "int" || type(v) == "double");
 });
-// a = [1, 2.2]

gc(operationopt, argumentopt) → {boolean|number}nullable

Interacts with the mark and sweep garbage collector of the running ucode virtual machine.

Depending on the given operation string argument, the meaning of argument and the function return value differs.

The following operations are defined:

  • collect - Perform a complete garbage collection cycle, returns true.
  • start - (Re-)start periodic garbage collection, argument is an optional integer in the range 1..65535 specifying the interval. Defaults to 1000 if omitted. Returns true if the periodic GC was previously stopped and is now started or if the interval changed. Returns false otherwise.
  • stop - Stop periodic garbage collection. Returns true if the periodic GC was previously started and is now stopped, false otherwise.
  • count - Count the amount of active complex object references in the VM context, returns the counted amount.

If the operation argument is omitted, the default is collect.

Parameters:
NameTypeAttributesDescription
operationstringoptional(optional)

The operation to perform.

argument*optional(optional)

The argument for the operation.

Returns: boolean | number
Example
gc();         // true
+// a = [1, 2.2]

gc(operationopt, argumentopt) → {boolean|number}nullable

Interacts with the mark and sweep garbage collector of the running ucode virtual machine.

Depending on the given operation string argument, the meaning of argument and the function return value differs.

The following operations are defined:

  • collect - Perform a complete garbage collection cycle, returns true.
  • start - (Re-)start periodic garbage collection, argument is an optional integer in the range 1..65535 specifying the interval. Defaults to 1000 if omitted. Returns true if the periodic GC was previously stopped and is now started or if the interval changed. Returns false otherwise.
  • stop - Stop periodic garbage collection. Returns true if the periodic GC was previously started and is now stopped, false otherwise.
  • count - Count the amount of active complex object references in the VM context, returns the counted amount.

If the operation argument is omitted, the default is collect.

Parameters:
NameTypeAttributesDescription
operationstringoptional(optional)

The operation to perform.

argument*optional(optional)

The argument for the operation.

Returns: boolean | number
Example
gc();         // true
 gc("start");  // true
-gc("count");  // 42

getenv(nameopt) → {string|Object<string: string>}

Query an environment variable or then entire environment.

Returns the value of the given environment variable, or - if omitted - a dictionary containing all environment variables.

Parameters:
NameTypeAttributesDescription
namestringoptional(optional)

The name of the environment variable.

Returns: string | Object<string: string>

gmtime(epochopt) → {TimeSpec}

Like localtime() but interpreting the given epoch value as UTC time.

See localtime() for details on the return value.

Parameters:
NameTypeAttributesDescription
epochnumberoptional(optional)

The epoch timestamp.

Returns: TimeSpec
Example
gmtime(1647953502);
+gc("count");  // 42

getenv(nameopt) → {string|Object<string: string>}

Query an environment variable or then entire environment.

Returns the value of the given environment variable, or - if omitted - a dictionary containing all environment variables.

Parameters:
NameTypeAttributesDescription
namestringoptional(optional)

The name of the environment variable.

Returns: string | Object<string: string>

gmtime(epochopt) → {TimeSpec}

Like localtime() but interpreting the given epoch value as UTC time.

See localtime() for details on the return value.

Parameters:
NameTypeAttributesDescription
epochnumberoptional(optional)

The epoch timestamp.

Returns: TimeSpec
Example
gmtime(1647953502);
 // Returns:
 // {
 //     sec: 42,
@@ -59,8 +59,8 @@
 //     wday: 2,
 //     yday: 81,
 //     isdst: 0
-// }

hex(x) → {number}

Converts the given hexadecimal string into a number.

Returns the resulting integer value or NaN if the input value cannot be interpreted as hexadecimal number.

Parameters:
NameTypeDescription
x*

The hexadecimal string to be converted.

Returns: number

hexdec(hexstring, skipcharsopt) → {string}nullable

Decodes the given hexadecimal digit string into a byte string, optionally skipping specified characters.

If the characters to skip are not specified, a default of " \t\n" is used.

Returns null if the input string contains invalid characters or an uneven amount of hex digits.

Returns the decoded byte string on success.

Parameters:
NameTypeAttributesDescription
hexstringstring

The hexadecimal digit string to decode.

skipcharsstringoptional(optional)

The characters to skip during decoding.

Returns: string
Example
hexdec("48656c6c6f20776f726c64210a");  // "Hello world!\n"
-hexdec("44:55:66:77:33:44", ":");      // "DUfw3D"

hexenc(val) → {string}

Encodes the given byte string into a hexadecimal digit string, converting the input value to a string if needed.

Parameters:
NameTypeDescription
valstring

The byte string to encode.

Returns: string
Example
hexenc("Hello world!\n");   // "48656c6c6f20776f726c64210a"

include(path, scopeopt)

Evaluate and include the file at the given path and optionally override the execution scope with the given scope object.

By default, the file is executed within the same scope as the calling include(), but by passing an object as the second argument, it is possible to extend the scope available to the included file.

This is useful to supply additional properties as global variables to the included code. To sandbox included code, that is giving it only access to explicitly provided properties, the proto() function can be used to create a scope object with an empty prototype.

Parameters:
NameTypeAttributesDescription
pathstring

The path to the file to be included.

scopeObjectoptional(optional)

The optional scope object to override the execution scope.

Example
// Load and execute "foo.uc" immediately
+// }

hex(x) → {number}

Converts the given hexadecimal string into a number.

Returns the resulting integer value or NaN if the input value cannot be interpreted as hexadecimal number.

Parameters:
NameTypeDescription
x*

The hexadecimal string to be converted.

Returns: number

hexdec(hexstring, skipcharsopt) → {string}nullable

Decodes the given hexadecimal digit string into a byte string, optionally skipping specified characters.

If the characters to skip are not specified, a default of " \t\n" is used.

Returns null if the input string contains invalid characters or an uneven amount of hex digits.

Returns the decoded byte string on success.

Parameters:
NameTypeAttributesDescription
hexstringstring

The hexadecimal digit string to decode.

skipcharsstringoptional(optional)

The characters to skip during decoding.

Returns: string
Example
hexdec("48656c6c6f20776f726c64210a");  // "Hello world!\n"
+hexdec("44:55:66:77:33:44", ":");      // "DUfw3D"

hexenc(val) → {string}

Encodes the given byte string into a hexadecimal digit string, converting the input value to a string if needed.

Parameters:
NameTypeDescription
valstring

The byte string to encode.

Returns: string
Example
hexenc("Hello world!\n");   // "48656c6c6f20776f726c64210a"

include(path, scopeopt)

Evaluate and include the file at the given path and optionally override the execution scope with the given scope object.

By default, the file is executed within the same scope as the calling include(), but by passing an object as the second argument, it is possible to extend the scope available to the included file.

This is useful to supply additional properties as global variables to the included code. To sandbox included code, that is giving it only access to explicitly provided properties, the proto() function can be used to create a scope object with an empty prototype.

Parameters:
NameTypeAttributesDescription
pathstring

The path to the file to be included.

scopeObjectoptional(optional)

The optional scope object to override the execution scope.

Example
// Load and execute "foo.uc" immediately
 include("./foo.uc")
 
 // Execute the "supplemental.ucode" in an extended scope and make the "foo"
@@ -78,15 +78,15 @@
   foo: true,
   bar: 123,
   print: print
-}, {}))

index(arr_or_str, needle) → {number}nullable

Finds the given value passed as the second argument within the array or string specified in the first argument.

Returns the first matching array index or first matching string offset or -1 if the value was not found.

Returns null if the first argument was neither an array nor a string.

Parameters:
NameTypeDescription
arr_or_strArray | string

The array or string to search for the value.

needle*

The value to find within the array or string.

Returns: number
Example
index("Hello hello hello", "ll")          // 2
+}, {}))

index(arr_or_str, needle) → {number}nullable

Finds the given value passed as the second argument within the array or string specified in the first argument.

Returns the first matching array index or first matching string offset or -1 if the value was not found.

Returns null if the first argument was neither an array nor a string.

Parameters:
NameTypeDescription
arr_or_strArray | string

The array or string to search for the value.

needle*

The value to find within the array or string.

Returns: number
Example
index("Hello hello hello", "ll")          // 2
 index([ 1, 2, 3, 1, 2, 3, 1, 2, 3 ], 2)   // 1
 index("foo", "bar")                       // -1
 index(["Red", "Blue", "Green"], "Brown")  // -1
-index(123, 2)                             // null

int(x) → {number}

Converts the given value to an integer.

Returns NaN if the value is not convertible.

Parameters:
NameTypeDescription
x*

The value to be converted to an integer.

Returns: number

iptoarr(address) → {number[]}nullable

Convert the given IP address string to an array of byte values.

IPv4 addresses result in arrays of 4 integers while IPv6 ones in arrays containing 16 intergers. The resulting array can be turned back into IP address strings using the inverse arrtoip() function.

Returns an array containing the address byte values. Returns null if the given argument is not a string or an invalid IP.

Parameters:
NameTypeDescription
addressstring

The IP address string to convert.

Returns: number[]
Example
iptoarr("192.168.1.1")              // [ 192, 168, 1, 1 ]
+index(123, 2)                             // null

int(x) → {number}

Converts the given value to an integer.

Returns NaN if the value is not convertible.

Parameters:
NameTypeDescription
x*

The value to be converted to an integer.

Returns: number

iptoarr(address) → {number[]}nullable

Convert the given IP address string to an array of byte values.

IPv4 addresses result in arrays of 4 integers while IPv6 ones in arrays containing 16 intergers. The resulting array can be turned back into IP address strings using the inverse arrtoip() function.

Returns an array containing the address byte values. Returns null if the given argument is not a string or an invalid IP.

Parameters:
NameTypeDescription
addressstring

The IP address string to convert.

Returns: number[]
Example
iptoarr("192.168.1.1")              // [ 192, 168, 1, 1 ]
 iptoarr("fe80::fc54:ff:fe82:abbd")  // [ 254, 128, 0, 0, 0, 0, 0, 0, 252, 84,
                                     //   0, 255, 254, 130, 171, 189 ])
 iptoarr("foo")                      // null (invalid address)
-iptoarr(123)                        // null (not a string)

join(sep, arr) → {string}nullable

Joins the array passed as the second argument into a string, using the separator passed in the first argument as glue.

Returns null if the second argument is not an array.

Parameters:
NameTypeDescription
sepstring

The separator to be used in joining the array elements.

arrArray

The array to be joined into a string.

Returns: string

json(str_or_resource) → {*}

Parse the given string or resource as JSON and return the resulting value.

If the input argument is a plain string, it is directly parsed as JSON.

If an array, object or resource value is given, this function will attempt to invoke a read() method on it to read chunks of input text to incrementally parse as JSON data. Reading will stop if the object's read() method returns either null or an empty string.

Throws an exception on parse errors, trailing garbage, or premature EOF.

Returns the parsed JSON data.

Parameters:
NameTypeDescription
str_or_resourcestring

The string or resource object to be parsed as JSON.

Returns: *
Example
json('{"a":true, "b":123}')   // { "a": true, "b": 123 }
+iptoarr(123)                        // null (not a string)

join(sep, arr) → {string}nullable

Joins the array passed as the second argument into a string, using the separator passed in the first argument as glue.

Returns null if the second argument is not an array.

Parameters:
NameTypeDescription
sepstring

The separator to be used in joining the array elements.

arrArray

The array to be joined into a string.

Returns: string

json(str_or_resource) → {*}

Parse the given string or resource as JSON and return the resulting value.

If the input argument is a plain string, it is directly parsed as JSON.

If an array, object or resource value is given, this function will attempt to invoke a read() method on it to read chunks of input text to incrementally parse as JSON data. Reading will stop if the object's read() method returns either null or an empty string.

Throws an exception on parse errors, trailing garbage, or premature EOF.

Returns the parsed JSON data.

Parameters:
NameTypeDescription
str_or_resourcestring

The string or resource object to be parsed as JSON.

Returns: *
Example
json('{"a":true, "b":123}')   // { "a": true, "b": 123 }
 json('[1,2,')                 // Throws an exception
 
 import { open } from 'fs';
@@ -99,19 +99,19 @@
     { read: function() { return shift(this) } }
 );
 json(x);                      // will keep invoking `x.read()` until array
-                              // is empty incrementally parse each piece

keys(obj) → {Array}nullable

Enumerates all object key names.

Returns an array of all key names present in the passed object. Returns null if the given argument is not an object.

Parameters:
NameTypeDescription
objobject

The object from which to retrieve the key names.

Returns: Array

lc(s) → {string}nullable

Convert the given string to lowercase and return the resulting string.

Returns null if the given argument could not be converted to a string.

Parameters:
NameTypeDescription
sstring

The input string.

Returns: string

The lowercase string.

Example
lc("HeLLo WoRLd!");  // "hello world!"

length(x) → {number}nullable

Determine the length of the given object, array or string.

Returns the length of the given value.

  • For strings, the length is the amount of bytes within the string
  • For arrays, the length is the amount of array elements
  • For objects, the length is defined as the amount of keys

Returns null if the given argument is not an object, array or string.

Parameters:
NameTypeDescription
xObject | Array | string

The input object, array, or string.

Returns: number
  • The length of the input.
Example
length("test")                             // 4
+                              // is empty incrementally parse each piece

keys(obj) → {Array}nullable

Enumerates all object key names.

Returns an array of all key names present in the passed object. Returns null if the given argument is not an object.

Parameters:
NameTypeDescription
objobject

The object from which to retrieve the key names.

Returns: Array

lc(s) → {string}nullable

Convert the given string to lowercase and return the resulting string.

Returns null if the given argument could not be converted to a string.

Parameters:
NameTypeDescription
sstring

The input string.

Returns: string

The lowercase string.

Example
lc("HeLLo WoRLd!");  // "hello world!"

length(x) → {number}nullable

Determine the length of the given object, array or string.

Returns the length of the given value.

  • For strings, the length is the amount of bytes within the string
  • For arrays, the length is the amount of array elements
  • For objects, the length is defined as the amount of keys

Returns null if the given argument is not an object, array or string.

Parameters:
NameTypeDescription
xObject | Array | string

The input object, array, or string.

Returns: number
  • The length of the input.
Example
length("test")                             // 4
 length([true, false, null, 123, "test"])   // 5
 length({foo: true, bar: 123, baz: "test"}) // 3
 length({})                                 // 0
 length(true)                               // null
-length(10.0)                               // null

loadfile(path, optionsopt) → {function}

Compiles the given file into a ucode program and returns the resulting program entry function.

See loadstring() for details.

Returns the compiled program entry function.

Throws an exception on compilation or file I/O errors.

Parameters:
NameTypeAttributesDescription
pathstring

The path of the file to compile.

optionsParseConfigoptional(optional)

The options for compilation.

Returns: function
Example
loadfile("./templates/example.uc");  // function main() { ... }

loadstring(code, optionsopt) → {function}

Compiles the given code string into a ucode program and returns the resulting program entry function.

The optional options dictionary overrides parse and compile options.

  • If a non-string code argument is given, it is implicitly converted to a string value first.
  • If options is omitted or a non-object value, the compile options of the running ucode program are reused.

See ParseConfig for known keys within the options object. Unrecognized keys are ignored, unspecified options default to those of the running program.

Returns the compiled program entry function.

Throws an exception on compilation errors.

Parameters:
NameTypeAttributesDescription
codestring

The code string to compile.

optionsParseConfigoptional(optional)

The options for compilation.

Returns: function
Example
let fn1 = loadstring("Hello, {{ name }}", { raw_mode: false });
+length(10.0)                               // null

loadfile(path, optionsopt) → {function}

Compiles the given file into a ucode program and returns the resulting program entry function.

See loadstring() for details.

Returns the compiled program entry function.

Throws an exception on compilation or file I/O errors.

Parameters:
NameTypeAttributesDescription
pathstring

The path of the file to compile.

optionsParseConfigoptional(optional)

The options for compilation.

Returns: function
Example
loadfile("./templates/example.uc");  // function main() { ... }

loadstring(code, optionsopt) → {function}

Compiles the given code string into a ucode program and returns the resulting program entry function.

The optional options dictionary overrides parse and compile options.

  • If a non-string code argument is given, it is implicitly converted to a string value first.
  • If options is omitted or a non-object value, the compile options of the running ucode program are reused.

See ParseConfig for known keys within the options object. Unrecognized keys are ignored, unspecified options default to those of the running program.

Returns the compiled program entry function.

Throws an exception on compilation errors.

Parameters:
NameTypeAttributesDescription
codestring

The code string to compile.

optionsParseConfigoptional(optional)

The options for compilation.

Returns: function
Example
let fn1 = loadstring("Hello, {{ name }}", { raw_mode: false });
 
 global.name = "Alice";
 fn1(); // prints `Hello, Alice`
 
 
 let fn2 = loadstring("return 1 + 2;", { raw_mode: true });
-fn2(); // 3

localtime(epochopt) → {TimeSpec}

Return the given epoch timestamp (or now, if omitted) as a dictionary containing broken-down date and time information according to the local system timezone.

See TimeSpec for a description of the fields.

Note that in contrast to the underlying localtime(3) C library function, the values for mon, wday, and yday are 1-based, and the year is 1900-based.

Parameters:
NameTypeAttributesDescription
epochnumberoptional(optional)

The epoch timestamp.

Returns: TimeSpec
Example
localtime(1647953502);
+fn2(); // 3

localtime(epochopt) → {TimeSpec}

Return the given epoch timestamp (or now, if omitted) as a dictionary containing broken-down date and time information according to the local system timezone.

See TimeSpec for a description of the fields.

Note that in contrast to the underlying localtime(3) C library function, the values for mon, wday, and yday are 1-based, and the year is 1900-based.

Parameters:
NameTypeAttributesDescription
epochnumberoptional(optional)

The epoch timestamp.

Returns: TimeSpec
Example
localtime(1647953502);
 // Returns:
 // {
 //     sec: 42,
@@ -123,31 +123,31 @@
 //     wday: 2,
 //     yday: 81,
 //     isdst: 0
-// }

ltrim(s, copt) → {string}

Trim any of the specified characters from the start of the string. If the second argument is omitted, trims the characters (space), '\t', '\r', and '\n'.

Returns the left trimmed string.

Parameters:
NameTypeAttributesDescription
sstring

The input string.

cstringoptional(optional)

The characters to trim.

Returns: string
Example
ltrim("  foo  \n")     // "foo  \n"
-ltrim("--bar--", "-")  // "bar--"

map(arr, fn) → {Array}

Transform the array passed as the first argument by invoking the function specified in the second argument for each array item.

Returns a new array of the same length as the input array containing the transformed values.

Parameters:
NameTypeDescription
arrArray

The input array.

fnfunction

The mapping function.

Returns: Array
Example
// turn into an array of string lengths:
+// }

ltrim(s, copt) → {string}

Trim any of the specified characters from the start of the string. If the second argument is omitted, trims the characters (space), '\t', '\r', and '\n'.

Returns the left trimmed string.

Parameters:
NameTypeAttributesDescription
sstring

The input string.

cstringoptional(optional)

The characters to trim.

Returns: string
Example
ltrim("  foo  \n")     // "foo  \n"
+ltrim("--bar--", "-")  // "bar--"

map(arr, fn) → {Array}

Transform the array passed as the first argument by invoking the function specified in the second argument for each array item.

Returns a new array of the same length as the input array containing the transformed values.

Parameters:
NameTypeDescription
arrArray

The input array.

fnfunction

The mapping function.

Returns: Array
Example
// turn into an array of string lengths:
 a = map(["Apple", "Banana", "Bean"], length);
 // a = [5, 6, 4]
 
 // map to type names:
 a = map(["foo", 1, true, null, 2.2], type);
-// a = ["string", "int", "bool", null, "double"]

match(str, pattern) → {Array}nullable

Match the given string against the regular expression pattern specified as the second argument.

If the passed regular expression uses the g flag, the return value will be an array of arrays describing all found occurrences within the string.

Without the g modifier, an array describing the first match is returned.

Returns null if the pattern was not found within the given string.

Parameters:
NameTypeDescription
strstring

The string to be matched against the pattern.

patternRegExp

The regular expression pattern.

Returns: Array
Example
match("foobarbaz", /b.(.)/)   // ["bar", "r"]
-match("foobarbaz", /b.(.)/g)  // [["bar", "r"], ["baz", "z"]]

max(…valopt) → {*}

Return the largest value among all parameters passed to the function.

Parameters:
NameTypeAttributesDescription
val*optional, repeatable(optional, repeatable)

The values to compare.

Returns: *
Example
max(5, 2.1, 3, "abc", 0.3);            // Returns 5
+// a = ["string", "int", "bool", null, "double"]

match(str, pattern) → {Array}nullable

Match the given string against the regular expression pattern specified as the second argument.

If the passed regular expression uses the g flag, the return value will be an array of arrays describing all found occurrences within the string.

Without the g modifier, an array describing the first match is returned.

Returns null if the pattern was not found within the given string.

Parameters:
NameTypeDescription
strstring

The string to be matched against the pattern.

patternRegExp

The regular expression pattern.

Returns: Array
Example
match("foobarbaz", /b.(.)/)   // ["bar", "r"]
+match("foobarbaz", /b.(.)/g)  // [["bar", "r"], ["baz", "z"]]

max(…valopt) → {*}

Return the largest value among all parameters passed to the function.

Parameters:
NameTypeAttributesDescription
val*optional, repeatable(optional, repeatable)

The values to compare.

Returns: *
Example
max(5, 2.1, 3, "abc", 0.3);            // Returns 5
 max(1, "abc");                         // Returns 1 (!)
 max("1", "abc");                       // Returns "abc"
 max("def", "abc", "ghi");              // Returns "ghi"
-max(true, false);                      // Returns true

min(…valopt) → {*}

Return the smallest value among all parameters passed to the function.

Parameters:
NameTypeAttributesDescription
val*optional, repeatable(optional, repeatable)

The values to compare.

Returns: *
Example
min(5, 2.1, 3, "abc", 0.3);            // Returns 0.3
+max(true, false);                      // Returns true

min(…valopt) → {*}

Return the smallest value among all parameters passed to the function.

Parameters:
NameTypeAttributesDescription
val*optional, repeatable(optional, repeatable)

The values to compare.

Returns: *
Example
min(5, 2.1, 3, "abc", 0.3);            // Returns 0.3
 min(1, "abc");                         // Returns 1
 min("1", "abc");                       // Returns "1"
 min("def", "abc", "ghi");              // Returns "abc"
-min(true, false);                      // Returns false

ord(s, offsetopt) → {number}nullable

Without further arguments, this function returns the byte value of the first character in the given string.

If an offset argument is supplied, the byte value of the character at this position is returned. If an invalid index is supplied, the function will return null. Negative index entries are counted towards the end of the string, e.g. -2 will return the value of the second last character.

Returns the byte value of the character. Returns null if the offset is invalid or if the input is not a string.

Parameters:
NameTypeAttributesDescription
sstring

The input string.

offsetnumberoptional(optional)

The offset of the character.

Returns: number
Example
ord("Abc");         // 65
+min(true, false);                      // Returns false

ord(s, offsetopt) → {number}nullable

Without further arguments, this function returns the byte value of the first character in the given string.

If an offset argument is supplied, the byte value of the character at this position is returned. If an invalid index is supplied, the function will return null. Negative index entries are counted towards the end of the string, e.g. -2 will return the value of the second last character.

Returns the byte value of the character. Returns null if the offset is invalid or if the input is not a string.

Parameters:
NameTypeAttributesDescription
sstring

The input string.

offsetnumberoptional(optional)

The offset of the character.

Returns: number
Example
ord("Abc");         // 65
 ord("Abc", 0);      // 65
 ord("Abc", 1);      // 98
 ord("Abc", 2);      // 99
 ord("Abc", 10);     // null
 ord("Abc", -10);    // null
-ord("Abc", "nan");  // null

pop(arr) → {*}

Pops the first item from the given array and returns it.

Returns null if the array was empty or if a non-array argument was passed.

Parameters:
NameTypeDescription
arrArray

The input array.

Returns: *
Example
let x = [ 1, 2, 3 ];
+ord("Abc", "nan");  // null

pop(arr) → {*}

Pops the first item from the given array and returns it.

Returns null if the array was empty or if a non-array argument was passed.

Parameters:
NameTypeDescription
arrArray

The input array.

Returns: *
Example
let x = [ 1, 2, 3 ];
 pop(x);          // 3
-print(x, "\n");  // [ 1, 2 ]

print(…values) → {number}

Print any of the given values to stdout.

The print() function writes a string representation of each given argument to stdout and returns the amount of bytes written.

String values are printed as-is, integer and double values are printed in decimal notation, boolean values are printed as true or false while arrays and objects are converted to their JSON representation before being written to the standard output. The null value is represented by an empty string so print(null) would print nothing. Resource values are printed in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

If resource, array or object values contain a tostring() function in their prototypes, then this function is invoked to obtain an alternative string representation of the value.

Examples:

print(1 != 2);                       // Will print 'true'
+print(x, "\n");  // [ 1, 2 ]

print(…values) → {number}

Print any of the given values to stdout.

The print() function writes a string representation of each given argument to stdout and returns the amount of bytes written.

String values are printed as-is, integer and double values are printed in decimal notation, boolean values are printed as true or false while arrays and objects are converted to their JSON representation before being written to the standard output. The null value is represented by an empty string so print(null) would print nothing. Resource values are printed in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

If resource, array or object values contain a tostring() function in their prototypes, then this function is invoked to obtain an alternative string representation of the value.

Examples:

print(1 != 2);                       // Will print 'true'
 print(0xff);                         // Will print '255'
 print(2e3);                          // Will print '2000'
 print(null);                         // Will print nothing
@@ -178,26 +178,26 @@
   //   2,
   //   3
   // ]
-%}

proto(val, protoopt) → {Object}nullable

Get or set the prototype of the array or object value val.

When invoked without a second argument, the function returns the current prototype of the value in val or null if there is no prototype or if the given value is neither an object nor an array.

When invoked with a second prototype argument, the given proto value is set as the prototype on the array or object in val.

Throws an exception if the given prototype value is not an object.

Parameters:
NameTypeAttributesDescription
valArray | Object

The array or object value.

protoObjectoptional(optional)

The optional prototype object.

Returns: Object
Example
const arr = [1, 2, 3];
+%}

proto(val, protoopt) → {Object}nullable

Get or set the prototype of the array or object value val.

When invoked without a second argument, the function returns the current prototype of the value in val or null if there is no prototype or if the given value is neither an object nor an array.

When invoked with a second prototype argument, the given proto value is set as the prototype on the array or object in val.

Throws an exception if the given prototype value is not an object.

Parameters:
NameTypeAttributesDescription
valArray | Object

The array or object value.

protoObjectoptional(optional)

The optional prototype object.

Returns: Object
Example
const arr = [1, 2, 3];
 proto(arr);                 // Returns the current prototype of the array (null by default)
-proto(arr, { foo: true });  // Sets the given object as the prototype of the array

push(arr, …valuesopt) → {*}

Pushes the given argument(s) to the given array.

Returns the last pushed value.

Parameters:
NameTypeAttributesDescription
arrArray

The array to push values to.

values*optional, repeatable(optional, repeatable)

The values to push.

Returns: *
Example
let x = [ 1, 2, 3 ];
+proto(arr, { foo: true });  // Sets the given object as the prototype of the array

push(arr, …valuesopt) → {*}

Pushes the given argument(s) to the given array.

Returns the last pushed value.

Parameters:
NameTypeAttributesDescription
arrArray

The array to push values to.

values*optional, repeatable(optional, repeatable)

The values to push.

Returns: *
Example
let x = [ 1, 2, 3 ];
 push(x, 4, 5, 6);    // 6
-print(x, "\n");      // [ 1, 2, 3, 4, 5, 6 ]

regexp(source, flagsopt) → {RegExp}

Construct a regular expression instance from the given source pattern string and any flags optionally specified by the flags argument.

  • Throws a type error exception if flags is not a string or if the string in flags contains unrecognized regular expression flag characters.
  • Throws a syntax error when the pattern in source cannot be compiled into a valid regular expression.

Returns the compiled regular expression value.

Parameters:
NameTypeAttributesDescription
sourcestring

The pattern string.

flagsstringoptional(optional)

The optional regular expression flags.

Returns: RegExp
Example
regexp('foo.*bar', 'is');   // equivalent to /foo.*bar/is
+print(x, "\n");      // [ 1, 2, 3, 4, 5, 6 ]

regexp(source, flagsopt) → {RegExp}

Construct a regular expression instance from the given source pattern string and any flags optionally specified by the flags argument.

  • Throws a type error exception if flags is not a string or if the string in flags contains unrecognized regular expression flag characters.
  • Throws a syntax error when the pattern in source cannot be compiled into a valid regular expression.

Returns the compiled regular expression value.

Parameters:
NameTypeAttributesDescription
sourcestring

The pattern string.

flagsstringoptional(optional)

The optional regular expression flags.

Returns: RegExp
Example
regexp('foo.*bar', 'is');   // equivalent to /foo.*bar/is
 regexp('foo.*bar', 'x');    // throws a "Type error: Unrecognized flag character 'x'" exception
-regexp('foo.*(');           // throws a "Syntax error: Unmatched ( or \( exception"

render(path_or_func, scope_or_fnarg1opt, fnarg2opt, …fnargNopt) → {string}

When invoked with a string value as the first argument, the function acts like include() but captures the output of the included file as a string and returns the captured contents.

The second argument is treated as the scope.

When invoked with a function value as the first argument, render() calls the given function and passes all subsequent arguments to it.

Any output produced by the called function is captured and returned as a string. The return value of the called function is discarded.

Parameters:
NameTypeAttributesDescription
path_or_funcstring | function

The path to the file or the function to be rendered.

scope_or_fnarg1Object | *optional(optional)

The optional scope or the first argument for the function.

fnarg2*optional(optional)

The second argument for the function.

fnargN*optional, repeatable(optional, repeatable)

Additional arguments for the function.

Returns: string
Example
// Renders template file with given scope and captures the output as a string
+regexp('foo.*(');           // throws a "Syntax error: Unmatched ( or \( exception"

render(path_or_func, scope_or_fnarg1opt, fnarg2opt, …fnargNopt) → {string}

When invoked with a string value as the first argument, the function acts like include() but captures the output of the included file as a string and returns the captured contents.

The second argument is treated as the scope.

When invoked with a function value as the first argument, render() calls the given function and passes all subsequent arguments to it.

Any output produced by the called function is captured and returned as a string. The return value of the called function is discarded.

Parameters:
NameTypeAttributesDescription
path_or_funcstring | function

The path to the file or the function to be rendered.

scope_or_fnarg1Object | *optional(optional)

The optional scope or the first argument for the function.

fnarg2*optional(optional)

The second argument for the function.

fnargN*optional, repeatable(optional, repeatable)

Additional arguments for the function.

Returns: string
Example
// Renders template file with given scope and captures the output as a string
 const output = render("./template.uc", { foo: "bar" });
 
 // Calls a function, captures the output, and returns it as a string
 const result = render(function(name) {
     printf("Hello, %s!\n", name);
-}, "Alice");

replace(str, pattern, replace, limitopt) → {string}

Replace occurrences of the specified pattern in the string passed as the first argument.

  • The pattern value may be either a regular expression or a plain string.
  • The replace value may be a function which is invoked for each found pattern or any other value which is converted into a plain string and used as replacement.
  • When an optional limit is specified, substitutions are performed only that many times.
  • If the pattern is a regular expression and not using the g flag, then only the first occurrence in the string is replaced.
  • If the g flag is used or if the pattern is not a regular expression, all occurrences are replaced.
  • If the replace value is a callback function, it is invoked with the found substring as the first and any capture group values as subsequent parameters.
  • If the replace value is a string, specific substrings are substituted before it is inserted into the result.

Returns a new string with the pattern replaced.

Parameters:
NameTypeAttributesDescription
strstring

The string in which to replace occurrences.

patternRegExp | string

The pattern to be replaced.

replacefunction | string

The replacement value.

limitnumberoptional(optional)

The optional limit of substitutions.

Returns: string
Example
replace("barfoobaz", /(f)(o+)/g, "[$$|$`|$&|$'|$1|$2|$3]")  // bar[$|bar|foo|baz|f|oo|$3]baz
+}, "Alice");

replace(str, pattern, replace, limitopt) → {string}

Replace occurrences of the specified pattern in the string passed as the first argument.

  • The pattern value may be either a regular expression or a plain string.
  • The replace value may be a function which is invoked for each found pattern or any other value which is converted into a plain string and used as replacement.
  • When an optional limit is specified, substitutions are performed only that many times.
  • If the pattern is a regular expression and not using the g flag, then only the first occurrence in the string is replaced.
  • If the g flag is used or if the pattern is not a regular expression, all occurrences are replaced.
  • If the replace value is a callback function, it is invoked with the found substring as the first and any capture group values as subsequent parameters.
  • If the replace value is a string, specific substrings are substituted before it is inserted into the result.

Returns a new string with the pattern replaced.

Parameters:
NameTypeAttributesDescription
strstring

The string in which to replace occurrences.

patternRegExp | string

The pattern to be replaced.

replacefunction | string

The replacement value.

limitnumberoptional(optional)

The optional limit of substitutions.

Returns: string
Example
replace("barfoobaz", /(f)(o+)/g, "[$$|$`|$&|$'|$1|$2|$3]")  // bar[$|bar|foo|baz|f|oo|$3]baz
 replace("barfoobaz", /(f)(o+)/g, uc)                        // barFOObaz
 replace("barfoobaz", "a", "X")                              // bXrfoobXz
 replace("barfoobaz", /(.)(.)(.)/g, function(m, c1, c2, c3) {
     return c3 + c2 + c1;
 })                                                          // raboofzab
 replace("aaaaa", "a", "x", 3)                               // xxxaa
-replace("foo bar baz", /[ao]/g, "x", 3)                     // fxx bxr baz

require(name) → {*}

Load and evaluate ucode scripts or shared library extensions.

The require() function expands each member of the global REQUIRE_SEARCH_PATH array to a filesystem path by replacing the * placeholder with a slash-separated version of the given dotted module name and subsequently tries to load a file at the resulting location.

If a file is found at one of the search path locations, it is compiled and evaluated or loaded via the C runtime's dlopen() function, depending on whether the found file is a ucode script or a compiled dynamic library.

The resulting program function of the compiled/loaded module is then subsequently executed with the current global environment, without a this context and without arguments.

Finally, the return value of the invoked program function is returned back by require() to the caller.

By default, modules are cached in the global modules dictionary and subsequent attempts to require the same module will return the cached module dictionary entry without re-evaluating the module.

To force reloading a module, the corresponding entry from the global modules dictionary can be deleted.

To preload a module or to provide a "virtual" module without a corresponding filesystem resource, an entry can be manually added to the global modules dictionary.

Summarized, the require() function can be roughly described by the following code:

function require(name) {
+replace("foo bar baz", /[ao]/g, "x", 3)                     // fxx bxr baz

require(name) → {*}

Load and evaluate ucode scripts or shared library extensions.

The require() function expands each member of the global REQUIRE_SEARCH_PATH array to a filesystem path by replacing the * placeholder with a slash-separated version of the given dotted module name and subsequently tries to load a file at the resulting location.

If a file is found at one of the search path locations, it is compiled and evaluated or loaded via the C runtime's dlopen() function, depending on whether the found file is a ucode script or a compiled dynamic library.

The resulting program function of the compiled/loaded module is then subsequently executed with the current global environment, without a this context and without arguments.

Finally, the return value of the invoked program function is returned back by require() to the caller.

By default, modules are cached in the global modules dictionary and subsequent attempts to require the same module will return the cached module dictionary entry without re-evaluating the module.

To force reloading a module, the corresponding entry from the global modules dictionary can be deleted.

To preload a module or to provide a "virtual" module without a corresponding filesystem resource, an entry can be manually added to the global modules dictionary.

Summarized, the require() function can be roughly described by the following code:

function require(name) {
     if (exists(modules, name))
         return modules[name];
 
@@ -233,15 +233,15 @@
 };
 
 const test = require('example.test');
-test.hello();  // will print "This is the example module"

reverse(arr_or_str) → {Array|string}nullable

Reverse the order of the given input array or string.

If an array is passed, returns the array in reverse order. If a string is passed, returns the string with the sequence of the characters reversed.

Returns the reversed array or string. Returns null if neither an array nor a string were passed.

Parameters:
NameTypeDescription
arr_or_strArray | string

The input array or string.

Returns: Array | string
Example
reverse([1, 2, 3]);   // [ 3, 2, 1 ]
-reverse("Abc");       // "cbA"

rindex(arr_or_str, needle) → {number}nullable

Finds the given value passed as the second argument within the array or string specified in the first argument.

Returns the last matching array index or last matching string offset or -1 if the value was not found.

Returns null if the first argument was neither an array nor a string.

Parameters:
NameTypeDescription
arr_or_strArray | string

The array or string to search for the value.

needle*

The value to find within the array or string.

Returns: number
Example
rindex("Hello hello hello", "ll")          // 14
+test.hello();  // will print "This is the example module"

reverse(arr_or_str) → {Array|string}nullable

Reverse the order of the given input array or string.

If an array is passed, returns the array in reverse order. If a string is passed, returns the string with the sequence of the characters reversed.

Returns the reversed array or string. Returns null if neither an array nor a string were passed.

Parameters:
NameTypeDescription
arr_or_strArray | string

The input array or string.

Returns: Array | string
Example
reverse([1, 2, 3]);   // [ 3, 2, 1 ]
+reverse("Abc");       // "cbA"

rindex(arr_or_str, needle) → {number}nullable

Finds the given value passed as the second argument within the array or string specified in the first argument.

Returns the last matching array index or last matching string offset or -1 if the value was not found.

Returns null if the first argument was neither an array nor a string.

Parameters:
NameTypeDescription
arr_or_strArray | string

The array or string to search for the value.

needle*

The value to find within the array or string.

Returns: number
Example
rindex("Hello hello hello", "ll")          // 14
 rindex([ 1, 2, 3, 1, 2, 3, 1, 2, 3 ], 2)   //  7
 rindex("foo", "bar")                       // -1
 rindex(["Red", "Blue", "Green"], "Brown")  // -1
-rindex(123, 2)                             // null

rtrim(str, copt) → {string}

Trim any of the specified characters from the end of the string. If the second argument is omitted, trims the characters (space), '\t', '\r', and '\n'.

Returns the right trimmed string.

Parameters:
NameTypeAttributesDescription
strstring

The input string.

cstringoptional(optional)

The characters to trim.

Returns: string
Example
rtrim("  foo  \n")     // "  foo"
-rtrim("--bar--", "-")  // "--bar"

shift(arr) → {*}

Pops the first item from the given array and returns it.

Returns null if the array was empty or if a non-array argument was passed.

Parameters:
NameTypeDescription
arrArray

The array from which to pop the first item.

Returns: *
Example
let x = [ 1, 2, 3 ];
+rindex(123, 2)                             // null

rtrim(str, copt) → {string}

Trim any of the specified characters from the end of the string. If the second argument is omitted, trims the characters (space), '\t', '\r', and '\n'.

Returns the right trimmed string.

Parameters:
NameTypeAttributesDescription
strstring

The input string.

cstringoptional(optional)

The characters to trim.

Returns: string
Example
rtrim("  foo  \n")     // "  foo"
+rtrim("--bar--", "-")  // "--bar"

shift(arr) → {*}

Pops the first item from the given array and returns it.

Returns null if the array was empty or if a non-array argument was passed.

Parameters:
NameTypeDescription
arrArray

The array from which to pop the first item.

Returns: *
Example
let x = [ 1, 2, 3 ];
 shift(x);        // 1
-print(x, "\n");  // [ 2, 3 ]

signal(signal, handleropt) → {function|string}

Set or query process signal handler function.

When invoked with two arguments, a signal specification and a signal handler value, this function configures a new process signal handler.

When invoked with one argument, a signal specification, this function returns the currently configured handler for the given signal.

The signal specification might either be an integer signal number or a string value containing a signal name (with or without "SIG" prefix). Signal names are treated case-insensitively.

The signal handler might be either a callable function value or one of the two special string values "ignore" and "default". Passing "ignore" will mask the given process signal while "default" will restore the operating systems default behaviour for the given signal.

In case a callable handler function is provided, it is invoked at the earliest opportunity after receiving the corresponding signal from the operating system. The invoked function will receive a single argument, the number of the signal it is invoked for.

Note that within the ucode VM, process signals are not immediately delivered, instead the VM keeps track of received signals and delivers them to the ucode script environment at the next opportunity, usually before executing the next byte code instruction. This means that if a signal is received while performing a computationally expensive operation in C mode, such as a complex regexp match, the corresponding ucode signal handler will only be invoked after that operation concluded and control flow returns to the VM.

Returns the signal handler function or one of the special values "ignore" or "default" corresponding to the given signal specification.

Returns null if an invalid signal spec or signal handler was provided.

Returns null if changing the signal action failed, e.g. due to insufficient permission, or when attempting to ignore a non-ignorable signal.

Parameters:
NameTypeAttributesDescription
signalnumber | string

The signal to query/set handler for.

handlerfunction | stringoptional(optional)

The signal handler to install for the given signal.

Returns: function | string
Example
// Ignore signals
+print(x, "\n");  // [ 2, 3 ]

signal(signal, handleropt) → {function|string}

Set or query process signal handler function.

When invoked with two arguments, a signal specification and a signal handler value, this function configures a new process signal handler.

When invoked with one argument, a signal specification, this function returns the currently configured handler for the given signal.

The signal specification might either be an integer signal number or a string value containing a signal name (with or without "SIG" prefix). Signal names are treated case-insensitively.

The signal handler might be either a callable function value or one of the two special string values "ignore" and "default". Passing "ignore" will mask the given process signal while "default" will restore the operating systems default behaviour for the given signal.

In case a callable handler function is provided, it is invoked at the earliest opportunity after receiving the corresponding signal from the operating system. The invoked function will receive a single argument, the number of the signal it is invoked for.

Note that within the ucode VM, process signals are not immediately delivered, instead the VM keeps track of received signals and delivers them to the ucode script environment at the next opportunity, usually before executing the next byte code instruction. This means that if a signal is received while performing a computationally expensive operation in C mode, such as a complex regexp match, the corresponding ucode signal handler will only be invoked after that operation concluded and control flow returns to the VM.

Returns the signal handler function or one of the special values "ignore" or "default" corresponding to the given signal specification.

Returns null if an invalid signal spec or signal handler was provided.

Returns null if changing the signal action failed, e.g. due to insufficient permission, or when attempting to ignore a non-ignorable signal.

Parameters:
NameTypeAttributesDescription
signalnumber | string

The signal to query/set handler for.

handlerfunction | stringoptional(optional)

The signal handler to install for the given signal.

Returns: function | string
Example
// Ignore signals
 signal('INT', 'ignore');      // "ignore"
 signal('SIGINT', 'ignore');   // "ignore" (equivalent to 'INT')
 signal('sigterm', 'ignore');  // "ignore" (signal names are case insensitive)
@@ -259,33 +259,33 @@
 }
 
 signal('SIGINT', intexit);    // returns intexit
-signal('SIGINT') == intexit;  // true

sleep(milliseconds) → {boolean}

Pause execution for the given amount of milliseconds.

Parameters:
NameTypeDescription
millisecondsnumber

The amount of milliseconds to sleep.

Returns: boolean
Example
sleep(1000);                          // Sleeps for 1 second

slice(arr, offopt, endopt) → {Array}

Performs a shallow copy of a portion of the source array, as specified by the start and end offsets. The original array is not modified.

Returns a new array containing the copied elements, if any. Returns null if the given source argument is not an array value.

Parameters:
NameTypeAttributesDescription
arrArray

The source array to be copied.

offnumberoptional(optional)

The index of the first element to copy.

endnumberoptional(optional)

The index of the first element to exclude from the returned array.

Returns: Array
Example
slice([1, 2, 3])          // [1, 2, 3]
+signal('SIGINT') == intexit;  // true

sleep(milliseconds) → {boolean}

Pause execution for the given amount of milliseconds.

Parameters:
NameTypeDescription
millisecondsnumber

The amount of milliseconds to sleep.

Returns: boolean
Example
sleep(1000);                          // Sleeps for 1 second

slice(arr, offopt, endopt) → {Array}

Performs a shallow copy of a portion of the source array, as specified by the start and end offsets. The original array is not modified.

Returns a new array containing the copied elements, if any. Returns null if the given source argument is not an array value.

Parameters:
NameTypeAttributesDescription
arrArray

The source array to be copied.

offnumberoptional(optional)

The index of the first element to copy.

endnumberoptional(optional)

The index of the first element to exclude from the returned array.

Returns: Array
Example
slice([1, 2, 3])          // [1, 2, 3]
 slice([1, 2, 3], 1)       // [2, 3]
 slice([1, 2, 3], -1)      // [3]
 slice([1, 2, 3], -3, -1)  // [1, 2]
 slice([1, 2, 3], 10)      // []
 slice([1, 2, 3], 2, 1)    // []
-slice("invalid", 1, 2)    // null

sort(arr, fnopt) → {Array}

Sort the given array according to the given sort function. If no sort function is provided, a default ascending sort order is applied.

The input array is sorted in-place, no copy is made.

The custom sort function is repeatedly called until the entire array is sorted. It will receive two values as arguments and should return a value lower than, larger than or equal to zero depending on whether the first argument is smaller, larger or equal to the second argument respectively.

Returns the sorted input array.

Parameters:
NameTypeAttributesDescription
arrArray

The input array to be sorted.

fnfunctionoptional(optional)

The sort function.

Returns: Array
Example
sort([8, 1, 5, 9]) // [1, 5, 8, 9]
+slice("invalid", 1, 2)    // null

sort(arr, fnopt) → {Array}

Sort the given array according to the given sort function. If no sort function is provided, a default ascending sort order is applied.

The input array is sorted in-place, no copy is made.

The custom sort function is repeatedly called until the entire array is sorted. It will receive two values as arguments and should return a value lower than, larger than or equal to zero depending on whether the first argument is smaller, larger or equal to the second argument respectively.

Returns the sorted input array.

Parameters:
NameTypeAttributesDescription
arrArray

The input array to be sorted.

fnfunctionoptional(optional)

The sort function.

Returns: Array
Example
sort([8, 1, 5, 9]) // [1, 5, 8, 9]
 sort(["Bean", "Orange", "Apple"], function(a, b) {
    return length(a) - length(b);
-}) // ["Bean", "Apple", "Orange"]

sourcepath(depthopt, dironlyopt) → {string}nullable

Determine the path of the source file currently being executed by ucode.

Parameters:
NameTypeAttributesDefaultDescription
depthnumberoptional0(optional, default: 0)

The depth to walk up the call stack.

dironlybooleanoptional(optional)

Whether to return only the directory portion of the source file path.

Returns: string
Example
sourcepath();         // Returns the path of the currently executed file
+}) // ["Bean", "Apple", "Orange"]

sourcepath(depthopt, dironlyopt) → {string}nullable

Determine the path of the source file currently being executed by ucode.

Parameters:
NameTypeAttributesDefaultDescription
depthnumberoptional0(optional, default: 0)

The depth to walk up the call stack.

dironlybooleanoptional(optional)

Whether to return only the directory portion of the source file path.

Returns: string
Example
sourcepath();         // Returns the path of the currently executed file
 sourcepath(1);        // Returns the path of the parent source file
-sourcepath(2, true);  // Returns the directory portion of the grandparent source file path

splice(arr, off, lenopt, …elementsopt) → {*}

Removes the elements designated by off and len from the given array, and replaces them with the additional arguments passed, if any.

The array grows or shrinks as necessary.

Returns the modified input array.

Parameters:
NameTypeAttributesDescription
arrArray

The input array to be modified.

offnumber

The index to start removing elements.

lennumberoptional(optional)

The number of elements to remove.

elements*optional, repeatable(optional, repeatable)

The elements to insert.

Returns: *
Example
let x = [ 1, 2, 3, 4 ];
+sourcepath(2, true);  // Returns the directory portion of the grandparent source file path

splice(arr, off, lenopt, …elementsopt) → {*}

Removes the elements designated by off and len from the given array, and replaces them with the additional arguments passed, if any.

The array grows or shrinks as necessary.

Returns the modified input array.

Parameters:
NameTypeAttributesDescription
arrArray

The input array to be modified.

offnumber

The index to start removing elements.

lennumberoptional(optional)

The number of elements to remove.

elements*optional, repeatable(optional, repeatable)

The elements to insert.

Returns: *
Example
let x = [ 1, 2, 3, 4 ];
 splice(x, 1, 2, "a", "b", "c");  // [ 1, "a", "b", "c", 4 ]
-print(x, "\n");                  // [ 1, "a", "b", "c", 4 ]

split(str, sep, limitopt) → {Array}

Split the given string using the separator passed as the second argument and return an array containing the resulting pieces.

If a limit argument is supplied, the resulting array contains no more than the given amount of entries, that means the string is split at most limit - 1 times total.

The separator may either be a plain string or a regular expression.

Returns a new array containing the resulting pieces.

Parameters:
NameTypeAttributesDescription
strstring

The input string to be split.

sepstring | RegExp

The separator.

limitnumberoptional(optional)

The limit on the number of splits.

Returns: Array
Example
split("foo,bar,baz", ",")     // ["foo", "bar", "baz"]
+print(x, "\n");                  // [ 1, "a", "b", "c", 4 ]

split(str, sep, limitopt) → {Array}

Split the given string using the separator passed as the second argument and return an array containing the resulting pieces.

If a limit argument is supplied, the resulting array contains no more than the given amount of entries, that means the string is split at most limit - 1 times total.

The separator may either be a plain string or a regular expression.

Returns a new array containing the resulting pieces.

Parameters:
NameTypeAttributesDescription
strstring

The input string to be split.

sepstring | RegExp

The separator.

limitnumberoptional(optional)

The limit on the number of splits.

Returns: Array
Example
split("foo,bar,baz", ",")     // ["foo", "bar", "baz"]
 split("foobar", "")           // ["f", "o", "o", "b", "a", "r"]
 split("foo,bar,baz", /[ao]/)  // ["f", "", ",b", "r,b", "z"]
-split("foo=bar=baz", "=", 2)  // ["foo", "bar=baz"]

sprintf(fmt, …Arguments) → {string}

Formats the given arguments according to the given format string.

See printf() for details.

Returns the formatted string.

Parameters:
NameTypeAttributesDescription
fmtstring

The format string.

Arguments*repeatable(repeatable)

to be formatted.

Returns: string
Example
sprintf("Hello %s", "world");    // "Hello world"
+split("foo=bar=baz", "=", 2)  // ["foo", "bar=baz"]

sprintf(fmt, …Arguments) → {string}

Formats the given arguments according to the given format string.

See printf() for details.

Returns the formatted string.

Parameters:
NameTypeAttributesDescription
fmtstring

The format string.

Arguments*repeatable(repeatable)

to be formatted.

Returns: string
Example
sprintf("Hello %s", "world");    // "Hello world"
 sprintf("%08x", 123);            // "0000007b"
 sprintf("%c%c%c", 65, 98, 99);   // "Abc"
 sprintf("%g", 10 / 3.0);         // "3.33333"
 sprintf("%2$d %1$d", 12, 34);    // "34 12"
-sprintf("%J", [1,2,3]);          // "[1,2,3]"

substr(str, off, lenopt) → {string}

Extracts a substring out of str and returns it. First character is at offset zero.

  • If off is negative, starts that far back from the end of the string.
  • If len is omitted, returns everything through the end of the string.
  • If len is negative, leaves that many characters off the string end.

Returns the extracted substring.

Parameters:
NameTypeAttributesDescription
strstring

The input string.

offnumber

The starting offset.

lennumberoptional(optional)

The length of the substring.

Returns: string
Example
s = "The black cat climbed the green tree";
+sprintf("%J", [1,2,3]);          // "[1,2,3]"

substr(str, off, lenopt) → {string}

Extracts a substring out of str and returns it. First character is at offset zero.

  • If off is negative, starts that far back from the end of the string.
  • If len is omitted, returns everything through the end of the string.
  • If len is negative, leaves that many characters off the string end.

Returns the extracted substring.

Parameters:
NameTypeAttributesDescription
strstring

The input string.

offnumber

The starting offset.

lennumberoptional(optional)

The length of the substring.

Returns: string
Example
s = "The black cat climbed the green tree";
 substr(s, 4, 5);      // black
 substr(s, 4, -11);    // black cat climbed the
 substr(s, 14);        // climbed the green tree
 substr(s, -4);        // tree
-substr(s, -4, 2);     // tr

system(command, timeoutopt) → {number}

Executes the given command, waits for completion, and returns the resulting exit code.

The command argument may be either a string, in which case it is passed to /bin/sh -c, or an array, which is directly converted into an execv() argument vector.

  • If the program terminated normally, a positive integer holding the program's exit() code is returned.
  • If the program was terminated by an uncaught signal, a negative signal number is returned.
  • If the optional timeout argument is specified, the program is terminated by SIGKILL after that many milliseconds if it doesn't complete within the timeout.

Omitting the timeout argument or passing 0 disables the command timeout.

Returns the program exit code.

Parameters:
NameTypeAttributesDescription
commandstring | Array

The command to be executed.

timeoutnumberoptional(optional)

The optional timeout in milliseconds.

Returns: number
Example
// Execute through `/bin/sh`
+substr(s, -4, 2);     // tr

system(command, timeoutopt) → {number}

Executes the given command, waits for completion, and returns the resulting exit code.

The command argument may be either a string, in which case it is passed to /bin/sh -c, or an array, which is directly converted into an execv() argument vector.

  • If the program terminated normally, a positive integer holding the program's exit() code is returned.
  • If the program was terminated by an uncaught signal, a negative signal number is returned.
  • If the optional timeout argument is specified, the program is terminated by SIGKILL after that many milliseconds if it doesn't complete within the timeout.

Omitting the timeout argument or passing 0 disables the command timeout.

Returns the program exit code.

Parameters:
NameTypeAttributesDescription
commandstring | Array

The command to be executed.

timeoutnumberoptional(optional)

The optional timeout in milliseconds.

Returns: number
Example
// Execute through `/bin/sh`
 // prints "Hello world" to stdout and returns 3
 system("echo 'Hello world' && exit 3");
 
@@ -295,15 +295,15 @@
 
 // Apply a timeout
 // returns -9
-system("sleep 3 && echo 'Success'", 1000);

time() → {number}

Returns the current UNIX epoch.

Returns: number
Example
time();     // 1598043054

timegm(datetimespec) → {number}nullable

Like timelocal() but interpreting the given date time specification as UTC time.

See timelocal() for details.

Parameters:
NameTypeDescription
datetimespecTimeSpec

The broken-down date and time dictionary.

Returns: number
Example
timegm({ "sec": 42, "min": 51, "hour": 13, "mday": 22, "mon": 3, "year": 2022, "isdst": 0 });
-// Returns 1647953502

timelocal(datetimespec) → {number}nullable

Performs the inverse operation of localtime() by taking a broken-down date and time dictionary and transforming it into an epoch value according to the local system timezone.

The wday and yday fields of the given date time specification are ignored. Field values outside of their valid range are internally normalized, e.g. October 40th is interpreted as November 9th.

Returns the resulting epoch value or null if the input date time dictionary was invalid or if the date time specification cannot be represented as epoch value.

Parameters:
NameTypeDescription
datetimespecTimeSpec

The broken-down date and time dictionary.

Returns: number
Example
timelocal({ "sec": 42, "min": 51, "hour": 13, "mday": 22, "mon": 3, "year": 2022, "isdst": 0 });
-// Returns 1647953502

trace(level)

Enables or disables VM opcode tracing.

When invoked with a positive non-zero level, opcode tracing is enabled and debug information is printed to stderr as the program is executed.

Invoking trace() with zero as an argument turns off opcode tracing.

Parameters:
NameTypeDescription
levelnumber

The level of tracing to enable.

Example
trace(1);   // Enables opcode tracing
-trace(0);   // Disables opcode tracing

trim(str, copt) → {string}

Trim any of the specified characters in c from the start and end of str. If the second argument is omitted, trims the characters, (space), \t, \r, and \n.

Returns the trimmed string.

Parameters:
NameTypeAttributesDescription
strstring

The string to be trimmed.

cstringoptional(optional)

The characters to be trimmed from the start and end of the string.

Returns: string

type(x) → {string}nullable

Query the type of the given value.

Returns the type of the given value as a string which might be one of "function", "object", "array", "double", "int", or "bool".

Returns null when no value or null is passed.

Parameters:
NameTypeDescription
x*

The value to determine the type of.

Returns: string

uc(str) → {string}nullable

Converts the given string to uppercase and returns the resulting string.

Returns null if the given argument could not be converted to a string.

Parameters:
NameTypeDescription
str*

The string to be converted to uppercase.

Returns: string
Example
uc("hello");   // "HELLO"
-uc(123);       // null

uchr(…Numeric) → {string}

Converts each given numeric value to an UTF-8 multibyte sequence and returns the resulting string.

Invalid numeric values or values outside the range 0..0x10FFFF are represented by the unicode replacement character 0xFFFD.

Returns a new UTF-8 encoded string consisting of unicode characters corresponding to the given numeric codepoints.

Parameters:
NameTypeAttributesDescription
Numericnumberrepeatable(repeatable)

values to convert.

Returns: string
Example
uchr(0x2600, 0x26C6, 0x2601);  // "☀⛆☁"
-uchr(-1, 0x20ffff, "foo");     // "���"

uniq(array) → {Array}nullable

Returns a new array containing all unique values of the given input array.

  • The order is preserved, and subsequent duplicate values are skipped.
  • If a non-array argument is given, the function returns null.
Parameters:
NameTypeDescription
arrayArray

The input array.

Returns: Array
Example
uniq([1, true, "foo", 2, true, "bar", "foo"]);       // Returns [1, true, "foo", 2, "bar"]
-uniq("test");                                        // Returns null

unshift(arr, …Values) → {*}

Add the given values to the beginning of the array passed via first argument.

Returns the last value added to the array.

Parameters:
NameTypeAttributesDescription
arrArray

The array to which the values will be added.

Values*repeatable(repeatable)

to add.

Returns: *
Example
let x = [ 3, 4, 5 ];
+system("sleep 3 && echo 'Success'", 1000);

time() → {number}

Returns the current UNIX epoch.

Returns: number
Example
time();     // 1598043054

timegm(datetimespec) → {number}nullable

Like timelocal() but interpreting the given date time specification as UTC time.

See timelocal() for details.

Parameters:
NameTypeDescription
datetimespecTimeSpec

The broken-down date and time dictionary.

Returns: number
Example
timegm({ "sec": 42, "min": 51, "hour": 13, "mday": 22, "mon": 3, "year": 2022, "isdst": 0 });
+// Returns 1647953502

timelocal(datetimespec) → {number}nullable

Performs the inverse operation of localtime() by taking a broken-down date and time dictionary and transforming it into an epoch value according to the local system timezone.

The wday and yday fields of the given date time specification are ignored. Field values outside of their valid range are internally normalized, e.g. October 40th is interpreted as November 9th.

Returns the resulting epoch value or null if the input date time dictionary was invalid or if the date time specification cannot be represented as epoch value.

Parameters:
NameTypeDescription
datetimespecTimeSpec

The broken-down date and time dictionary.

Returns: number
Example
timelocal({ "sec": 42, "min": 51, "hour": 13, "mday": 22, "mon": 3, "year": 2022, "isdst": 0 });
+// Returns 1647953502

trace(level)

Enables or disables VM opcode tracing.

When invoked with a positive non-zero level, opcode tracing is enabled and debug information is printed to stderr as the program is executed.

Invoking trace() with zero as an argument turns off opcode tracing.

Parameters:
NameTypeDescription
levelnumber

The level of tracing to enable.

Example
trace(1);   // Enables opcode tracing
+trace(0);   // Disables opcode tracing

trim(str, copt) → {string}

Trim any of the specified characters in c from the start and end of str. If the second argument is omitted, trims the characters, (space), \t, \r, and \n.

Returns the trimmed string.

Parameters:
NameTypeAttributesDescription
strstring

The string to be trimmed.

cstringoptional(optional)

The characters to be trimmed from the start and end of the string.

Returns: string

type(x) → {string}nullable

Query the type of the given value.

Returns the type of the given value as a string which might be one of "function", "object", "array", "double", "int", or "bool".

Returns null when no value or null is passed.

Parameters:
NameTypeDescription
x*

The value to determine the type of.

Returns: string

uc(str) → {string}nullable

Converts the given string to uppercase and returns the resulting string.

Returns null if the given argument could not be converted to a string.

Parameters:
NameTypeDescription
str*

The string to be converted to uppercase.

Returns: string
Example
uc("hello");   // "HELLO"
+uc(123);       // null

uchr(…Numeric) → {string}

Converts each given numeric value to an UTF-8 multibyte sequence and returns the resulting string.

Invalid numeric values or values outside the range 0..0x10FFFF are represented by the unicode replacement character 0xFFFD.

Returns a new UTF-8 encoded string consisting of unicode characters corresponding to the given numeric codepoints.

Parameters:
NameTypeAttributesDescription
Numericnumberrepeatable(repeatable)

values to convert.

Returns: string
Example
uchr(0x2600, 0x26C6, 0x2601);  // "☀⛆☁"
+uchr(-1, 0x20ffff, "foo");     // "���"

uniq(array) → {Array}nullable

Returns a new array containing all unique values of the given input array.

  • The order is preserved, and subsequent duplicate values are skipped.
  • If a non-array argument is given, the function returns null.
Parameters:
NameTypeDescription
arrayArray

The input array.

Returns: Array
Example
uniq([1, true, "foo", 2, true, "bar", "foo"]);       // Returns [1, true, "foo", 2, "bar"]
+uniq("test");                                        // Returns null

unshift(arr, …Values) → {*}

Add the given values to the beginning of the array passed via first argument.

Returns the last value added to the array.

Parameters:
NameTypeAttributesDescription
arrArray

The array to which the values will be added.

Values*repeatable(repeatable)

to add.

Returns: *
Example
let x = [ 3, 4, 5 ];
 unshift(x, 1, 2);  // 2
-print(x, "\n");    // [ 1, 2, 3, 4, 5 ]

values(obj) → {Array}nullable

Returns an array containing all values of the given object.

Returns null if no object was passed.

Parameters:
NameTypeDescription
obj*

The object from which to extract values.

Returns: Array
Example
values({ foo: true, bar: false });   // [true, false]

warn(…x) → {number}

Print any of the given values to stderr. Arrays and objects are converted to their JSON representation.

Returns the amount of bytes printed.

Parameters:
NameTypeAttributesDescription
x*repeatable(repeatable)

The values to be printed.

Returns: number
Example
warn("Hello", "world");  // Print "Helloworld" to stderr
-warn({ key: "value" });  // Print JSON representation of the object to stderr

wildcard(subject, pattern, nocaseopt) → {boolean}

Match the given subject against the supplied wildcard (file glob) pattern.

  • If a truthy value is supplied as the third argument, case-insensitive matching is performed.
  • If a non-string value is supplied as the subject, it is converted into a string before being matched.

Returns true when the value matched the given pattern, otherwise false.

Parameters:
NameTypeAttributesDescription
subject*

The subject to match against the wildcard pattern.

patternstring

The wildcard pattern.

nocasebooleanoptional(optional)

Whether to perform case-insensitive matching.

Returns: boolean
Example
wildcard("file.txt", "*.txt");        // Returns true
+print(x, "\n");    // [ 1, 2, 3, 4, 5 ]

values(obj) → {Array}nullable

Returns an array containing all values of the given object.

Returns null if no object was passed.

Parameters:
NameTypeDescription
obj*

The object from which to extract values.

Returns: Array
Example
values({ foo: true, bar: false });   // [true, false]

warn(…x) → {number}

Print any of the given values to stderr. Arrays and objects are converted to their JSON representation.

Returns the amount of bytes printed.

Parameters:
NameTypeAttributesDescription
x*repeatable(repeatable)

The values to be printed.

Returns: number
Example
warn("Hello", "world");  // Print "Helloworld" to stderr
+warn({ key: "value" });  // Print JSON representation of the object to stderr

wildcard(subject, pattern, nocaseopt) → {boolean}

Match the given subject against the supplied wildcard (file glob) pattern.

  • If a truthy value is supplied as the third argument, case-insensitive matching is performed.
  • If a non-string value is supplied as the subject, it is converted into a string before being matched.

Returns true when the value matched the given pattern, otherwise false.

Parameters:
NameTypeAttributesDescription
subject*

The subject to match against the wildcard pattern.

patternstring

The wildcard pattern.

nocasebooleanoptional(optional)

Whether to perform case-insensitive matching.

Returns: boolean
Example
wildcard("file.txt", "*.txt");        // Returns true
 wildcard("file.txt", "*.TXT", true);  // Returns true (case-insensitive match)
-wildcard("file.txt", "*.jpg");        // Returns false

Type Definitions

ParseConfig :Object

A parse configuration is a plain object describing options to use when compiling ucode at runtime. It is expected as parameter by the loadfile() and loadstring() functions.

All members of the parse configuration object are optional and will default to the state of the running ucode file if omitted.

Properties
NameTypeDescription
lstrip_blocksboolean

Whether to strip whitespace preceeding template directives. See Whitespace handling.

trim_blocksboolean

Whether to trim trailing newlines following template directives. See Whitespace handling.

strict_declarationsboolean

Whether to compile the code in strict mode (true) or not (false).

raw_modeboolean

Whether to compile the code in plain script mode (true) or not (false).

module_search_pathstring[]

Override the module search path for compile time imports while compiling the ucode source.

force_dynlink_liststring[]

List of module names assumed to be dynamic library extensions, allows compiling ucode source with import statements referring to *.so extensions not present at compile time.

TimeSpec :Object

A time spec is a plain object describing a point in time, it is returned by the gmtime() and localtime() functions and expected as parameter by the complementary timegm() and timelocal() functions.

When returned by gmtime() or localtime(), all members of the object will be initialized, when passed as argument to timegm() or timelocal(), most member values are optional.

Properties
NameTypeDescription
secnumber

Seconds (0..60)

minnumber

Minutes (0..59)

hournumber

Hours (0..23)

mdaynumber

Day of month (1..31)

monnumber

Month (1..12)

yearnumber

Year (>= 1900)

wdaynumber

Day of week (1..7, Sunday = 7)

ydaynumber

Day of year (1-366, Jan 1st = 1)

isdstnumber

Daylight saving time in effect (yes = 1)

Table of Contents
\ No newline at end of file +wildcard("file.txt", "*.jpg"); // Returns false

Type Definitions

ParseConfig :Object

A parse configuration is a plain object describing options to use when compiling ucode at runtime. It is expected as parameter by the loadfile() and loadstring() functions.

All members of the parse configuration object are optional and will default to the state of the running ucode file if omitted.

Properties
NameTypeDescription
lstrip_blocksboolean

Whether to strip whitespace preceeding template directives. See Whitespace handling.

trim_blocksboolean

Whether to trim trailing newlines following template directives. See Whitespace handling.

strict_declarationsboolean

Whether to compile the code in strict mode (true) or not (false).

raw_modeboolean

Whether to compile the code in plain script mode (true) or not (false).

module_search_pathstring[]

Override the module search path for compile time imports while compiling the ucode source.

force_dynlink_liststring[]

List of module names assumed to be dynamic library extensions, allows compiling ucode source with import statements referring to *.so extensions not present at compile time.

TimeSpec :Object

A time spec is a plain object describing a point in time, it is returned by the gmtime() and localtime() functions and expected as parameter by the complementary timegm() and timelocal() functions.

When returned by gmtime() or localtime(), all members of the object will be initialized, when passed as argument to timegm() or timelocal(), most member values are optional.

Properties
NameTypeDescription
secnumber

Seconds (0..60)

minnumber

Minutes (0..59)

hournumber

Hours (0..23)

mdaynumber

Day of month (1..31)

monnumber

Month (1..12)

yearnumber

Year (>= 1900)

wdaynumber

Day of week (1..7, Sunday = 7)

ydaynumber

Day of year (1-366, Jan 1st = 1)

isdstnumber

Daylight saving time in effect (yes = 1)

Table of Contents
\ No newline at end of file diff --git a/module-debug.html b/module-debug.html index 330b4bb6..e9941aca 100644 --- a/module-debug.html +++ b/module-debug.html @@ -1,6 +1,6 @@ Module: debug

Debugger Module

This module provides runtime debug functionality for ucode scripts.

Functions can be individually imported and directly accessed using the named import syntax:

import { memdump, traceback } from 'debug';
+    

Debugger Module

This module provides runtime debug functionality for ucode scripts.

Functions can be individually imported and directly accessed using the named import syntax:

import { memdump, traceback } from 'debug';
 
 let stacktrace = traceback(1);
 
@@ -10,4 +10,4 @@
 let stacktrace = debug.traceback(1);
 
 debug.memdump("/tmp/dump.txt");
-

Additionally, the debug module namespace may also be imported by invoking the ucode interpreter with the -ldebug switch.

Upon loading, the debug module will register a SIGUSR2 signal handler which, upon receipt of the signal, will write a memory dump of the currently running program to /tmp/ucode.$timestamp.$pid.memdump. This default behavior can be inhibited by setting the UCODE_DEBUG_MEMDUMP_ENABLED environment variable to 0 when starting the process. The memory dump signal and output directory can be overridden with the UCODE_DEBUG_MEMDUMP_SIGNAL and UCODE_DEBUG_MEMDUMP_PATH environment variables respectively.

Methods

getinfo(value) → {ValueInformation}nullable

Obtain information about the given value.

The getinfo() function allows querying internal information about the given ucode value, such as the current reference count, the mark bit state etc.

Returns a dictionary with value type specific details.

Returns null if a null value was provided.

Parameters:
NameTypeDescription
value*

The value to query information for.

getlocal(levelopt, variable) → {LocalInfo}nullable

Obtain local variable.

The getlocal() function retrieves information about the specified local variable at the given call stack depth.

The call stack depth specifies the amount of levels up local variables should be queried. A value of 0 refers to this getlocal() function call itself, 1 to the function calling getlocal() and so on.

The variable to query might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the given variable.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is a C call.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeAttributesDefaultDescription
levelnumberoptional1(optional, default: 1)

The amount of call stack levels up local variables should be queried.

variablestring | number

The variable index or variable name to obtain information for.

Returns: LocalInfo

getupval(target, variable) → {UpvalInfo}nullable

Obtain captured variable (upvalue).

The getupval() function retrieves information about the specified captured variable associated with the given function value or the invoked function at the given call stack depth.

The call stack depth specifies the amount of levels up the function should be selected to query associated captured variables for. A value of 0 refers to this getupval() function call itself, 1 to the function calling getupval() and so on.

The variable to query might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the given variable.

Returns null if the given function value is not a closure.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is not a closure.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeDescription
targetfunction | number

Either a function value referring to a closure to query upvalues for or a stack depth number selecting a closure that many levels up.

variablestring | number

The variable index or variable name to obtain information for.

Returns: UpvalInfo

memdump(file) → {boolean}nullable

Write a memory dump report to the given file.

This function generates a human readable memory dump of ucode values currently managed by the running VM which is useful to track down logical memory leaks in scripts.

The file parameter can be either a string value containing a file path, in which case this function tries to create and write the report file at the given location, or an already open file handle this function should write to.

Returns true if the report has been written.

Returns null if the file could not be opened or if the handle was invalid.

Parameters:
NameTypeDescription
filestring | module:fs.file | module:fs.proc

The file path or open file handle to write report to.

Returns: boolean

setlocal(levelopt, variable, valueopt) → {LocalInfo}nullable

Set local variable.

The setlocal() function manipulates the value of the specified local variable at the given call stack depth.

The call stack depth specifies the amount of levels up local variables should be updated. A value of 0 refers to this setlocal() function call itself, 1 to the function calling setlocal() and so on.

The variable to update might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the updated variable.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is a C call.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeAttributesDefaultDescription
levelnumberoptional1(optional, default: 1)

The amount of call stack levels up local variables should be updated.

variablestring | number

The variable index or variable name to update.

value*optionalnull(optional, default: null)

The value to set the local variable to.

Returns: LocalInfo

setupval(target, variable, value) → {UpvalInfo}nullable

Set upvalue.

The setupval() function manipulates the value of the specified captured variable associated with the given function value or the invoked function at the given call stack depth.

The call stack depth specifies the amount of levels up the function should be selected to update associated captured variables for. A value of 0 refers to this setupval() function call itself, 1 to the function calling setupval() and so on.

The variable to update might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the updated variable.

Returns null if the given function value is not a closure.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is not a closure.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeDescription
targetfunction | number

Either a function value referring to a closure to update upvalues for or a stack depth number selecting a closure that many levels up.

variablestring | number

The variable index or variable name to update.

value*

The value to set the variable to.

Returns: UpvalInfo

sourcepos() → {SourcePosition}nullable

Obtain information about the current source position.

The sourcepos() function determines the source code position of the current instruction invoking this function.

Returns a dictionary containing the filename, line number and line byte offset of the call site.

Returns null if this function was invoked from C code.

traceback(levelopt) → {StackTraceEntry[]}

Capture call stack trace.

This function captures the current call stack and returns it. The optional level parameter controls how many calls up the trace should start. It defaults to 1, that is the function calling this traceback() function.

Returns an array of stack trace entries describing the function invocations up to the point where traceback() is called.

Parameters:
NameTypeAttributesDefaultDescription
levelnumberoptional1(optional, default: 1)

The number of callframes up the call trace should start, 0 is this function itself, 1 the function calling it and so on.

Returns: StackTraceEntry[]

Type Definitions

LocalInfo :Object

Properties
NameTypeDescription
indexnumber

The index of the local variable.

namestring

The name of the local variable.

value*

The current value of the local variable.

linefromnumber

The source line number of the local variable declaration.

bytefromnumber

The source line offset of the local variable declaration.

linetonumber

The source line number where the local variable goes out of scope.

bytetonumber

The source line offset where the local vatiable goes out of scope.

SourcePosition :Object

Properties
NameTypeDescription
filenamestring

The name of the source file that called this function.

linenumber

The source line of the function call.

bytenumber

The source line offset of the function call.

StackTraceEntry :Object

Properties
NameTypeAttributesDescription
calleefunction

The function that was called.

this*

The this context the function was called with.

mcallboolean

Indicates whether the function was invoked as a method.

strictbooleanoptional(optional)

Indicates whether the VM was running in strict mode when the function was called (only applicable to non-C, pure ucode calls).

filenamestringoptional(optional)

The name of the source file that called the function (only applicable to non-C, pure ucode calls).

linenumberoptional(optional)

The source line of the function call (only applicable to non-C, pure ucode calls).

bytenumberoptional(optional)

The source line offset of the function call (only applicable to non-C, pure ucode calls).

contextstringoptional(optional)

The surrounding source code context formatted as human-readable string, useful for generating debug messages (only applicable to non-C, pure ucode calls).

UpvalInfo :Object

Properties
NameTypeDescription
indexnumber

The index of the captured variable (upvalue).

namestring

The name of the captured variable.

closedboolean

Indicates whether the captured variable is closed or not. A closed upvalue means that the function outlived the declaration scope of the captured variable.

value*

The current value of the captured variable.

UpvalRef :Object

Properties
NameTypeAttributesDescription
namestring

The name of the captured variable.

closedboolean

Indicates whether the captured variable (upvalue) is closed or not. A closed upvalue means that the function value outlived the declaration scope of the captured variable.

value*

The current value of the captured variable.

slotnumberoptional(optional)

The stack slot of the captured variable. Only applicable to open (non-closed) captured variables.

ValueInformation :Object

Properties
NameTypeAttributesDescription
typestring

The name of the value type, one of integer, boolean, string, double, array, object, regexp, cfunction, closure, upvalue or resource.

value*

The value itself.

taggedboolean

Indicates whether the given value is internally stored as tagged pointer without an additional heap allocation.

markbooleanoptional(optional)

Indicates whether the value has it's mark bit set, which is used for loop detection during recursive object traversal on garbage collection cycles or complex value stringification. Only applicable to non-tagged values.

refcountnumberoptional(optional)

The current reference count of the value. Note that the getinfo() function places a reference to the value into the value field of the resulting information dictionary, so the ref count will always be at least 2 - one reference for the function call argument and one for the value property in the result dictionary. Only applicable to non-tagged values.

unsignedbooleanoptional(optional)

Whether the number value is internally stored as unsigned integer. Only applicable to non-tagged integer values.

addressnumberoptional(optional)

The address of the underlying C heap memory. Only applicable to non-tagged string, array, object, cfunction or resource values.

lengthnumberoptional(optional)

The length of the underlying string memory. Only applicable to non-tagged string values.

countnumberoptional(optional)

The amount of elements in the underlying memory structure. Only applicable to array and object values.

constantbooleanoptional(optional)

Indicates whether the value is constant (immutable). Only applicable to array and object values.

prototype*optional(optional)

The associated prototype value, if any. Only applicable to array, object and prototype values.

sourcestringoptional(optional)

The original regex source pattern. Only applicable to regexp values.

icasebooleanoptional(optional)

Whether the compiled regex has the i (ignore case) flag set. Only applicable to regexp values.

globalbooleanoptional(optional)

Whether the compiled regex has the g (global) flag set. Only applicable to regexp values.

newlinebooleanoptional(optional)

Whether the compiled regex has the s (single line) flag set. Only applicable to regexp values.

nsubnumberoptional(optional)

The amount of capture groups within the regular expression. Only applicable to regexp values.

namestringoptional(optional)

The name of the non-anonymous function. Only applicable to cfunction and closure values. Set to null for anonymous function values.

arrowbooleanoptional(optional)

Indicates whether the ucode function value is an arrow function. Only applicable to closure values.

modulebooleanoptional(optional)

Indicates whether the ucode function value is a module entry point. Only applicable to closure values.

strictbooleanoptional(optional)

Indicates whether the function body will be executed in strict mode. Only applicable to closure values.

varargbooleanoptional(optional)

Indicates whether the ucode function takes a variable number of arguments. Only applicable to closure values.

nargsnumberoptional(optional)

The number of arguments expected by the ucode function, excluding a potential final variable argument ellipsis. Only applicable to closure values.

argnamesstring[]optional(optional)

The names of the function arguments in their declaration order. Only applicable to closure values.

nupvalsnumberoptional(optional)

The number of upvalues associated with the ucode function. Only applicable to closure values.

upvalsUpvalRef[]optional(optional)

An array of upvalue information objects. Only applicable to closure values.

filenamestringoptional(optional)

The path of the source file the function was declared in. Only applicable to closure values.

linenumberoptional(optional)

The source line number the function was declared at. Only applicable to closure values.

bytenumberoptional(optional)

The source line offset the function was declared at. Only applicable to closure values.

typestringoptional(optional)

The resource type name. Only applicable to resource values.

Table of Contents
\ No newline at end of file +

Additionally, the debug module namespace may also be imported by invoking the ucode interpreter with the -ldebug switch.

Upon loading, the debug module will register a SIGUSR2 signal handler which, upon receipt of the signal, will write a memory dump of the currently running program to /tmp/ucode.$timestamp.$pid.memdump. This default behavior can be inhibited by setting the UCODE_DEBUG_MEMDUMP_ENABLED environment variable to 0 when starting the process. The memory dump signal and output directory can be overridden with the UCODE_DEBUG_MEMDUMP_SIGNAL and UCODE_DEBUG_MEMDUMP_PATH environment variables respectively.

Methods

getinfo(value) → {ValueInformation}nullable

Obtain information about the given value.

The getinfo() function allows querying internal information about the given ucode value, such as the current reference count, the mark bit state etc.

Returns a dictionary with value type specific details.

Returns null if a null value was provided.

Parameters:
NameTypeDescription
value*

The value to query information for.

getlocal(levelopt, variable) → {LocalInfo}nullable

Obtain local variable.

The getlocal() function retrieves information about the specified local variable at the given call stack depth.

The call stack depth specifies the amount of levels up local variables should be queried. A value of 0 refers to this getlocal() function call itself, 1 to the function calling getlocal() and so on.

The variable to query might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the given variable.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is a C call.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeAttributesDefaultDescription
levelnumberoptional1(optional, default: 1)

The amount of call stack levels up local variables should be queried.

variablestring | number

The variable index or variable name to obtain information for.

Returns: LocalInfo

getupval(target, variable) → {UpvalInfo}nullable

Obtain captured variable (upvalue).

The getupval() function retrieves information about the specified captured variable associated with the given function value or the invoked function at the given call stack depth.

The call stack depth specifies the amount of levels up the function should be selected to query associated captured variables for. A value of 0 refers to this getupval() function call itself, 1 to the function calling getupval() and so on.

The variable to query might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the given variable.

Returns null if the given function value is not a closure.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is not a closure.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeDescription
targetfunction | number

Either a function value referring to a closure to query upvalues for or a stack depth number selecting a closure that many levels up.

variablestring | number

The variable index or variable name to obtain information for.

Returns: UpvalInfo

memdump(file) → {boolean}nullable

Write a memory dump report to the given file.

This function generates a human readable memory dump of ucode values currently managed by the running VM which is useful to track down logical memory leaks in scripts.

The file parameter can be either a string value containing a file path, in which case this function tries to create and write the report file at the given location, or an already open file handle this function should write to.

Returns true if the report has been written.

Returns null if the file could not be opened or if the handle was invalid.

Parameters:
NameTypeDescription
filestring | module:fs.file | module:fs.proc

The file path or open file handle to write report to.

Returns: boolean

setlocal(levelopt, variable, valueopt) → {LocalInfo}nullable

Set local variable.

The setlocal() function manipulates the value of the specified local variable at the given call stack depth.

The call stack depth specifies the amount of levels up local variables should be updated. A value of 0 refers to this setlocal() function call itself, 1 to the function calling setlocal() and so on.

The variable to update might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the updated variable.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is a C call.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeAttributesDefaultDescription
levelnumberoptional1(optional, default: 1)

The amount of call stack levels up local variables should be updated.

variablestring | number

The variable index or variable name to update.

value*optionalnull(optional, default: null)

The value to set the local variable to.

Returns: LocalInfo

setupval(target, variable, value) → {UpvalInfo}nullable

Set upvalue.

The setupval() function manipulates the value of the specified captured variable associated with the given function value or the invoked function at the given call stack depth.

The call stack depth specifies the amount of levels up the function should be selected to update associated captured variables for. A value of 0 refers to this setupval() function call itself, 1 to the function calling setupval() and so on.

The variable to update might be either specified by name or by its index with index numbers following the source code declaration order.

Returns a dictionary holding information about the updated variable.

Returns null if the given function value is not a closure.

Returns null if the stack depth exceeds the size of the current call stack.

Returns null if the invocation at the given stack depth is not a closure.

Returns null if the given variable name is not found or the given variable index is invalid.

Parameters:
NameTypeDescription
targetfunction | number

Either a function value referring to a closure to update upvalues for or a stack depth number selecting a closure that many levels up.

variablestring | number

The variable index or variable name to update.

value*

The value to set the variable to.

Returns: UpvalInfo

sourcepos() → {SourcePosition}nullable

Obtain information about the current source position.

The sourcepos() function determines the source code position of the current instruction invoking this function.

Returns a dictionary containing the filename, line number and line byte offset of the call site.

Returns null if this function was invoked from C code.

traceback(levelopt) → {StackTraceEntry[]}

Capture call stack trace.

This function captures the current call stack and returns it. The optional level parameter controls how many calls up the trace should start. It defaults to 1, that is the function calling this traceback() function.

Returns an array of stack trace entries describing the function invocations up to the point where traceback() is called.

Parameters:
NameTypeAttributesDefaultDescription
levelnumberoptional1(optional, default: 1)

The number of callframes up the call trace should start, 0 is this function itself, 1 the function calling it and so on.

Returns: StackTraceEntry[]

Type Definitions

LocalInfo :Object

Properties
NameTypeDescription
indexnumber

The index of the local variable.

namestring

The name of the local variable.

value*

The current value of the local variable.

linefromnumber

The source line number of the local variable declaration.

bytefromnumber

The source line offset of the local variable declaration.

linetonumber

The source line number where the local variable goes out of scope.

bytetonumber

The source line offset where the local vatiable goes out of scope.

SourcePosition :Object

Properties
NameTypeDescription
filenamestring

The name of the source file that called this function.

linenumber

The source line of the function call.

bytenumber

The source line offset of the function call.

StackTraceEntry :Object

Properties
NameTypeAttributesDescription
calleefunction

The function that was called.

this*

The this context the function was called with.

mcallboolean

Indicates whether the function was invoked as a method.

strictbooleanoptional(optional)

Indicates whether the VM was running in strict mode when the function was called (only applicable to non-C, pure ucode calls).

filenamestringoptional(optional)

The name of the source file that called the function (only applicable to non-C, pure ucode calls).

linenumberoptional(optional)

The source line of the function call (only applicable to non-C, pure ucode calls).

bytenumberoptional(optional)

The source line offset of the function call (only applicable to non-C, pure ucode calls).

contextstringoptional(optional)

The surrounding source code context formatted as human-readable string, useful for generating debug messages (only applicable to non-C, pure ucode calls).

UpvalInfo :Object

Properties
NameTypeDescription
indexnumber

The index of the captured variable (upvalue).

namestring

The name of the captured variable.

closedboolean

Indicates whether the captured variable is closed or not. A closed upvalue means that the function outlived the declaration scope of the captured variable.

value*

The current value of the captured variable.

UpvalRef :Object

Properties
NameTypeAttributesDescription
namestring

The name of the captured variable.

closedboolean

Indicates whether the captured variable (upvalue) is closed or not. A closed upvalue means that the function value outlived the declaration scope of the captured variable.

value*

The current value of the captured variable.

slotnumberoptional(optional)

The stack slot of the captured variable. Only applicable to open (non-closed) captured variables.

ValueInformation :Object

Properties
NameTypeAttributesDescription
typestring

The name of the value type, one of integer, boolean, string, double, array, object, regexp, cfunction, closure, upvalue or resource.

value*

The value itself.

taggedboolean

Indicates whether the given value is internally stored as tagged pointer without an additional heap allocation.

markbooleanoptional(optional)

Indicates whether the value has it's mark bit set, which is used for loop detection during recursive object traversal on garbage collection cycles or complex value stringification. Only applicable to non-tagged values.

refcountnumberoptional(optional)

The current reference count of the value. Note that the getinfo() function places a reference to the value into the value field of the resulting information dictionary, so the ref count will always be at least 2 - one reference for the function call argument and one for the value property in the result dictionary. Only applicable to non-tagged values.

unsignedbooleanoptional(optional)

Whether the number value is internally stored as unsigned integer. Only applicable to non-tagged integer values.

addressnumberoptional(optional)

The address of the underlying C heap memory. Only applicable to non-tagged string, array, object, cfunction or resource values.

lengthnumberoptional(optional)

The length of the underlying string memory. Only applicable to non-tagged string values.

countnumberoptional(optional)

The amount of elements in the underlying memory structure. Only applicable to array and object values.

constantbooleanoptional(optional)

Indicates whether the value is constant (immutable). Only applicable to array and object values.

prototype*optional(optional)

The associated prototype value, if any. Only applicable to array, object and prototype values.

sourcestringoptional(optional)

The original regex source pattern. Only applicable to regexp values.

icasebooleanoptional(optional)

Whether the compiled regex has the i (ignore case) flag set. Only applicable to regexp values.

globalbooleanoptional(optional)

Whether the compiled regex has the g (global) flag set. Only applicable to regexp values.

newlinebooleanoptional(optional)

Whether the compiled regex has the s (single line) flag set. Only applicable to regexp values.

nsubnumberoptional(optional)

The amount of capture groups within the regular expression. Only applicable to regexp values.

namestringoptional(optional)

The name of the non-anonymous function. Only applicable to cfunction and closure values. Set to null for anonymous function values.

arrowbooleanoptional(optional)

Indicates whether the ucode function value is an arrow function. Only applicable to closure values.

modulebooleanoptional(optional)

Indicates whether the ucode function value is a module entry point. Only applicable to closure values.

strictbooleanoptional(optional)

Indicates whether the function body will be executed in strict mode. Only applicable to closure values.

varargbooleanoptional(optional)

Indicates whether the ucode function takes a variable number of arguments. Only applicable to closure values.

nargsnumberoptional(optional)

The number of arguments expected by the ucode function, excluding a potential final variable argument ellipsis. Only applicable to closure values.

argnamesstring[]optional(optional)

The names of the function arguments in their declaration order. Only applicable to closure values.

nupvalsnumberoptional(optional)

The number of upvalues associated with the ucode function. Only applicable to closure values.

upvalsUpvalRef[]optional(optional)

An array of upvalue information objects. Only applicable to closure values.

filenamestringoptional(optional)

The path of the source file the function was declared in. Only applicable to closure values.

linenumberoptional(optional)

The source line number the function was declared at. Only applicable to closure values.

bytenumberoptional(optional)

The source line offset the function was declared at. Only applicable to closure values.

typestringoptional(optional)

The resource type name. Only applicable to resource values.

Table of Contents
\ No newline at end of file diff --git a/module-fs.dir.html b/module-fs.dir.html index bf7f55b8..27ad16c7 100644 --- a/module-fs.dir.html +++ b/module-fs.dir.html @@ -1,6 +1,6 @@ Class: dir

fs. dir

Represents a handle for interacting with a directory opened by opendir().

Example
const handle = opendir(…);
+    

fs. dir

Represents a handle for interacting with a directory opened by opendir().

Example
const handle = opendir(…);
 
 handle.read();
 
@@ -20,4 +20,4 @@
 
 handle.seek(begin);
 
-print(handle.read(), "\n");  // prints the first entry again

tell() → {number}nullable

Obtain current read position.

Returns the current read position in the open directory handle which can be passed back to the seek() function to return to this position. This is mainly useful to read an open directory handle (or specific items) multiple times.

Returns an integer referring to the current position.

Returns null if an error occurred.

Returns: number
Table of Contents
\ No newline at end of file +print(handle.read(), "\n"); // prints the first entry again

tell() → {number}nullable

Obtain current read position.

Returns the current read position in the open directory handle which can be passed back to the seek() function to return to this position. This is mainly useful to read an open directory handle (or specific items) multiple times.

Returns an integer referring to the current position.

Returns null if an error occurred.

Returns: number
Table of Contents
\ No newline at end of file diff --git a/module-fs.file.html b/module-fs.file.html index 13b20d14..2ce3f030 100644 --- a/module-fs.file.html +++ b/module-fs.file.html @@ -1,6 +1,6 @@ Class: file

fs. file

Represents a handle for interacting with a file opened by one of the file open functions.

Example
const handle = open(…);
+    

fs. file

Represents a handle for interacting with a file opened by one of the file open functions.

Example
const handle = open(…);
 
 handle.read(…);
 handle.write(…);
@@ -43,4 +43,4 @@
 fp.seek(-10, 2);            // set position to ten bytes before EOF ...
 print(fp.read(100), "\n");  // ... reads 10 bytes at most

tell() → {number}nullable

Obtain current read position.

Obtains the current, absolute read position of the open file.

Returns an integer containing the current read offset in bytes.

Returns null if an error occurred.

Returns: number

write(data) → {number}nullable

Writes a chunk of data to the file handle.

In case the given data is not a string, it is converted to a string before being written into the file. String values are written as-is, integer and double values are written in decimal notation, boolean values are written as true or false while arrays and objects are converted to their JSON representation before being written. The null value is represented by an empty string so file.write(null) would be a no-op. Resource values are written in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

If resource, array or object values contain a tostring() function in their prototypes, then this function is invoked to obtain an alternative string representation of the value.

Returns the number of bytes written.

Returns null if a write error occurred.

Parameters:
NameTypeDescription
data*

The data to be written.

Returns: number
Example
const fp = open("file.txt", "w");
 
-fp.write("Hello world!\n");
Table of Contents
\ No newline at end of file +fp.write("Hello world!\n");
Table of Contents
\ No newline at end of file diff --git a/module-fs.html b/module-fs.html index b4638a9b..1e97a2bf 100644 --- a/module-fs.html +++ b/module-fs.html @@ -1,6 +1,6 @@ Module: fs

Filesystem Access

The fs module provides functions for interacting with the file system.

Functions can be individually imported and directly accessed using the named import syntax:

import { readlink, popen } from 'fs';
+    

Filesystem Access

The fs module provides functions for interacting with the file system.

Functions can be individually imported and directly accessed using the named import syntax:

import { readlink, popen } from 'fs';
 
 let dest = readlink('/sys/class/net/eth0');
 let proc = popen('ps ww');
@@ -53,4 +53,4 @@
 
 // Write object as JSON to a file and limit to 1024 bytes at most
 const obj = { foo: "Hello world", bar: true, baz: 123 };
-const bytesWritten = writefile('debug.txt', obj, 1024);

Type Definitions

FileStatResult :Object

Properties
NameTypeDescription
devObject

The device information.

Properties
NameTypeDescription
majornumber

The major device number.

minornumber

The minor device number.

permObject

The file permissions.

Properties
NameTypeDescription
setuidboolean

Whether the setuid bit is set.

setgidboolean

Whether the setgid bit is set.

stickyboolean

Whether the sticky bit is set.

user_readboolean

Whether the file is readable by the owner.

user_writeboolean

Whether the file is writable by the owner.

user_execboolean

Whether the file is executable by the owner.

group_readboolean

Whether the file is readable by the group.

group_writeboolean

Whether the file is writable by the group.

group_execboolean

Whether the file is executable by the group.

other_readboolean

Whether the file is readable by others.

other_writeboolean

Whether the file is writable by others.

other_execboolean

Whether the file is executable by others.

inodenumber

The inode number.

modenumber

The file mode.

nlinknumber

The number of hard links.

uidnumber

The user ID of the owner.

gidnumber

The group ID of the owner.

sizenumber

The file size in bytes.

blksizenumber

The block size for file system I/O.

blocksnumber

The number of 512-byte blocks allocated for the file.

atimenumber

The timestamp when the file was last accessed.

mtimenumber

The timestamp when the file was last modified.

ctimenumber

The timestamp when the file status was last changed.

typestring

The type of the file ("directory", "file", etc.).

Table of Contents
\ No newline at end of file +const bytesWritten = writefile('debug.txt', obj, 1024);

Type Definitions

FileStatResult :Object

Properties
NameTypeDescription
devObject

The device information.

Properties
NameTypeDescription
majornumber

The major device number.

minornumber

The minor device number.

permObject

The file permissions.

Properties
NameTypeDescription
setuidboolean

Whether the setuid bit is set.

setgidboolean

Whether the setgid bit is set.

stickyboolean

Whether the sticky bit is set.

user_readboolean

Whether the file is readable by the owner.

user_writeboolean

Whether the file is writable by the owner.

user_execboolean

Whether the file is executable by the owner.

group_readboolean

Whether the file is readable by the group.

group_writeboolean

Whether the file is writable by the group.

group_execboolean

Whether the file is executable by the group.

other_readboolean

Whether the file is readable by others.

other_writeboolean

Whether the file is writable by others.

other_execboolean

Whether the file is executable by others.

inodenumber

The inode number.

modenumber

The file mode.

nlinknumber

The number of hard links.

uidnumber

The user ID of the owner.

gidnumber

The group ID of the owner.

sizenumber

The file size in bytes.

blksizenumber

The block size for file system I/O.

blocksnumber

The number of 512-byte blocks allocated for the file.

atimenumber

The timestamp when the file was last accessed.

mtimenumber

The timestamp when the file was last modified.

ctimenumber

The timestamp when the file status was last changed.

typestring

The type of the file ("directory", "file", etc.).

Table of Contents
\ No newline at end of file diff --git a/module-fs.proc.html b/module-fs.proc.html index 0b27c707..6c2938ad 100644 --- a/module-fs.proc.html +++ b/module-fs.proc.html @@ -1,6 +1,6 @@ Class: proc

fs. proc

Represents a handle for interacting with a program launched by popen().

Example
const handle = popen(…);
+    

fs. proc

Represents a handle for interacting with a program launched by popen().

Example
const handle = popen(…);
 
 handle.read(…);
 handle.write(…);
@@ -29,4 +29,4 @@
 // Example 4: Read until encountering the character ':'
 const field = fp.read(":");

write(data) → {number}nullable

Writes a chunk of data to the program handle.

In case the given data is not a string, it is converted to a string before being written to the program's stdin. String values are written as-is, integer and double values are written in decimal notation, boolean values are written as true or false while arrays and objects are converted to their JSON representation before being written. The null value is represented by an empty string so proc.write(null) would be a no-op. Resource values are written in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

If resource, array or object values contain a tostring() function in their prototypes, then this function is invoked to obtain an alternative string representation of the value.

Returns the number of bytes written.

Returns null if a write error occurred.

Parameters:
NameTypeDescription
data*

The data to be written.

Returns: number
Example
const fp = popen("command", "w");
 
-fp.write("Hello world!\n");
Table of Contents
\ No newline at end of file +fp.write("Hello world!\n");
Table of Contents
\ No newline at end of file diff --git a/module-log.html b/module-log.html index d2acc1ee..88e48ded 100644 --- a/module-log.html +++ b/module-log.html @@ -1,6 +1,6 @@ Module: log

System logging functions

The log module provides bindings to the POSIX syslog functions openlog(), syslog() and closelog() as well as - when available - the OpenWrt specific ulog library functions.

Functions can be individually imported and directly accessed using the named import syntax:

import { openlog, syslog, LOG_PID, LOG_USER, LOG_ERR } from 'log';
+    

System logging functions

The log module provides bindings to the POSIX syslog functions openlog(), syslog() and closelog() as well as - when available - the OpenWrt specific ulog library functions.

Functions can be individually imported and directly accessed using the named import syntax:

import { openlog, syslog, LOG_PID, LOG_USER, LOG_ERR } from 'log';
 
 openlog("my-log-ident", LOG_PID, LOG_USER);
 syslog(LOG_ERR, "An error occurred!");
@@ -58,4 +58,4 @@
 ulog(LOG_DEBUG, "Testing thresholds");
 
 // Using priority name
-ulog_threshold("debug");

Type Definitions

LogFacility :string

The following log facility strings are recognized:

FacilityDescription
"auth"Authentication/authorization messages.
"authpriv"Private authentication messages.
"cron"Clock daemon (cron and at commands).
"daemon"System daemons without separate facility values.
"ftp"FTP server daemon.
"kern"Kernel messages.
"lpr"Line printer subsystem.
"mail"Mail system.
"news"Network news subsystem.
"syslog"Messages generated internally by syslogd.
"user"Generic user-level messages.
"uucp"UUCP subsystem.
"local0"Local use 0 (custom facility).
"local1"Local use 1 (custom facility).
"local2"Local use 2 (custom facility).
"local3"Local use 3 (custom facility).
"local4"Local use 4 (custom facility).
"local5"Local use 5 (custom facility).
"local6"Local use 6 (custom facility).
"local7"Local use 7 (custom facility).

LogOption :string

The following log option strings are recognized:

Log OptionDescription
"pid"Include PID with each message.
"cons"Log to console if an error occurs while sending to syslog.
"ndelay"Open the connection to the logger immediately.
"odelay"Delay open until the first message is logged.
"nowait"Do not wait for child processes created during logging.

LogPriority :string

The following log priority strings are recognized:

PriorityDescription
"emerg"System is unusable.
"alert"Action must be taken immediately.
"crit"Critical conditions.
"err"Error conditions.
"warning"Warning conditions.
"notice"Normal, but significant, condition.
"info"Informational message.
"debug"Debug-level message.

UlogChannel :string

The following ulog channel strings are recognized:

ChannelDescription
"kmsg"Log to /dev/kmsg, log messages appear in dmesg.
"syslog"Use standard syslog() mechanism.
"stdio"Use stderr for log output.
Table of Contents
\ No newline at end of file +ulog_threshold("debug");

Type Definitions

LogFacility :string

The following log facility strings are recognized:

FacilityDescription
"auth"Authentication/authorization messages.
"authpriv"Private authentication messages.
"cron"Clock daemon (cron and at commands).
"daemon"System daemons without separate facility values.
"ftp"FTP server daemon.
"kern"Kernel messages.
"lpr"Line printer subsystem.
"mail"Mail system.
"news"Network news subsystem.
"syslog"Messages generated internally by syslogd.
"user"Generic user-level messages.
"uucp"UUCP subsystem.
"local0"Local use 0 (custom facility).
"local1"Local use 1 (custom facility).
"local2"Local use 2 (custom facility).
"local3"Local use 3 (custom facility).
"local4"Local use 4 (custom facility).
"local5"Local use 5 (custom facility).
"local6"Local use 6 (custom facility).
"local7"Local use 7 (custom facility).

LogOption :string

The following log option strings are recognized:

Log OptionDescription
"pid"Include PID with each message.
"cons"Log to console if an error occurs while sending to syslog.
"ndelay"Open the connection to the logger immediately.
"odelay"Delay open until the first message is logged.
"nowait"Do not wait for child processes created during logging.

LogPriority :string

The following log priority strings are recognized:

PriorityDescription
"emerg"System is unusable.
"alert"Action must be taken immediately.
"crit"Critical conditions.
"err"Error conditions.
"warning"Warning conditions.
"notice"Normal, but significant, condition.
"info"Informational message.
"debug"Debug-level message.

UlogChannel :string

The following ulog channel strings are recognized:

ChannelDescription
"kmsg"Log to /dev/kmsg, log messages appear in dmesg.
"syslog"Use standard syslog() mechanism.
"stdio"Use stderr for log output.
Table of Contents
\ No newline at end of file diff --git a/module-math.html b/module-math.html index 96e82fac..a239b906 100644 --- a/module-math.html +++ b/module-math.html @@ -1,6 +1,6 @@ Module: math

Mathematical Functions

The math module bundles various mathematical and trigonometrical functions.

Functions can be individually imported and directly accessed using the named import syntax:

import { pow, rand } from 'math';
+    

Mathematical Functions

The math module bundles various mathematical and trigonometrical functions.

Functions can be individually imported and directly accessed using the named import syntax:

import { pow, rand } from 'math';
 
 let x = pow(2, 5);
 let y = rand();
@@ -8,4 +8,4 @@
 
 let x = math.pow(2, 5);
 let y = math.rand();
-

Additionally, the math module namespace may also be imported by invoking the ucode interpreter with the -lmath switch.

Methods

abs(number) → {number}

Returns the absolute value of the given numeric value.

Parameters:
NameTypeDescription
number*

The number to return the absolute value for.

Returns: number

Returns the absolute value or NaN if the given argument could not be converted to a number.

atan2(y, x) → {number}

Calculates the principal value of the arc tangent of y/x, using the signs of the two arguments to determine the quadrant of the result.

On success, this function returns the principal value of the arc tangent of y/x in radians; the return value is in the range [-pi, pi].

  • If y is +0 (-0) and x is less than 0, +pi (-pi) is returned.
  • If y is +0 (-0) and x is greater than 0, +0 (-0) is returned.
  • If y is less than 0 and x is +0 or -0, -pi/2 is returned.
  • If y is greater than 0 and x is +0 or -0, pi/2 is returned.
  • If either x or y is NaN, a NaN is returned.
  • If y is +0 (-0) and x is -0, +pi (-pi) is returned.
  • If y is +0 (-0) and x is +0, +0 (-0) is returned.
  • If y is a finite value greater (less) than 0, and x is negative infinity, +pi (-pi) is returned.
  • If y is a finite value greater (less) than 0, and x is positive infinity, +0 (-0) is returned.
  • If y is positive infinity (negative infinity), and x is finite, pi/2 (-pi/2) is returned.
  • If y is positive infinity (negative infinity) and x is negative infinity, +3pi/4 (-3pi/4) is returned.
  • If y is positive infinity (negative infinity) and x is positive infinity, +pi/4 (-pi/4) is returned.

When either x or y can't be converted to a numeric value, NaN is returned.

Parameters:
NameTypeDescription
y*

The y value.

x*

The x value.

Returns: number

cos(x) → {number}

Calculates the cosine of x, where x is given in radians.

Returns the resulting consine value.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Radians value to calculate cosine for.

Returns: number

exp(x) → {number}

Calculates the value of e (the base of natural logarithms) raised to the power of x.

On success, returns the exponential value of x.

  • If x is positive infinity, positive infinity is returned.
  • If x is negative infinity, +0 is returned.
  • If the result underflows, a range error occurs, and zero is returned.
  • If the result overflows, a range error occurs, and Infinity is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Power to raise e to.

Returns: number

isnan(x) → {boolean}

Tests whether x is a NaN double.

This functions checks whether the given argument is of type double with a NaN (not a number) value.

Returns true if the value is NaN, otherwise false.

Note that a value can also be checked for NaN with the expression x !== x which only evaluates to true if x is NaN.

Parameters:
NameTypeDescription
xnumber

The value to test.

Returns: boolean

log(x) → {number}

Calculates the natural logarithm of x.

On success, returns the natural logarithm of x.

  • If x is 1, the result is +0.
  • If x is positive nfinity, positive infinity is returned.
  • If x is zero, then a pole error occurs, and the function returns negative infinity.
  • If x is negative (including negative infinity), then a domain error occurs, and NaN is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Value to calulate natural logarithm of.

Returns: number

pow(x, y) → {number}

Calculates the value of x raised to the power of y.

On success, returns the value of x raised to the power of y.

  • If the result overflows, a range error occurs, and the function returns Infinity.
  • If result underflows, and is not representable, a range error occurs, and 0.0 with the appropriate sign is returned.
  • If x is +0 or -0, and y is an odd integer less than 0, a pole error occurs Infinity is returned, with the same sign as x.
  • If x is +0 or -0, and y is less than 0 and not an odd integer, a pole error occurs and Infinity is returned.
  • If x is +0 (-0), and y is an odd integer greater than 0, the result is +0 (-0).
  • If x is 0, and y greater than 0 and not an odd integer, the result is +0.
  • If x is -1, and y is positive infinity or negative infinity, the result is 1.0.
  • If x is +1, the result is 1.0 (even if y is NaN).
  • If y is 0, the result is 1.0 (even if x is NaN).
  • If x is a finite value less than 0, and y is a finite noninteger, a domain error occurs, and NaN is returned.
  • If the absolute value of x is less than 1, and y is negative infinity, the result is positive infinity.
  • If the absolute value of x is greater than 1, and y is negative infinity, the result is +0.
  • If the absolute value of x is less than 1, and y is positive infinity, the result is +0.
  • If the absolute value of x is greater than 1, and y is positive infinity, the result is positive infinity.
  • If x is negative infinity, and y is an odd integer less than 0, the result is -0.
  • If x is negative infinity, and y less than 0 and not an odd integer, the result is +0.
  • If x is negative infinity, and y is an odd integer greater than 0, the result is negative infinity.
  • If x is negative infinity, and y greater than 0 and not an odd integer, the result is positive infinity.
  • If x is positive infinity, and y less than 0, the result is +0.
  • If x is positive infinity, and y greater than 0, the result is positive infinity.

Returns NaN if either the x or y value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

The base value.

ynumber

The power value.

Returns: number

rand() → {number}

Produces a pseudo-random positive integer.

Returns the calculated pseuo-random value. The value is within the range 0 to RAND_MAX inclusive where RAND_MAX is a platform specific value guaranteed to be at least 32767.

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

If no seed value is explicitly set by calling srand() prior to the first call to rand(), the math module will automatically seed the PRNG once, using the current time of day in milliseconds as seed value.

Returns: number

sin(x) → {number}

Calculates the sine of x, where x is given in radians.

Returns the resulting sine value.

  • When x is positive or negative infinity, a domain error occurs and NaN is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Radians value to calculate sine for.

Returns: number

sqrt(x) → {number}

Calculates the nonnegative square root of x.

Returns the resulting square root value.

  • If x is +0 (-0) then +0 (-0) is returned.
  • If x is positive infinity, positive infinity is returned.
  • If x is less than -0, a domain error occurs, and NaN is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Value to calculate square root for.

Returns: number

srand(seed)

Seeds the pseudo-random number generator.

This functions seeds the PRNG with the given value and thus affects the pseudo-random integer sequence produced by subsequent calls to rand().

Setting the same seed value will result in the same pseudo-random numbers produced by rand().

Parameters:
NameTypeDescription
seednumber

The seed value.

Table of Contents
\ No newline at end of file +

Additionally, the math module namespace may also be imported by invoking the ucode interpreter with the -lmath switch.

Methods

abs(number) → {number}

Returns the absolute value of the given numeric value.

Parameters:
NameTypeDescription
number*

The number to return the absolute value for.

Returns: number

Returns the absolute value or NaN if the given argument could not be converted to a number.

atan2(y, x) → {number}

Calculates the principal value of the arc tangent of y/x, using the signs of the two arguments to determine the quadrant of the result.

On success, this function returns the principal value of the arc tangent of y/x in radians; the return value is in the range [-pi, pi].

  • If y is +0 (-0) and x is less than 0, +pi (-pi) is returned.
  • If y is +0 (-0) and x is greater than 0, +0 (-0) is returned.
  • If y is less than 0 and x is +0 or -0, -pi/2 is returned.
  • If y is greater than 0 and x is +0 or -0, pi/2 is returned.
  • If either x or y is NaN, a NaN is returned.
  • If y is +0 (-0) and x is -0, +pi (-pi) is returned.
  • If y is +0 (-0) and x is +0, +0 (-0) is returned.
  • If y is a finite value greater (less) than 0, and x is negative infinity, +pi (-pi) is returned.
  • If y is a finite value greater (less) than 0, and x is positive infinity, +0 (-0) is returned.
  • If y is positive infinity (negative infinity), and x is finite, pi/2 (-pi/2) is returned.
  • If y is positive infinity (negative infinity) and x is negative infinity, +3pi/4 (-3pi/4) is returned.
  • If y is positive infinity (negative infinity) and x is positive infinity, +pi/4 (-pi/4) is returned.

When either x or y can't be converted to a numeric value, NaN is returned.

Parameters:
NameTypeDescription
y*

The y value.

x*

The x value.

Returns: number

cos(x) → {number}

Calculates the cosine of x, where x is given in radians.

Returns the resulting consine value.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Radians value to calculate cosine for.

Returns: number

exp(x) → {number}

Calculates the value of e (the base of natural logarithms) raised to the power of x.

On success, returns the exponential value of x.

  • If x is positive infinity, positive infinity is returned.
  • If x is negative infinity, +0 is returned.
  • If the result underflows, a range error occurs, and zero is returned.
  • If the result overflows, a range error occurs, and Infinity is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Power to raise e to.

Returns: number

isnan(x) → {boolean}

Tests whether x is a NaN double.

This functions checks whether the given argument is of type double with a NaN (not a number) value.

Returns true if the value is NaN, otherwise false.

Note that a value can also be checked for NaN with the expression x !== x which only evaluates to true if x is NaN.

Parameters:
NameTypeDescription
xnumber

The value to test.

Returns: boolean

log(x) → {number}

Calculates the natural logarithm of x.

On success, returns the natural logarithm of x.

  • If x is 1, the result is +0.
  • If x is positive nfinity, positive infinity is returned.
  • If x is zero, then a pole error occurs, and the function returns negative infinity.
  • If x is negative (including negative infinity), then a domain error occurs, and NaN is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Value to calulate natural logarithm of.

Returns: number

pow(x, y) → {number}

Calculates the value of x raised to the power of y.

On success, returns the value of x raised to the power of y.

  • If the result overflows, a range error occurs, and the function returns Infinity.
  • If result underflows, and is not representable, a range error occurs, and 0.0 with the appropriate sign is returned.
  • If x is +0 or -0, and y is an odd integer less than 0, a pole error occurs Infinity is returned, with the same sign as x.
  • If x is +0 or -0, and y is less than 0 and not an odd integer, a pole error occurs and Infinity is returned.
  • If x is +0 (-0), and y is an odd integer greater than 0, the result is +0 (-0).
  • If x is 0, and y greater than 0 and not an odd integer, the result is +0.
  • If x is -1, and y is positive infinity or negative infinity, the result is 1.0.
  • If x is +1, the result is 1.0 (even if y is NaN).
  • If y is 0, the result is 1.0 (even if x is NaN).
  • If x is a finite value less than 0, and y is a finite noninteger, a domain error occurs, and NaN is returned.
  • If the absolute value of x is less than 1, and y is negative infinity, the result is positive infinity.
  • If the absolute value of x is greater than 1, and y is negative infinity, the result is +0.
  • If the absolute value of x is less than 1, and y is positive infinity, the result is +0.
  • If the absolute value of x is greater than 1, and y is positive infinity, the result is positive infinity.
  • If x is negative infinity, and y is an odd integer less than 0, the result is -0.
  • If x is negative infinity, and y less than 0 and not an odd integer, the result is +0.
  • If x is negative infinity, and y is an odd integer greater than 0, the result is negative infinity.
  • If x is negative infinity, and y greater than 0 and not an odd integer, the result is positive infinity.
  • If x is positive infinity, and y less than 0, the result is +0.
  • If x is positive infinity, and y greater than 0, the result is positive infinity.

Returns NaN if either the x or y value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

The base value.

ynumber

The power value.

Returns: number

rand() → {number}

Produces a pseudo-random positive integer.

Returns the calculated pseuo-random value. The value is within the range 0 to RAND_MAX inclusive where RAND_MAX is a platform specific value guaranteed to be at least 32767.

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

If no seed value is explicitly set by calling srand() prior to the first call to rand(), the math module will automatically seed the PRNG once, using the current time of day in milliseconds as seed value.

Returns: number

sin(x) → {number}

Calculates the sine of x, where x is given in radians.

Returns the resulting sine value.

  • When x is positive or negative infinity, a domain error occurs and NaN is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Radians value to calculate sine for.

Returns: number

sqrt(x) → {number}

Calculates the nonnegative square root of x.

Returns the resulting square root value.

  • If x is +0 (-0) then +0 (-0) is returned.
  • If x is positive infinity, positive infinity is returned.
  • If x is less than -0, a domain error occurs, and NaN is returned.

Returns NaN if the x value can't be converted to a number.

Parameters:
NameTypeDescription
xnumber

Value to calculate square root for.

Returns: number

srand(seed)

Seeds the pseudo-random number generator.

This functions seeds the PRNG with the given value and thus affects the pseudo-random integer sequence produced by subsequent calls to rand().

Setting the same seed value will result in the same pseudo-random numbers produced by rand().

Parameters:
NameTypeDescription
seednumber

The seed value.

Table of Contents
\ No newline at end of file diff --git a/module-struct.html b/module-struct.html index 7387c524..a660436e 100644 --- a/module-struct.html +++ b/module-struct.html @@ -1,6 +1,6 @@ Module: struct

Handle Packed Binary Data

The struct module provides routines for interpreting byte strings as packed binary data.

Functions can be individually imported and directly accessed using the named import syntax:

import { pack, unpack } from 'struct';
+    

Handle Packed Binary Data

The struct module provides routines for interpreting byte strings as packed binary data.

Functions can be individually imported and directly accessed using the named import syntax:

import { pack, unpack } from 'struct';
 
 let buffer = pack('bhl', -13, 1234, 444555666);
 let values = unpack('bhl', buffer);
@@ -45,4 +45,4 @@
 const data = pack('!III', 1, 2, 3);

unpack(format, input, offsetopt) → {array}

Unpack given byte string according to specified format.

The unpack() function interpretes a byte string according to the given format string and returns the resulting values. If the optional offset argument is given, unpacking starts from this byte position within the input. If not specified, the start offset defaults to 0, the start of the given input string.

Returns an array of unpacked values.

Raises a runtime exception if the format string is invalid or if an invalid input string or offset value is given.

Parameters:
NameTypeAttributesDefaultDescription
formatstring

The format string.

inputstring

The input string to unpack.

offsetnumberoptional0(optional, default: 0)

The offset within the input string to start unpacking from.

Returns: array
Example
// Unpack three consecutive unsigned int values in network byte order.
 const numbers =
   unpack('!III', '\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03');
-print(numbers, "\n"); // [ 1, 2, 3 ]
Table of Contents
\ No newline at end of file +print(numbers, "\n"); // [ 1, 2, 3 ]
Table of Contents
\ No newline at end of file diff --git a/module-struct.instance.html b/module-struct.instance.html index c17bfc51..e043b246 100644 --- a/module-struct.instance.html +++ b/module-struct.instance.html @@ -1,9 +1,9 @@ Class: instance

struct. instance

Represents a struct instance created by new().

Example
const fmt = struct.new(…);
+    

struct. instance

Represents a struct instance created by new().

Example
const fmt = struct.new(…);
 
 fmt.pack(…);
 
 const values = fmt.unpack(…);

Methods

pack(…values) → {string}

Pack given values.

The pack() function creates a byte string containing the argument values packed according to the given format instance.

Returns the packed string.

Raises a runtime exception if a given argument value does not match the required type of the corresponding format string directive.

Parameters:
NameTypeAttributesDescription
values*repeatable(repeatable)

Variable number of values to pack.

Returns: string
Example
const fmt = struct.new(…);
 const data = fmt.pack(…);

unpack(input, offsetopt) → {array}

Unpack given byte string.

The unpack() function interpretes a byte string according to the given format instance and returns the resulting values. If the optional offset argument is given, unpacking starts from this byte position within the input. If not specified, the start offset defaults to 0, the start of the given input string.

Returns an array of unpacked values.

Raises a runtime exception if an invalid input string or offset value is given.

Parameters:
NameTypeAttributesDefaultDescription
inputstring

The input string to unpack.

offsetnumberoptional0(optional, default: 0)

The offset within the input string to start unpacking from.

Returns: array
Example
const fmt = struct.new(…);
-const values = fmt.unpack(…);
Table of Contents
\ No newline at end of file +const values = fmt.unpack(…);
Table of Contents
\ No newline at end of file diff --git a/module-uci.cursor.html b/module-uci.cursor.html index 2ff40c5c..c7cfdea4 100644 --- a/module-uci.cursor.html +++ b/module-uci.cursor.html @@ -1,6 +1,6 @@ Class: cursor

uci. cursor

Represents a context for interacting with uci configuration files.

Operations on uci configurations are performed through a uci cursor object which operates on in-memory representations of loaded configuration files.

Any changes made to configuration values are local to the cursor object and held in memory only until they're written out to the filesystem using the save() and commit() methods.

Changes performed in one cursor instance are not reflected in another, unless the first instance writes those changes to the filesystem and the other instance explicitly (re)loads the affected configuration files.

Example
const ctx = cursor(…);
+    

uci. cursor

Represents a context for interacting with uci configuration files.

Operations on uci configurations are performed through a uci cursor object which operates on in-memory representations of loaded configuration files.

Any changes made to configuration values are local to the cursor object and held in memory only until they're written out to the filesystem using the save() and commit() methods.

Changes performed in one cursor instance are not reflected in another, unless the first instance writes those changes to the filesystem and the other instance explicitly (re)loads the affected configuration files.

Example
const ctx = cursor(…);
 
 // Enumerate configuration files
 ctx.configs();
@@ -146,4 +146,4 @@
 …
 
 // Delete 'disabled' option in first wifi-iface section
-ctx.set('wireless', '@wifi-iface[0]', 'disabled', '');

unload(config) → {boolean}nullable

Explicitly unload configuration file.

The unload() function forcibly discards a loaded configuration state from the cursor so that the next attempt to read or modify that configuration will load it anew from the file system.

Returns true if the configuration was successfully unloaded.

Returns false if the configuration was not loaded to begin with.

Returns null on error, e.g. if the requested configuration does not exist.

Parameters:
NameTypeDescription
configstring

The name of the configuration file to unload.

Returns: boolean

Type Definitions

ChangeRecord :string[]

A uci change record is a plain array containing the change operation name as first element, the affected section ID as second argument and an optional third and fourth argument whose meanings depend on the operation.

Properties
NameTypeDescription
0string

The operation name - may be one of add, set, remove, order, list-add, list-del or rename.

1string

The section ID targeted by the operation.

2string

The meaning of the third element depends on the operation.

  • For add it is type of the section that has been added
  • For set it either is the option name if a fourth element exists, or the type of a named section which has been added when the change entry only contains three elements.
  • For remove it contains the name of the option that has been removed.
  • For order it specifies the new sort index of the section.
  • For list-add it contains the name of the list option a new value has been added to.
  • For list-del it contains the name of the list option a value has been removed from.
  • For rename it contains the name of the option that has been renamed if a fourth element exists, else it contains the new name a section has been renamed to if the change entry only contains three elements.
4string

The meaning of the fourth element depends on the operation.

  • For set it is the value an option has been set to.
  • For list-add it is the new value that has been added to a list option.
  • For rename it is the new name of an option that has been renamed.

SectionCallback(section) :function

The sections callback is invoked for each section found within the given configuration and receives the section object and its associated name as arguments.

Parameters:
NameTypeDescription
sectionSectionObject

The section object.

SectionObject :Object<string: (boolean|number|string|string[])>

A section object represents the options and their corresponding values enclosed within a configuration section, as well as some additional meta data such as sort indexes and internal ID.

Any internal metadata fields are prefixed with a dot which isn't an allowed character for normal option names.

Properties
NameTypeDescription
.anonymousboolean

The .anonymous property specifies whether the configuration is anonymous (true) or named (false).

.indexnumber

The .index property specifies the sort order of the section.

.namestring

The .name property holds the name of the section object. It may be either an anonymous ID in the form cfgXXXXXX with X being a hexadecimal digit or a string holding the name of the section.

.typestring

The .type property contains the type of the corresponding uci section.

*string | string[]

A section object may contain an arbitrary number of further properties representing the uci option enclosed in the section.

All option property names will be in the form [A-Za-z0-9_]+ and either contain a string value or an array of strings, in case the underlying option is an UCI list.

Table of Contents
\ No newline at end of file +ctx.set('wireless', '@wifi-iface[0]', 'disabled', '');

unload(config) → {boolean}nullable

Explicitly unload configuration file.

The unload() function forcibly discards a loaded configuration state from the cursor so that the next attempt to read or modify that configuration will load it anew from the file system.

Returns true if the configuration was successfully unloaded.

Returns false if the configuration was not loaded to begin with.

Returns null on error, e.g. if the requested configuration does not exist.

Parameters:
NameTypeDescription
configstring

The name of the configuration file to unload.

Returns: boolean

Type Definitions

ChangeRecord :string[]

A uci change record is a plain array containing the change operation name as first element, the affected section ID as second argument and an optional third and fourth argument whose meanings depend on the operation.

Properties
NameTypeDescription
0string

The operation name - may be one of add, set, remove, order, list-add, list-del or rename.

1string

The section ID targeted by the operation.

2string

The meaning of the third element depends on the operation.

  • For add it is type of the section that has been added
  • For set it either is the option name if a fourth element exists, or the type of a named section which has been added when the change entry only contains three elements.
  • For remove it contains the name of the option that has been removed.
  • For order it specifies the new sort index of the section.
  • For list-add it contains the name of the list option a new value has been added to.
  • For list-del it contains the name of the list option a value has been removed from.
  • For rename it contains the name of the option that has been renamed if a fourth element exists, else it contains the new name a section has been renamed to if the change entry only contains three elements.
4string

The meaning of the fourth element depends on the operation.

  • For set it is the value an option has been set to.
  • For list-add it is the new value that has been added to a list option.
  • For rename it is the new name of an option that has been renamed.

SectionCallback(section) :function

The sections callback is invoked for each section found within the given configuration and receives the section object and its associated name as arguments.

Parameters:
NameTypeDescription
sectionSectionObject

The section object.

SectionObject :Object<string: (boolean|number|string|string[])>

A section object represents the options and their corresponding values enclosed within a configuration section, as well as some additional meta data such as sort indexes and internal ID.

Any internal metadata fields are prefixed with a dot which isn't an allowed character for normal option names.

Properties
NameTypeDescription
.anonymousboolean

The .anonymous property specifies whether the configuration is anonymous (true) or named (false).

.indexnumber

The .index property specifies the sort order of the section.

.namestring

The .name property holds the name of the section object. It may be either an anonymous ID in the form cfgXXXXXX with X being a hexadecimal digit or a string holding the name of the section.

.typestring

The .type property contains the type of the corresponding uci section.

*string | string[]

A section object may contain an arbitrary number of further properties representing the uci option enclosed in the section.

All option property names will be in the form [A-Za-z0-9_]+ and either contain a string value or an array of strings, in case the underlying option is an UCI list.

Table of Contents
\ No newline at end of file diff --git a/module-uci.html b/module-uci.html index 5d91e74e..c905a2bd 100644 --- a/module-uci.html +++ b/module-uci.html @@ -1,6 +1,6 @@ Module: uci

OpenWrt UCI configuration

The uci module provides access to the native OpenWrt libuci API for reading and manipulating UCI configuration files.

Functions can be individually imported and directly accessed using the named import syntax:

import { cursor } from 'uci';
+    

OpenWrt UCI configuration

The uci module provides access to the native OpenWrt libuci API for reading and manipulating UCI configuration files.

Functions can be individually imported and directly accessed using the named import syntax:

import { cursor } from 'uci';
 
 let ctx = cursor();
 let hostname = ctx.get_first('system', 'system', 'hostname');
@@ -13,4 +13,4 @@
 ctx.set("not_existing_config", "test", "1");
 
 // Print error (should yield "Entry not found")
-print(ctx.error(), "\n");
Table of Contents
\ No newline at end of file +print(ctx.error(), "\n");
Table of Contents
\ No newline at end of file diff --git a/tutorial-01-usage.html b/tutorial-01-usage.html index b149d73e..eaffaabd 100644 --- a/tutorial-01-usage.html +++ b/tutorial-01-usage.html @@ -1,8 +1,8 @@ Tutorial: Usage

Usage

The ucode command line utility provides a set of options and arguments for executing and compiling ucode programs. Here is a detailed explanation of each option and its usage:

  • -h: Display the help message, which provides an overview of the available options and their usage.

  • -e "expression": Execute the given expression as a ucode program. This option allows you to provide a single-line ucode expression for immediate execution.

  • -p "expression": Execute the given expression as a ucode program and print the result after execution.

  • -c [-s] [-o output.uc] input.uc [input2.uc ...]: Compile the specified source file(s) to bytecode instead of executing them. By default, the compiled bytecode is written to ./uc.out. The -s option omits debug information, reducing the size of the compiled bytecode. The -o option allows specifying the output file path for the compiled bytecode.

  • -t: Enable VM (Virtual Machine) execution tracing. This option enables tracing of the ucode program's execution, providing detailed information for debugging purposes.

  • -g interval: Perform periodic garbage collection at regular intervals defined by the interval parameter. Garbage collection is a memory management process that frees up memory occupied by objects that are no longer in use.

  • -S: Enable strict mode, which enforces strict adherence to ucode language rules and prevents the use of certain potentially error-prone or unsafe language features.

  • -R: Process source file(s) as raw script code. This is the default mode of operation, where the ucode interpreter treats the source files as direct ucode script code.

  • -T[flag,flag,...]: Process the source file(s) as templates instead of raw script code. This option enables the usage of Jinja-like templates with embedded ECMAScript 6 code. The flags provide additional control over template processing, such as preserving leading whitespace or trailing newlines.

  • -D [name=]value: Define a global variable in the ucode program. If the name parameter is omitted, a JSON dictionary is expected as the value, where each property becomes a global variable with its corresponding value. If name is specified, it defines a global variable with the provided value, parsed as JSON or as a literal string if JSON parsing fails.

  • -F [name=]path: Similar to the -D option, but reads the value from a file specified by the path parameter. The file must contain a single, well-formed JSON dictionary.

  • -U name: Undefine the given global variable name. This option removes the specified global variable from the ucode program's scope.

  • -l [name=]library: Preload the specified library for use in the ucode program. Optionally, the library can be aliased to a different name within the program.

  • -L pattern: Prepend the provided pattern to the default library search paths. This option allows specifying custom paths for loading libraries. If the pattern does not contain an asterisk (*), it is added twice, once with /*.so and once with /*.uc appended to it.

Examples

Here are some examples showcasing the invocation of the ucode program with different options:

  1. Execute a ucode expression:

    ucode -e "print('Hello, World!\n');"
    +    

    Usage

    The ucode command line utility provides a set of options and arguments for executing and compiling ucode programs. Here is a detailed explanation of each option and its usage:

    • -h: Display the help message, which provides an overview of the available options and their usage.

    • -e "expression": Execute the given expression as a ucode program. This option allows you to provide a single-line ucode expression for immediate execution.

    • -p "expression": Execute the given expression as a ucode program and print the result after execution.

    • -c [-s] [-o output.uc] input.uc [input2.uc ...]: Compile the specified source file(s) to bytecode instead of executing them. By default, the compiled bytecode is written to ./uc.out. The -s option omits debug information, reducing the size of the compiled bytecode. The -o option allows specifying the output file path for the compiled bytecode.

    • -t: Enable VM (Virtual Machine) execution tracing. This option enables tracing of the ucode program's execution, providing detailed information for debugging purposes.

    • -g interval: Perform periodic garbage collection at regular intervals defined by the interval parameter. Garbage collection is a memory management process that frees up memory occupied by objects that are no longer in use.

    • -S: Enable strict mode, which enforces strict adherence to ucode language rules and prevents the use of certain potentially error-prone or unsafe language features.

    • -R: Process source file(s) as raw script code. This is the default mode of operation, where the ucode interpreter treats the source files as direct ucode script code.

    • -T[flag,flag,...]: Process the source file(s) as templates instead of raw script code. This option enables the usage of Jinja-like templates with embedded ECMAScript 6 code. The flags provide additional control over template processing, such as preserving leading whitespace or trailing newlines.

    • -D [name=]value: Define a global variable in the ucode program. If the name parameter is omitted, a JSON dictionary is expected as the value, where each property becomes a global variable with its corresponding value. If name is specified, it defines a global variable with the provided value, parsed as JSON or as a literal string if JSON parsing fails.

    • -F [name=]path: Similar to the -D option, but reads the value from a file specified by the path parameter. The file must contain a single, well-formed JSON dictionary.

    • -U name: Undefine the given global variable name. This option removes the specified global variable from the ucode program's scope.

    • -l [name=]library: Preload the specified library for use in the ucode program. Optionally, the library can be aliased to a different name within the program.

    • -L pattern: Prepend the provided pattern to the default library search paths. This option allows specifying custom paths for loading libraries. If the pattern does not contain an asterisk (*), it is added twice, once with /*.so and once with /*.uc appended to it.

    Examples

    Here are some examples showcasing the invocation of the ucode program with different options:

    1. Execute a ucode expression:

      ucode -e "print('Hello, World!\n');"
       
    2. Execute a ucode expression and print the result:

      ucode -p "2 ** 3"
       
    3. Execute a ucode program from a source file:

      ucode program.uc
       
    4. Compile a ucode program to bytecode:

      ucode -c program.uc
       
    5. Compile a ucode program to bytecode with a specified output file:

      ucode -c -o compiled.uc program.uc
      -
    Table of Contents
    \ No newline at end of file +
Table of Contents
\ No newline at end of file diff --git a/tutorial-02-syntax.html b/tutorial-02-syntax.html index 5c885ebd..51a99826 100644 --- a/tutorial-02-syntax.html +++ b/tutorial-02-syntax.html @@ -1,6 +1,6 @@ Tutorial: Syntax

Syntax

The ucode programming language features a syntax that closely resembles ECMAScript 6. However, the ucode interpreter supports two distinct syntax modes: template mode and raw mode.

In template mode, ucode consumes Jinja-like templates that allow for the embedding of script code within the template structure. This mode enables the combination of expressive template constructs with JavaScript like functionality.

On the other hand, raw mode in ucode directly consumes ECMAScript 6-like syntax without any template-specific markup. This mode is mainly useful to develop standalone applications or libraries.

Template mode

By default, ucode is executed in raw mode, means it expects a given source file to only contain script code. By invoking the ucode interpreter with the -T flag or by using the utpl alias, the ucode interpreter is switched into template mode where the source file is expected to be a plaintext file containing template blocks containing ucode script expressions or comments.

Block types

There are three kinds of blocks; expression blocks, statement blocks and comment blocks. The former two embed code logic using ucode's JavaScript-like syntax while the latter comment block type is simply discarded during processing.

1. Statement block

Statement blocks are enclosed in an opening {% and a closing %} tag and may contain any number of script code statements, even entire programs.

It is allowed to omit the closing %} of a statement block to parse the entire remaining source text after the opening tag as ucode script.

By default, statement blocks produce no output and the entire block is reduced to an empty string during template evaluation but contained script code might invoke functions such as print() to explicitly output contents.

For example the following template would result in The epoch is odd or The epoch is even, depending on the current epoch value:

The epoch is {% if (time() % 2): %}odd{% else %}even{% endif %}!

2. Expression block

Expression blocks are enclosed in an opening {{ and a closing }} tag and may only contain a single expression statement (multiple expressions may be chained with comma). The implicit result of the rightmost evaluated expression is used as output when processing the block.

For example the template Hello world, {{ getenv("USER") }}! would result in the output "Hello world, user!" where user would correspond to the name of the current user executing the ucode interpreter.

3. Comment block

Comment blocks, which are denoted with an opening {# and a closing #} tag may contain arbitrary text except the closing #} tag itself. Comments blocks are completely stripped during processing and are replaced with an empty string.

The following example template would result in the output "Hello world":

Hello {# mad #}word

Whitespace handling

Each block start tag may be suffixed with a dash to strip any whitespace before the block and likewise any block end tag may be prefixed with a dash to strip any whitespace following the block.

Without using whitespace stripping, the following example:

This is a first line
+    

Syntax

The ucode programming language features a syntax that closely resembles ECMAScript 6. However, the ucode interpreter supports two distinct syntax modes: template mode and raw mode.

In template mode, ucode consumes Jinja-like templates that allow for the embedding of script code within the template structure. This mode enables the combination of expressive template constructs with JavaScript like functionality.

On the other hand, raw mode in ucode directly consumes ECMAScript 6-like syntax without any template-specific markup. This mode is mainly useful to develop standalone applications or libraries.

Template mode

By default, ucode is executed in raw mode, means it expects a given source file to only contain script code. By invoking the ucode interpreter with the -T flag or by using the utpl alias, the ucode interpreter is switched into template mode where the source file is expected to be a plaintext file containing template blocks containing ucode script expressions or comments.

Block types

There are three kinds of blocks; expression blocks, statement blocks and comment blocks. The former two embed code logic using ucode's JavaScript-like syntax while the latter comment block type is simply discarded during processing.

1. Statement block

Statement blocks are enclosed in an opening {% and a closing %} tag and may contain any number of script code statements, even entire programs.

It is allowed to omit the closing %} of a statement block to parse the entire remaining source text after the opening tag as ucode script.

By default, statement blocks produce no output and the entire block is reduced to an empty string during template evaluation but contained script code might invoke functions such as print() to explicitly output contents.

For example the following template would result in The epoch is odd or The epoch is even, depending on the current epoch value:

The epoch is {% if (time() % 2): %}odd{% else %}even{% endif %}!

2. Expression block

Expression blocks are enclosed in an opening {{ and a closing }} tag and may only contain a single expression statement (multiple expressions may be chained with comma). The implicit result of the rightmost evaluated expression is used as output when processing the block.

For example the template Hello world, {{ getenv("USER") }}! would result in the output "Hello world, user!" where user would correspond to the name of the current user executing the ucode interpreter.

3. Comment block

Comment blocks, which are denoted with an opening {# and a closing #} tag may contain arbitrary text except the closing #} tag itself. Comments blocks are completely stripped during processing and are replaced with an empty string.

The following example template would result in the output "Hello world":

Hello {# mad #}word

Whitespace handling

Each block start tag may be suffixed with a dash to strip any whitespace before the block and likewise any block end tag may be prefixed with a dash to strip any whitespace following the block.

Without using whitespace stripping, the following example:

This is a first line
 {% for (x in [1, 2, 3]): %}
 This is item {{ x }}.
 {% endfor %}
@@ -224,4 +224,4 @@
 
   print(a);              // { }
 %}
-

5.7. Precedence

Operator precedence determines the order in which operators are evaluated in an expression. In ucode, operators have different precedence levels, as outline in the table below.

PrecedenceOperator typeAssociativity
19Grouping ( … )n/a
18Property access … . …left-to-right
18Optional chaining … ?. …left-to-right
18Computed propery access … [ … ]n/a
18Function call … (…)n/a
17Postfix increment … ++n/a
17Postfix decrement … --n/a
16Logical not ! …n/a
16Bitwise not ~ …n/a
16Unary plus + …n/a
16Unary negation - …n/a
16Prefix increment ++ …n/a
16Prefix decrement -- …n/a
16Property deletion delete …n/a
15Exponentiation … ** …right-to-left
14Multiplication … * …left-to-right
14Division … / …left-to-right
14Remainder … % …left-to-right
13Addition … + …left-to-right
13Substraction … - …left-to-right
12Bitwise left shift … << …left-to-right
12Bitwise right shift … >> …left-to-right
11Less than … < …left-to-right
11Less than or equal … <= …left-to-right
11Greater than … > …left-to-right
11Greater than or equal … >= …left-to-right
11In … in …left-to-right
10Equality … == …left-to-right
10Inequality … != …left-to-right
10Strict equality … === …left-to-right
10Strict inequality … !== …left-to-right
9Bitwise AND … & …left-to-right
8Bitwise XOR … ^ …left-to-right
7Bitwise OR … | …left-to-right
6Logical AND … && …left-to-right
5Logical OR … || …left-to-right
5Nullish coalescing … ?? …left-to-right
4Assignment … = …right-to-left
4Assignment … += …right-to-left
4Assignment … -= …right-to-left
4Assignment … **= …right-to-left
4Assignment … *= …right-to-left
4Assignment … /= …right-to-left
4Assignment … %= …right-to-left
4Assignment … <<= …right-to-left
4Assignment … >>= …right-to-left
4Assignment … &= …right-to-left
4Assignment … ^= …right-to-left
4Assignment … |= …right-to-left
4Assignment … &&= …right-to-left
4Assignment … ||= …right-to-left
4Assignment … ??= …right-to-left
3Ternary … ? … : …right-to-left
2Arrow … => …right-to-left
2Spread ... …n/a
1Sequence … , …left-to-right

Operators with a higher precedence value are evaluated before operators with a lower precedence value. When operators have the same precedence, their associativity determines the order of evaluation (e.g., left-to-right or right-to-left).

Table of Contents
\ No newline at end of file +

5.7. Precedence

Operator precedence determines the order in which operators are evaluated in an expression. In ucode, operators have different precedence levels, as outline in the table below.

PrecedenceOperator typeAssociativity
19Grouping ( … )n/a
18Property access … . …left-to-right
18Optional chaining … ?. …left-to-right
18Computed propery access … [ … ]n/a
18Function call … (…)n/a
17Postfix increment … ++n/a
17Postfix decrement … --n/a
16Logical not ! …n/a
16Bitwise not ~ …n/a
16Unary plus + …n/a
16Unary negation - …n/a
16Prefix increment ++ …n/a
16Prefix decrement -- …n/a
16Property deletion delete …n/a
15Exponentiation … ** …right-to-left
14Multiplication … * …left-to-right
14Division … / …left-to-right
14Remainder … % …left-to-right
13Addition … + …left-to-right
13Substraction … - …left-to-right
12Bitwise left shift … << …left-to-right
12Bitwise right shift … >> …left-to-right
11Less than … < …left-to-right
11Less than or equal … <= …left-to-right
11Greater than … > …left-to-right
11Greater than or equal … >= …left-to-right
11In … in …left-to-right
10Equality … == …left-to-right
10Inequality … != …left-to-right
10Strict equality … === …left-to-right
10Strict inequality … !== …left-to-right
9Bitwise AND … & …left-to-right
8Bitwise XOR … ^ …left-to-right
7Bitwise OR … | …left-to-right
6Logical AND … && …left-to-right
5Logical OR … || …left-to-right
5Nullish coalescing … ?? …left-to-right
4Assignment … = …right-to-left
4Assignment … += …right-to-left
4Assignment … -= …right-to-left
4Assignment … **= …right-to-left
4Assignment … *= …right-to-left
4Assignment … /= …right-to-left
4Assignment … %= …right-to-left
4Assignment … <<= …right-to-left
4Assignment … >>= …right-to-left
4Assignment … &= …right-to-left
4Assignment … ^= …right-to-left
4Assignment … |= …right-to-left
4Assignment … &&= …right-to-left
4Assignment … ||= …right-to-left
4Assignment … ??= …right-to-left
3Ternary … ? … : …right-to-left
2Arrow … => …right-to-left
2Spread ... …n/a
1Sequence … , …left-to-right

Operators with a higher precedence value are evaluated before operators with a lower precedence value. When operators have the same precedence, their associativity determines the order of evaluation (e.g., left-to-right or right-to-left).

Table of Contents
\ No newline at end of file diff --git a/tutorial-03-memory.html b/tutorial-03-memory.html index c90c1950..470668ca 100644 --- a/tutorial-03-memory.html +++ b/tutorial-03-memory.html @@ -1,6 +1,6 @@ Tutorial: Memory Management

Memory Management

The ucode scripting language utilizes a reference count-based garbage collector as its primary method of memory management. When assigning an array or object value, the reference count is incremented. When a local variable holding a reference goes out of scope, the reference count is decremented. If the reference count reaches zero, a recursive traversal is performed to decrease the reference count of any nested references. Once the traversal is complete, the top-level array or object structure is freed.

Example 1:

x = [ { a: 1 }, { b: 2 }, { c: 3 } ];
+    

Memory Management

The ucode scripting language utilizes a reference count-based garbage collector as its primary method of memory management. When assigning an array or object value, the reference count is incremented. When a local variable holding a reference goes out of scope, the reference count is decremented. If the reference count reaches zero, a recursive traversal is performed to decrease the reference count of any nested references. Once the traversal is complete, the top-level array or object structure is freed.

Example 1:

x = [ { a: 1 }, { b: 2 }, { c: 3 } ];
 // `x` holds a reference to `[...]` (refcount 1)
 // `x[0]` holds a reference to `{ a: 1 }` (refcount 1)
 // `x[1]` holds a reference to `{ b: 2 }` (refcount 1)
@@ -31,4 +31,4 @@
 // `a` holds a reference to itself (refcount 1)
 

Example 3:

x = { y: { z: [ ] } }; x.y.z = x;
 // `x` holds a reference to itself through `x.y.z` (refcount 1)
-

In these examples, cyclic references are created where objects or arrays point back to themselves or create a circular chain. Since each element within the cycle maintains a reference, the reference count for each object or array never reaches zero, resulting in a memory leak. The reference count-based garbage collector cannot automatically reclaim memory in such cases.

To address cyclic structures and avoid memory leaks, ucode provides a secondary mark-and-sweep garbage collector. This collector can be enabled by passing the -g flag to the ucode interpreter or manually triggered using the gc() function during runtime. The mark-and-sweep collector identifies and frees unreachable objects, including those involved in cyclic references.

Table of Contents
\ No newline at end of file +

In these examples, cyclic references are created where objects or arrays point back to themselves or create a circular chain. Since each element within the cycle maintains a reference, the reference count for each object or array never reaches zero, resulting in a memory leak. The reference count-based garbage collector cannot automatically reclaim memory in such cases.

To address cyclic structures and avoid memory leaks, ucode provides a secondary mark-and-sweep garbage collector. This collector can be enabled by passing the -g flag to the ucode interpreter or manually triggered using the gc() function during runtime. The mark-and-sweep collector identifies and frees unreachable objects, including those involved in cyclic references.

Table of Contents
\ No newline at end of file