diff --git a/index.html b/index.html index dd5bf4d3..40902814 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 +
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/lib.c.html b/lib.c.html index b7e80d5e..281c7395 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
@@ -5930,4 +5930,4 @@
 
 	return NULL;
 }
-
Table of Contents
\ No newline at end of file +
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/lib_debug.c.html b/lib_debug.c.html index a4a73428..7b974f16 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 +
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/lib_fs.c.html b/lib_fs.c.html index de68df54..dc6b3040 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 +
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/lib_log.c.html b/lib_log.c.html index 31702e20..f6c425db 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 +
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/lib_math.c.html b/lib_math.c.html index 7452bde5..6014eb32 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 +
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/lib_struct.c.html b/lib_struct.c.html index 92eb050a..880956f8 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 +
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/lib_uci.c.html b/lib_uci.c.html index c890c687..07ca8c7d 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 +
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-core.html b/module-core.html index 7a9b008e..a528c028 100644 --- a/module-core.html +++ b/module-core.html @@ -1,6 +1,6 @@ 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)
@@ -306,4 +306,4 @@
 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)

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

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.

Source

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)

Source
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-debug.html b/module-debug.html index 30cc7bf1..b7674ba1 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.

ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-fs.dir.html b/module-fs.dir.html index 1c2044d8..c0752514 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
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-fs.file.html b/module-fs.file.html index ee107431..d2d3ad6d 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");
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-fs.html b/module-fs.html index d1bad742..8ce94027 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.).

ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-fs.proc.html b/module-fs.proc.html index 89b3bc3c..833aad3b 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");
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-log.html b/module-log.html index 2d0facbf..9cb8c0be 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.
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-math.html b/module-math.html index 2fb0b74d..d7f7c1e9 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.

ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-struct.html b/module-struct.html index e82d8312..419ca31a 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 ]
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-struct.instance.html b/module-struct.instance.html index e85d8fe9..9351f865 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(…);
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-uci.cursor.html b/module-uci.cursor.html index 08cbea1a..9420bc34 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.

ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-uci.html b/module-uci.html index 079d5741..b89caccb 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");
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/tutorial-01-usage.html b/tutorial-01-usage.html index f67481f6..65091332 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 +
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/tutorial-02-syntax.html b/tutorial-02-syntax.html index 18eb0da4..33eb70d5 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).

ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/tutorial-03-memory.html b/tutorial-03-memory.html index 8fc977f8..c8f0e6ab 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.

ucode Documentation
Table of Contents
\ No newline at end of file