diff --git a/index.html b/index.html index 7782bc0..9384297 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 e0aa938..a1e6f67 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
@@ -5982,4 +5982,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 7e5e6f3..be1f002 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 2e3783a..e0ec973 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
@@ -2883,4 +2883,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 2c7fac2..6f5ae6d 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 d647078..938d755 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_socket.c.html b/lib_socket.c.html index 59631e0..6bea775 100644 --- a/lib_socket.c.html +++ b/lib_socket.c.html @@ -1,6 +1,6 @@ Source: lib/socket.c

lib_socket.c

/*
+    

lib_socket.c

/*
  * Copyright (C) 2024 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -5230,4 +5230,4 @@
 
 	uc_type_declare(vm, "socket", socket_fns, close_socket);
 }
-
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 18c7465..3775e3c 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 49d6eae..1796ece 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
@@ -1872,4 +1872,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/lib_uloop.c.html b/lib_uloop.c.html index e143633..39557ef 100644 --- a/lib_uloop.c.html +++ b/lib_uloop.c.html @@ -1,6 +1,6 @@ Source: lib/uloop.c

lib_uloop.c

/*
+    

lib_uloop.c

/*
  * Copyright (C) 2022 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -2447,4 +2447,4 @@
 		uloop_fd_add(&signal_handle.ufd, ULOOP_READ);
 	}
 }
-
Table of Contents
\ No newline at end of file +
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/lib_zlib.c.html b/lib_zlib.c.html index d83a820..ec96c73 100644 --- a/lib_zlib.c.html +++ b/lib_zlib.c.html @@ -1,6 +1,6 @@ Source: lib/zlib.c

lib_zlib.c

/*
+    

lib_zlib.c

/*
  * Copyright (C) 2024 Thibaut VARÈNE <hacks@slashdirt.org>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -493,4 +493,4 @@
 	ADD_CONST(Z_BEST_COMPRESSION);
 	ADD_CONST(Z_DEFAULT_COMPRESSION);
 }
-
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 f07d04f..c6317d0 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)
@@ -337,4 +337,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:
NameTypeDescription
x*(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:
NameTypeDescription
subject*

The subject to match against the wildcard pattern.

patternstring

The wildcard pattern.

nocaseboolean(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 preceding 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 preceding 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 d3d7ef7..d5b648f 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:
NameTypeDescription
levelnumber(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:
NameTypeDescription
levelnumber(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*(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:
NameTypeDescription
levelnumber(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:
NameTypeDescription
levelnumber(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:
NameTypeDescription
levelnumber(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*(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:
NameTypeDescription
levelnumber(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 c823890..5a27e8d 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 96d957b..117e788 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

truncate(offsetopt) → {boolean}nullable

Truncate file to a given size

Returns true if the file was successfully truncated.

Returns null if an error occurred.

Parameters:
NameTypeDescription
offsetnumber(optional, default: 0)

The offset in bytes.

Returns: boolean

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 9fa7f01..04fa763 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 0f99647..274f683 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 d78bfd0..d6dd0f9 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 f8aedbc..0f9ef48 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-socket.html b/module-socket.html index 248ed3d..78f453c 100644 --- a/module-socket.html +++ b/module-socket.html @@ -1,6 +1,6 @@ Module: socket

Socket Module

The socket module provides functions for interacting with sockets.

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

import { AF_INET, SOCK_STREAM, create as socket } from 'socket';
+    

Socket Module

The socket module provides functions for interacting with sockets.

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

import { AF_INET, SOCK_STREAM, create as socket } from 'socket';
 
 let sock = socket(AF_INET, SOCK_STREAM, 0);
 sock.connect('192.168.1.1', 80);
@@ -84,4 +84,4 @@
 const address4 = sockaddr({ address: '192.168.0.1', port: 8080 });
 
 // Convert a path value to a UNIX domain socket address
-const address5 = sockaddr('/var/run/daemon.sock');

Type Definitions

AddressInfo: Object

Represents a network address information object returned by addrinfo().

Properties
NameTypeAttributesDefaultDescription
addrsocket.SocketAddress

A socket address structure.

canonnamestringoptionalnull(optional, default: null)

The canonical hostname associated with the address.

familynumber

The address family (e.g., 2 for AF_INET, 10 for AF_INET6).

flagsnumber

Additional flags indicating properties of the address.

protocolnumber

The protocol number.

socktypenumber

The socket type (e.g., 1 for SOCK_STREAM, 2 for SOCK_DGRAM).

PollSpec: Array

Represents a poll state serving as input parameter and return value type for poll().

Properties
NameTypeDescription
0socket

The polled socket instance.

1number

Requested or returned status flags of the polled socket instance.

Address Families

Constants representing address families and socket domains.

Properties
NameTypeDescription
AF_UNSPECnumber

Unspecified address family.

AF_UNIXnumber

UNIX domain sockets.

AF_INETnumber

IPv4 Internet protocols.

AF_INET6number

IPv6 Internet protocols.

AF_PACKETnumber

Low-level packet interface.

Address Info Flags

The AI_* flags may be passed as bitwise OR-ed number in the flags property of the hints dictionary argument of addrinfo().

Properties
NameTypeDescription
AI_ADDRCONFIGnumber

Address configuration flag.

AI_ALLnumber

Return IPv4 and IPv6 socket addresses.

AI_CANONIDNnumber

Canonicalize using the IDNA standard.

AI_CANONNAMEnumber

Fill in the canonical name field.

AI_IDNnumber

Enable IDN encoding.

AI_NUMERICHOSTnumber

Prevent hostname resolution.

AI_NUMERICSERVnumber

Prevent service name resolution.

AI_PASSIVEnumber

Use passive socket.

AI_V4MAPPEDnumber

Map IPv6 addresses to IPv4-mapped format.

IP Protocol Constants

The IPPROTO_IP constant specifies the IP protocol number and may be passed as third argument to create() as well as level argument value to getopt() and setopt().

The IP_* constants are option names recognized by getopt() and setopt(), in conjunction with the IPPROTO_IP socket level.

Properties
NameTypeDescription
IPPROTO_IPnumber

Dummy protocol for IP.

IP_ADD_MEMBERSHIPnumber

Add an IP group membership.

IP_ADD_SOURCE_MEMBERSHIPnumber

Add an IP group/source membership.

IP_BIND_ADDRESS_NO_PORTnumber

Bind to the device only.

IP_BLOCK_SOURCEnumber

Block IP group/source.

IP_DROP_MEMBERSHIPnumber

Drop an IP group membership.

IP_DROP_SOURCE_MEMBERSHIPnumber

Drop an IP group/source membership.

IP_FREEBINDnumber

Allow binding to an IP address not assigned to a network interface.

IP_HDRINCLnumber

Header is included with data.

IP_MSFILTERnumber

Filter IP multicast source memberships.

IP_MTUnumber

Path MTU discovery.

IP_MTU_DISCOVERnumber

Control Path MTU discovery.

IP_MULTICAST_ALLnumber

Receive all multicast packets.

IP_MULTICAST_IFnumber

Set outgoing interface for multicast packets.

IP_MULTICAST_LOOPnumber

Control multicast packet looping.

IP_MULTICAST_TTLnumber

Set time-to-live for outgoing multicast packets.

IP_NODEFRAGnumber

Don't fragment IP packets.

IP_OPTIONSnumber

Set/get IP options.

IP_PASSSECnumber

Pass security information.

IP_PKTINFOnumber

Receive packet information.

IP_RECVERRnumber

Receive all ICMP errors.

IP_RECVOPTSnumber

Receive all IP options.

IP_RECVORIGDSTADDRnumber

Receive original destination address of the socket.

IP_RECVTOSnumber

Receive IP TOS.

IP_RECVTTLnumber

Receive IP TTL.

IP_RETOPTSnumber

Set/get IP options.

IP_ROUTER_ALERTnumber

Receive ICMP msgs generated by router.

IP_TOSnumber

IP type of service and precedence.

IP_TRANSPARENTnumber

Transparent proxy support.

IP_TTLnumber

IP time-to-live.

IP_UNBLOCK_SOURCEnumber

Unblock IP group/source.

IPv6: Object

The IPPROTO_IPV6 constant specifies the IPv6 protocol number and may be passed as third argument to create() as well as level argument value to getopt() and setopt().

The IPV6_* constants are option names recognized by getopt() and setopt(), in conjunction with the IPPROTO_IPV6 socket level.

Properties
NameTypeDescription
IPPROTO_IPV6number

The IPv6 protocol.

IPV6_ADDRFORMnumber

Turn an AF_INET6 socket into a socket of a different address family. Only AF_INET is supported.

IPV6_ADDR_PREFERENCESnumber

Specify preferences for address selection.

IPV6_ADD_MEMBERSHIPnumber

Add an IPv6 group membership.

IPV6_AUTHHDRnumber

Set delivery of the authentication header control message for incoming datagrams.

IPV6_AUTOFLOWLABELnumber

Enable or disable automatic flow labels.

IPV6_DONTFRAGnumber

Control whether the socket allows IPv6 fragmentation.

IPV6_DROP_MEMBERSHIPnumber

Drop an IPv6 group membership.

IPV6_DSTOPTSnumber

Set delivery of the destination options control message for incoming datagrams.

IPV6_FLOWINFO_SENDnumber

Control whether flow information is sent.

IPV6_FLOWINFOnumber

Set delivery of the flow ID control message for incoming datagrams.

IPV6_FLOWLABEL_MGRnumber

Manage flow labels.

IPV6_FREEBINDnumber

Allow binding to an IP address not assigned to a network interface.

IPV6_HOPLIMITnumber

Set delivery of the hop limit control message for incoming datagrams.

IPV6_HOPOPTSnumber

Set delivery of the hop options control message for incoming datagrams.

IPV6_JOIN_ANYCASTnumber

Join an anycast group.

IPV6_LEAVE_ANYCASTnumber

Leave an anycast group.

IPV6_MINHOPCOUNTnumber

Set the minimum hop count.

IPV6_MTUnumber

Retrieve or set the MTU to be used for the socket.

IPV6_MTU_DISCOVERnumber

Control path-MTU discovery on the socket.

IPV6_MULTICAST_ALLnumber

Control whether the socket receives all multicast packets.

IPV6_MULTICAST_HOPSnumber

Set the multicast hop limit for the socket.

IPV6_MULTICAST_IFnumber

Set the device for outgoing multicast packets on the socket.

IPV6_MULTICAST_LOOPnumber

Control whether the socket sees multicast packets that it has sent itself.

IPV6_PKTINFOnumber

Set delivery of the IPV6_PKTINFO control message on incoming datagrams.

IPV6_RECVDSTOPTSnumber

Control receiving of the destination options control message.

IPV6_RECVERRnumber

Control receiving of asynchronous error options.

IPV6_RECVFRAGSIZEnumber

Control receiving of fragment size.

IPV6_RECVHOPLIMITnumber

Control receiving of hop limit.

IPV6_RECVHOPOPTSnumber

Control receiving of hop options.

IPV6_RECVORIGDSTADDRnumber

Control receiving of the original destination address.

IPV6_RECVPATHMTUnumber

Control receiving of path MTU.

IPV6_RECVPKTINFOnumber

Control receiving of packet information.

IPV6_RECVRTHDRnumber

Control receiving of routing header.

IPV6_RECVTCLASSnumber

Control receiving of traffic class.

IPV6_ROUTER_ALERT_ISOLATEnumber

Control isolation of router alert messages.

IPV6_ROUTER_ALERTnumber

Pass forwarded packets containing a router alert hop-by-hop option to this socket.

IPV6_RTHDRnumber

Set delivery of the routing header control message for incoming datagrams.

IPV6_RTHDRDSTOPTSnumber

Set delivery of the routing header destination options control message.

IPV6_TCLASSnumber

Set the traffic class.

IPV6_TRANSPARENTnumber

Enable transparent proxy support.

IPV6_UNICAST_HOPSnumber

Set the unicast hop limit for the socket.

IPV6_UNICAST_IFnumber

Set the interface for outgoing unicast packets.

IPV6_V6ONLYnumber

Restrict the socket to sending and receiving IPv6 packets only.

Message Flags

The MSG_* flag constants are commonly used in conjunction with the send() and recv() functions.

Properties
NameTypeDescription
MSG_CONFIRMnumber

Confirm path validity.

MSG_DONTROUTEnumber

Send without using routing tables.

MSG_DONTWAITnumber

Enables non-blocking operation.

MSG_EORnumber

End of record.

MSG_MOREnumber

Sender will send more.

MSG_NOSIGNALnumber

Do not generate SIGPIPE.

MSG_OOBnumber

Process out-of-band data.

MSG_FASTOPENnumber

Send data in TCP SYN.

MSG_CMSG_CLOEXECnumber

Sets the close-on-exec flag on the received file descriptor.

MSG_ERRQUEUEnumber

Receive errors from ICMP.

MSG_PEEKnumber

Peeks at incoming messages.

MSG_TRUNCnumber

Report if datagram truncation occurred.

MSG_WAITALLnumber

Wait for full message.

Name Info Constants

The NI_* flags may be passed as bitwise OR-ed number via the flags argument of nameinfo().

Properties
NameTypeDescription
NI_DGRAMnumber

Datagram socket type.

NI_IDNnumber

Enable IDN encoding.

NI_NAMEREQDnumber

Hostname resolution required.

NI_NOFQDNnumber

Do not force fully qualified domain name.

NI_NUMERICHOSTnumber

Return numeric form of the hostname.

NI_NUMERICSERVnumber

Return numeric form of the service name.

Packet Socket Constants

The SOL_PACKET constant specifies the packet socket level and may be passed as level argument value to getopt() and setopt().

Most PACKET_* constants are option argument values recognized by getopt() and setopt(), in conjunction with the SOL_PACKET socket level.

The constants PACKET_MR_PROMISC, PACKET_MR_MULTICAST and PACKET_MR_ALLMULTI are used in conjunction with the PACKET_ADD_MEMBERSHIP and PACKET_DROP_MEMBERSHIP options to specify the packet socket receive mode.

The constants PACKET_HOST, PACKET_BROADCAST, PACKET_MULTICAST, PACKET_OTHERHOST and PACKET_OUTGOING may be used as packet_type value in socket address structures.

Properties
NameTypeDescription
SOL_PACKETnumber

Socket options at the packet API level.

PACKET_ADD_MEMBERSHIPnumber

Add a multicast group membership.

PACKET_DROP_MEMBERSHIPnumber

Drop a multicast group membership.

PACKET_AUXDATAnumber

Receive auxiliary data (packet info).

PACKET_FANOUTnumber

Configure packet fanout.

PACKET_LOSSnumber

Retrieve the current packet loss statistics.

PACKET_RESERVEnumber

Reserve space for packet headers.

PACKET_RX_RINGnumber

Configure a receive ring buffer.

PACKET_STATISTICSnumber

Retrieve packet statistics.

PACKET_TIMESTAMPnumber

Retrieve packet timestamps.

PACKET_TX_RINGnumber

Configure a transmit ring buffer.

PACKET_VERSIONnumber

Set the packet protocol version.

PACKET_QDISC_BYPASSnumber

Bypass queuing discipline for outgoing packets.

PACKET_MR_PROMISCnumber

Enable promiscuous mode.

PACKET_MR_MULTICASTnumber

Receive multicast packets.

PACKET_MR_ALLMULTInumber

Receive all multicast packets.

PACKET_HOSTnumber

Receive packets destined for this host.

PACKET_BROADCASTnumber

Receive broadcast packets.

PACKET_MULTICASTnumber

Receive multicast packets.

PACKET_OTHERHOSTnumber

Receive packets destined for other hosts.

PACKET_OUTGOINGnumber

Transmit packets.

Poll Event Constants

The following constants represent event types for polling operations and are set or returned as part of a PollSpec tuple by the poll() function. When passed via an argument PollSpec to poll(), they specify the I/O events to watch for on the corresponding handle. When appearing in a PollSpec returned by poll(), they specify the I/O events that occurred on a watched handle.

Properties
NameTypeDescription
POLLINnumber

Data available to read.

POLLPRInumber

Priority data available to read.

POLLOUTnumber

Writable data available.

POLLERRnumber

Error condition.

POLLHUPnumber

Hang up.

POLLNVALnumber

Invalid request.

POLLRDHUPnumber

Peer closed or shutdown writing.

Shutdown Constants

The SHUT_* constants are passed as argument to the shutdown() function to specify which direction of a full duplex connection to shut down.

Properties
NameTypeDescription
SHUT_RDnumber

Disallow further receptions.

SHUT_WRnumber

Disallow further transmissions.

SHUT_RDWRnumber

Disallow further receptions and transmissions.

Socket Option Constants

The SOL_SOCKET constant is passed as level argument to the getopt() and setopt() functions in order to set or retrieve generic socket option values.

The SO_* constants are passed as option argument in conjunction with the SOL_SOCKET level to specify the specific option to get or set on the socket.

Properties
NameTypeDescription
SOL_SOCKETnumber

Socket options at the socket API level.

SO_ACCEPTCONNnumber

Reports whether socket listening is enabled.

SO_ATTACH_BPFnumber

Attach BPF program to socket.

SO_ATTACH_FILTERnumber

Attach a socket filter.

SO_ATTACH_REUSEPORT_CBPFnumber

Attach BPF program for cgroup and skb program reuseport hook.

SO_ATTACH_REUSEPORT_EBPFnumber

Attach eBPF program for cgroup and skb program reuseport hook.

SO_BINDTODEVICEnumber

Bind socket to a specific interface.

SO_BROADCASTnumber

Allow transmission of broadcast messages.

SO_BUSY_POLLnumber

Enable busy polling.

SO_DEBUGnumber

Enable socket debugging.

SO_DETACH_BPFnumber

Detach BPF program from socket.

SO_DETACH_FILTERnumber

Detach a socket filter.

SO_DOMAINnumber

Retrieves the domain of the socket.

SO_DONTROUTEnumber

Send packets directly without routing.

SO_ERRORnumber

Retrieves and clears the error status for the socket.

SO_INCOMING_CPUnumber

Retrieves the CPU number on which the last packet was received.

SO_INCOMING_NAPI_IDnumber

Retrieves the NAPI ID of the device.

SO_KEEPALIVEnumber

Enable keep-alive packets.

SO_LINGERnumber

Set linger on close.

SO_LOCK_FILTERnumber

Set or get the socket filter lock state.

SO_MARKnumber

Set the mark for packets sent through the socket.

SO_OOBINLINEnumber

Enables out-of-band data to be received in the normal data stream.

SO_PASSCREDnumber

Enable the receiving of SCM_CREDENTIALS control messages.

SO_PASSSECnumber

Enable the receiving of security context.

SO_PEEK_OFFnumber

Returns the number of bytes in the receive buffer without removing them.

SO_PEERCREDnumber

Retrieves the credentials of the foreign peer.

SO_PEERSECnumber

Retrieves the security context of the foreign peer.

SO_PRIORITYnumber

Set the protocol-defined priority for all packets.

SO_PROTOCOLnumber

Retrieves the protocol number.

SO_RCVBUFnumber

Set the receive buffer size.

SO_RCVBUFFORCEnumber

Set the receive buffer size forcefully.

SO_RCVLOWATnumber

Set the minimum number of bytes to process for input operations.

SO_RCVTIMEOnumber

Set the timeout for receiving data.

SO_REUSEADDRnumber

Allow the socket to be bound to an address that is already in use.

SO_REUSEPORTnumber

Enable duplicate address and port bindings.

SO_RXQ_OVFLnumber

Reports if the receive queue has overflown.

SO_SNDBUFnumber

Set the send buffer size.

SO_SNDBUFFORCEnumber

Set the send buffer size forcefully.

SO_SNDLOWATnumber

Set the minimum number of bytes to process for output operations.

SO_SNDTIMEOnumber

Set the timeout for sending data.

SO_TIMESTAMPnumber

Enable receiving of timestamps.

SO_TIMESTAMPNSnumber

Enable receiving of nanosecond timestamps.

SO_TYPEnumber

Retrieves the type of the socket (e.g., SOCK_STREAM).

Socket Types

The SOCK_* type and flag constants are used by create() to specify the type of socket to open. The accept() function recognizes the SOCK_NONBLOCK and SOCK_CLOEXEC flags and applies them to accepted peer sockets.

Properties
NameTypeDescription
SOCK_STREAMnumber

Provides sequenced, reliable, two-way, connection-based byte streams.

SOCK_DGRAMnumber

Supports datagrams (connectionless, unreliable messages of a fixed maximum length).

SOCK_RAWnumber

Provides raw network protocol access.

SOCK_PACKETnumber

Obsolete and should not be used.

SOCK_NONBLOCKnumber

Enables non-blocking operation.

SOCK_CLOEXECnumber

Sets the close-on-exec flag on the new file descriptor.

TCP Protocol Constants

The IPPROTO_TCP constant specifies the TCP protocol number and may be passed as third argument to create() as well as level argument value to getopt() and setopt().

The TCP_* constants are option argument values recognized by getopt() and setopt(), in conjunction with the IPPROTO_TCP socket level.

Properties
NameTypeDescription
IPPROTO_TCPnumber

TCP protocol.

TCP_CONGESTIONnumber

Set the congestion control algorithm.

TCP_CORKnumber

Delay packet transmission until full-sized packets are available.

TCP_DEFER_ACCEPTnumber

Delay accepting incoming connections until data arrives.

TCP_FASTOPENnumber

Enable TCP Fast Open.

TCP_FASTOPEN_CONNECTnumber

Perform TFO connect.

TCP_INFOnumber

Retrieve TCP statistics.

TCP_KEEPCNTnumber

Number of keepalive probes.

TCP_KEEPIDLEnumber

Time before keepalive probes begin.

TCP_KEEPINTVLnumber

Interval between keepalive probes.

TCP_LINGER2number

Lifetime of orphaned FIN_WAIT2 state sockets.

TCP_MAXSEGnumber

Maximum segment size.

TCP_NODELAYnumber

Disable Nagle's algorithm.

TCP_QUICKACKnumber

Enable quick ACKs.

TCP_SYNCNTnumber

Number of SYN retransmits.

TCP_USER_TIMEOUTnumber

Set the user timeout.

TCP_WINDOW_CLAMPnumber

Set the maximum window.

UDP Protocol Constants

The IPPROTO_UDP constant specifies the UDP protocol number and may be passed as third argument to create() as well as level argument value to getopt() and setopt().

The UDP_* constants are option argument values recognized by getopt() and setopt(), in conjunction with the IPPROTO_UDP socket level.

Properties
NameTypeDescription
IPPROTO_UDPnumber

UDP protocol.

UDP_CORKnumber

Cork data until flush.

Table of Contents
\ No newline at end of file +const address5 = sockaddr('/var/run/daemon.sock');

Type Definitions

AddressInfo: Object

Represents a network address information object returned by addrinfo().

Properties
NameTypeAttributesDefaultDescription
addrsocket.SocketAddress

A socket address structure.

canonnamestringoptionalnull(optional, default: null)

The canonical hostname associated with the address.

familynumber

The address family (e.g., 2 for AF_INET, 10 for AF_INET6).

flagsnumber

Additional flags indicating properties of the address.

protocolnumber

The protocol number.

socktypenumber

The socket type (e.g., 1 for SOCK_STREAM, 2 for SOCK_DGRAM).

PollSpec: Array

Represents a poll state serving as input parameter and return value type for poll().

Properties
NameTypeDescription
0socket

The polled socket instance.

1number

Requested or returned status flags of the polled socket instance.

Address Families

Constants representing address families and socket domains.

Properties
NameTypeDescription
AF_UNSPECnumber

Unspecified address family.

AF_UNIXnumber

UNIX domain sockets.

AF_INETnumber

IPv4 Internet protocols.

AF_INET6number

IPv6 Internet protocols.

AF_PACKETnumber

Low-level packet interface.

Address Info Flags

The AI_* flags may be passed as bitwise OR-ed number in the flags property of the hints dictionary argument of addrinfo().

Properties
NameTypeDescription
AI_ADDRCONFIGnumber

Address configuration flag.

AI_ALLnumber

Return IPv4 and IPv6 socket addresses.

AI_CANONIDNnumber

Canonicalize using the IDNA standard.

AI_CANONNAMEnumber

Fill in the canonical name field.

AI_IDNnumber

Enable IDN encoding.

AI_NUMERICHOSTnumber

Prevent hostname resolution.

AI_NUMERICSERVnumber

Prevent service name resolution.

AI_PASSIVEnumber

Use passive socket.

AI_V4MAPPEDnumber

Map IPv6 addresses to IPv4-mapped format.

IP Protocol Constants

The IPPROTO_IP constant specifies the IP protocol number and may be passed as third argument to create() as well as level argument value to getopt() and setopt().

The IP_* constants are option names recognized by getopt() and setopt(), in conjunction with the IPPROTO_IP socket level.

Properties
NameTypeDescription
IPPROTO_IPnumber

Dummy protocol for IP.

IP_ADD_MEMBERSHIPnumber

Add an IP group membership.

IP_ADD_SOURCE_MEMBERSHIPnumber

Add an IP group/source membership.

IP_BIND_ADDRESS_NO_PORTnumber

Bind to the device only.

IP_BLOCK_SOURCEnumber

Block IP group/source.

IP_DROP_MEMBERSHIPnumber

Drop an IP group membership.

IP_DROP_SOURCE_MEMBERSHIPnumber

Drop an IP group/source membership.

IP_FREEBINDnumber

Allow binding to an IP address not assigned to a network interface.

IP_HDRINCLnumber

Header is included with data.

IP_MSFILTERnumber

Filter IP multicast source memberships.

IP_MTUnumber

Path MTU discovery.

IP_MTU_DISCOVERnumber

Control Path MTU discovery.

IP_MULTICAST_ALLnumber

Receive all multicast packets.

IP_MULTICAST_IFnumber

Set outgoing interface for multicast packets.

IP_MULTICAST_LOOPnumber

Control multicast packet looping.

IP_MULTICAST_TTLnumber

Set time-to-live for outgoing multicast packets.

IP_NODEFRAGnumber

Don't fragment IP packets.

IP_OPTIONSnumber

Set/get IP options.

IP_PASSSECnumber

Pass security information.

IP_PKTINFOnumber

Receive packet information.

IP_RECVERRnumber

Receive all ICMP errors.

IP_RECVOPTSnumber

Receive all IP options.

IP_RECVORIGDSTADDRnumber

Receive original destination address of the socket.

IP_RECVTOSnumber

Receive IP TOS.

IP_RECVTTLnumber

Receive IP TTL.

IP_RETOPTSnumber

Set/get IP options.

IP_ROUTER_ALERTnumber

Receive ICMP msgs generated by router.

IP_TOSnumber

IP type of service and precedence.

IP_TRANSPARENTnumber

Transparent proxy support.

IP_TTLnumber

IP time-to-live.

IP_UNBLOCK_SOURCEnumber

Unblock IP group/source.

IPv6: Object

The IPPROTO_IPV6 constant specifies the IPv6 protocol number and may be passed as third argument to create() as well as level argument value to getopt() and setopt().

The IPV6_* constants are option names recognized by getopt() and setopt(), in conjunction with the IPPROTO_IPV6 socket level.

Properties
NameTypeDescription
IPPROTO_IPV6number

The IPv6 protocol.

IPV6_ADDRFORMnumber

Turn an AF_INET6 socket into a socket of a different address family. Only AF_INET is supported.

IPV6_ADDR_PREFERENCESnumber

Specify preferences for address selection.

IPV6_ADD_MEMBERSHIPnumber

Add an IPv6 group membership.

IPV6_AUTHHDRnumber

Set delivery of the authentication header control message for incoming datagrams.

IPV6_AUTOFLOWLABELnumber

Enable or disable automatic flow labels.

IPV6_DONTFRAGnumber

Control whether the socket allows IPv6 fragmentation.

IPV6_DROP_MEMBERSHIPnumber

Drop an IPv6 group membership.

IPV6_DSTOPTSnumber

Set delivery of the destination options control message for incoming datagrams.

IPV6_FLOWINFO_SENDnumber

Control whether flow information is sent.

IPV6_FLOWINFOnumber

Set delivery of the flow ID control message for incoming datagrams.

IPV6_FLOWLABEL_MGRnumber

Manage flow labels.

IPV6_FREEBINDnumber

Allow binding to an IP address not assigned to a network interface.

IPV6_HOPLIMITnumber

Set delivery of the hop limit control message for incoming datagrams.

IPV6_HOPOPTSnumber

Set delivery of the hop options control message for incoming datagrams.

IPV6_JOIN_ANYCASTnumber

Join an anycast group.

IPV6_LEAVE_ANYCASTnumber

Leave an anycast group.

IPV6_MINHOPCOUNTnumber

Set the minimum hop count.

IPV6_MTUnumber

Retrieve or set the MTU to be used for the socket.

IPV6_MTU_DISCOVERnumber

Control path-MTU discovery on the socket.

IPV6_MULTICAST_ALLnumber

Control whether the socket receives all multicast packets.

IPV6_MULTICAST_HOPSnumber

Set the multicast hop limit for the socket.

IPV6_MULTICAST_IFnumber

Set the device for outgoing multicast packets on the socket.

IPV6_MULTICAST_LOOPnumber

Control whether the socket sees multicast packets that it has sent itself.

IPV6_PKTINFOnumber

Set delivery of the IPV6_PKTINFO control message on incoming datagrams.

IPV6_RECVDSTOPTSnumber

Control receiving of the destination options control message.

IPV6_RECVERRnumber

Control receiving of asynchronous error options.

IPV6_RECVFRAGSIZEnumber

Control receiving of fragment size.

IPV6_RECVHOPLIMITnumber

Control receiving of hop limit.

IPV6_RECVHOPOPTSnumber

Control receiving of hop options.

IPV6_RECVORIGDSTADDRnumber

Control receiving of the original destination address.

IPV6_RECVPATHMTUnumber

Control receiving of path MTU.

IPV6_RECVPKTINFOnumber

Control receiving of packet information.

IPV6_RECVRTHDRnumber

Control receiving of routing header.

IPV6_RECVTCLASSnumber

Control receiving of traffic class.

IPV6_ROUTER_ALERT_ISOLATEnumber

Control isolation of router alert messages.

IPV6_ROUTER_ALERTnumber

Pass forwarded packets containing a router alert hop-by-hop option to this socket.

IPV6_RTHDRnumber

Set delivery of the routing header control message for incoming datagrams.

IPV6_RTHDRDSTOPTSnumber

Set delivery of the routing header destination options control message.

IPV6_TCLASSnumber

Set the traffic class.

IPV6_TRANSPARENTnumber

Enable transparent proxy support.

IPV6_UNICAST_HOPSnumber

Set the unicast hop limit for the socket.

IPV6_UNICAST_IFnumber

Set the interface for outgoing unicast packets.

IPV6_V6ONLYnumber

Restrict the socket to sending and receiving IPv6 packets only.

Message Flags

The MSG_* flag constants are commonly used in conjunction with the send() and recv() functions.

Properties
NameTypeDescription
MSG_CONFIRMnumber

Confirm path validity.

MSG_DONTROUTEnumber

Send without using routing tables.

MSG_DONTWAITnumber

Enables non-blocking operation.

MSG_EORnumber

End of record.

MSG_MOREnumber

Sender will send more.

MSG_NOSIGNALnumber

Do not generate SIGPIPE.

MSG_OOBnumber

Process out-of-band data.

MSG_FASTOPENnumber

Send data in TCP SYN.

MSG_CMSG_CLOEXECnumber

Sets the close-on-exec flag on the received file descriptor.

MSG_ERRQUEUEnumber

Receive errors from ICMP.

MSG_PEEKnumber

Peeks at incoming messages.

MSG_TRUNCnumber

Report if datagram truncation occurred.

MSG_WAITALLnumber

Wait for full message.

Name Info Constants

The NI_* flags may be passed as bitwise OR-ed number via the flags argument of nameinfo().

Properties
NameTypeDescription
NI_DGRAMnumber

Datagram socket type.

NI_IDNnumber

Enable IDN encoding.

NI_NAMEREQDnumber

Hostname resolution required.

NI_NOFQDNnumber

Do not force fully qualified domain name.

NI_NUMERICHOSTnumber

Return numeric form of the hostname.

NI_NUMERICSERVnumber

Return numeric form of the service name.

Packet Socket Constants

The SOL_PACKET constant specifies the packet socket level and may be passed as level argument value to getopt() and setopt().

Most PACKET_* constants are option argument values recognized by getopt() and setopt(), in conjunction with the SOL_PACKET socket level.

The constants PACKET_MR_PROMISC, PACKET_MR_MULTICAST and PACKET_MR_ALLMULTI are used in conjunction with the PACKET_ADD_MEMBERSHIP and PACKET_DROP_MEMBERSHIP options to specify the packet socket receive mode.

The constants PACKET_HOST, PACKET_BROADCAST, PACKET_MULTICAST, PACKET_OTHERHOST and PACKET_OUTGOING may be used as packet_type value in socket address structures.

Properties
NameTypeDescription
SOL_PACKETnumber

Socket options at the packet API level.

PACKET_ADD_MEMBERSHIPnumber

Add a multicast group membership.

PACKET_DROP_MEMBERSHIPnumber

Drop a multicast group membership.

PACKET_AUXDATAnumber

Receive auxiliary data (packet info).

PACKET_FANOUTnumber

Configure packet fanout.

PACKET_LOSSnumber

Retrieve the current packet loss statistics.

PACKET_RESERVEnumber

Reserve space for packet headers.

PACKET_RX_RINGnumber

Configure a receive ring buffer.

PACKET_STATISTICSnumber

Retrieve packet statistics.

PACKET_TIMESTAMPnumber

Retrieve packet timestamps.

PACKET_TX_RINGnumber

Configure a transmit ring buffer.

PACKET_VERSIONnumber

Set the packet protocol version.

PACKET_QDISC_BYPASSnumber

Bypass queuing discipline for outgoing packets.

PACKET_MR_PROMISCnumber

Enable promiscuous mode.

PACKET_MR_MULTICASTnumber

Receive multicast packets.

PACKET_MR_ALLMULTInumber

Receive all multicast packets.

PACKET_HOSTnumber

Receive packets destined for this host.

PACKET_BROADCASTnumber

Receive broadcast packets.

PACKET_MULTICASTnumber

Receive multicast packets.

PACKET_OTHERHOSTnumber

Receive packets destined for other hosts.

PACKET_OUTGOINGnumber

Transmit packets.

Poll Event Constants

The following constants represent event types for polling operations and are set or returned as part of a PollSpec tuple by the poll() function. When passed via an argument PollSpec to poll(), they specify the I/O events to watch for on the corresponding handle. When appearing in a PollSpec returned by poll(), they specify the I/O events that occurred on a watched handle.

Properties
NameTypeDescription
POLLINnumber

Data available to read.

POLLPRInumber

Priority data available to read.

POLLOUTnumber

Writable data available.

POLLERRnumber

Error condition.

POLLHUPnumber

Hang up.

POLLNVALnumber

Invalid request.

POLLRDHUPnumber

Peer closed or shutdown writing.

Shutdown Constants

The SHUT_* constants are passed as argument to the shutdown() function to specify which direction of a full duplex connection to shut down.

Properties
NameTypeDescription
SHUT_RDnumber

Disallow further receptions.

SHUT_WRnumber

Disallow further transmissions.

SHUT_RDWRnumber

Disallow further receptions and transmissions.

Socket Option Constants

The SOL_SOCKET constant is passed as level argument to the getopt() and setopt() functions in order to set or retrieve generic socket option values.

The SO_* constants are passed as option argument in conjunction with the SOL_SOCKET level to specify the specific option to get or set on the socket.

Properties
NameTypeDescription
SOL_SOCKETnumber

Socket options at the socket API level.

SO_ACCEPTCONNnumber

Reports whether socket listening is enabled.

SO_ATTACH_BPFnumber

Attach BPF program to socket.

SO_ATTACH_FILTERnumber

Attach a socket filter.

SO_ATTACH_REUSEPORT_CBPFnumber

Attach BPF program for cgroup and skb program reuseport hook.

SO_ATTACH_REUSEPORT_EBPFnumber

Attach eBPF program for cgroup and skb program reuseport hook.

SO_BINDTODEVICEnumber

Bind socket to a specific interface.

SO_BROADCASTnumber

Allow transmission of broadcast messages.

SO_BUSY_POLLnumber

Enable busy polling.

SO_DEBUGnumber

Enable socket debugging.

SO_DETACH_BPFnumber

Detach BPF program from socket.

SO_DETACH_FILTERnumber

Detach a socket filter.

SO_DOMAINnumber

Retrieves the domain of the socket.

SO_DONTROUTEnumber

Send packets directly without routing.

SO_ERRORnumber

Retrieves and clears the error status for the socket.

SO_INCOMING_CPUnumber

Retrieves the CPU number on which the last packet was received.

SO_INCOMING_NAPI_IDnumber

Retrieves the NAPI ID of the device.

SO_KEEPALIVEnumber

Enable keep-alive packets.

SO_LINGERnumber

Set linger on close.

SO_LOCK_FILTERnumber

Set or get the socket filter lock state.

SO_MARKnumber

Set the mark for packets sent through the socket.

SO_OOBINLINEnumber

Enables out-of-band data to be received in the normal data stream.

SO_PASSCREDnumber

Enable the receiving of SCM_CREDENTIALS control messages.

SO_PASSSECnumber

Enable the receiving of security context.

SO_PEEK_OFFnumber

Returns the number of bytes in the receive buffer without removing them.

SO_PEERCREDnumber

Retrieves the credentials of the foreign peer.

SO_PEERSECnumber

Retrieves the security context of the foreign peer.

SO_PRIORITYnumber

Set the protocol-defined priority for all packets.

SO_PROTOCOLnumber

Retrieves the protocol number.

SO_RCVBUFnumber

Set the receive buffer size.

SO_RCVBUFFORCEnumber

Set the receive buffer size forcefully.

SO_RCVLOWATnumber

Set the minimum number of bytes to process for input operations.

SO_RCVTIMEOnumber

Set the timeout for receiving data.

SO_REUSEADDRnumber

Allow the socket to be bound to an address that is already in use.

SO_REUSEPORTnumber

Enable duplicate address and port bindings.

SO_RXQ_OVFLnumber

Reports if the receive queue has overflown.

SO_SNDBUFnumber

Set the send buffer size.

SO_SNDBUFFORCEnumber

Set the send buffer size forcefully.

SO_SNDLOWATnumber

Set the minimum number of bytes to process for output operations.

SO_SNDTIMEOnumber

Set the timeout for sending data.

SO_TIMESTAMPnumber

Enable receiving of timestamps.

SO_TIMESTAMPNSnumber

Enable receiving of nanosecond timestamps.

SO_TYPEnumber

Retrieves the type of the socket (e.g., SOCK_STREAM).

Socket Types

The SOCK_* type and flag constants are used by create() to specify the type of socket to open. The accept() function recognizes the SOCK_NONBLOCK and SOCK_CLOEXEC flags and applies them to accepted peer sockets.

Properties
NameTypeDescription
SOCK_STREAMnumber

Provides sequenced, reliable, two-way, connection-based byte streams.

SOCK_DGRAMnumber

Supports datagrams (connectionless, unreliable messages of a fixed maximum length).

SOCK_RAWnumber

Provides raw network protocol access.

SOCK_PACKETnumber

Obsolete and should not be used.

SOCK_NONBLOCKnumber

Enables non-blocking operation.

SOCK_CLOEXECnumber

Sets the close-on-exec flag on the new file descriptor.

TCP Protocol Constants

The IPPROTO_TCP constant specifies the TCP protocol number and may be passed as third argument to create() as well as level argument value to getopt() and setopt().

The TCP_* constants are option argument values recognized by getopt() and setopt(), in conjunction with the IPPROTO_TCP socket level.

Properties
NameTypeDescription
IPPROTO_TCPnumber

TCP protocol.

TCP_CONGESTIONnumber

Set the congestion control algorithm.

TCP_CORKnumber

Delay packet transmission until full-sized packets are available.

TCP_DEFER_ACCEPTnumber

Delay accepting incoming connections until data arrives.

TCP_FASTOPENnumber

Enable TCP Fast Open.

TCP_FASTOPEN_CONNECTnumber

Perform TFO connect.

TCP_INFOnumber

Retrieve TCP statistics.

TCP_KEEPCNTnumber

Number of keepalive probes.

TCP_KEEPIDLEnumber

Time before keepalive probes begin.

TCP_KEEPINTVLnumber

Interval between keepalive probes.

TCP_LINGER2number

Lifetime of orphaned FIN_WAIT2 state sockets.

TCP_MAXSEGnumber

Maximum segment size.

TCP_NODELAYnumber

Disable Nagle's algorithm.

TCP_QUICKACKnumber

Enable quick ACKs.

TCP_SYNCNTnumber

Number of SYN retransmits.

TCP_USER_TIMEOUTnumber

Set the user timeout.

TCP_WINDOW_CLAMPnumber

Set the maximum window.

UDP Protocol Constants

The IPPROTO_UDP constant specifies the UDP protocol number and may be passed as third argument to create() as well as level argument value to getopt() and setopt().

The UDP_* constants are option argument values recognized by getopt() and setopt(), in conjunction with the IPPROTO_UDP socket level.

Properties
NameTypeDescription
IPPROTO_UDPnumber

UDP protocol.

UDP_CORKnumber

Cork data until flush.

ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-socket.socket.html b/module-socket.socket.html index 90ecebd..3588134 100644 --- a/module-socket.socket.html +++ b/module-socket.socket.html @@ -1,6 +1,6 @@ Class: socket

socket. socket

Represents a socket handle.

Example
const sock = create(…);
+    

socket. socket

Represents a socket handle.

Example
const sock = create(…);
 
 sock.getopt(…);
 sock.setopt(…);
@@ -121,4 +121,4 @@
 if (myAddress)
     print(`My source IP address is ${myAddress}\n`);
 else
-    print(`Failed to retrieve peer address: ${sock.error()}\n`);

Type Definitions

ControlMessage: Object

Represents a single control (ancillary data) message returned in the ancillary array by recvmsg().

Properties
NameTypeDescription
levelnumber

The message socket level (cmsg_level), e.g. SOL_SOCKET.

typenumber

The protocol specific message type (cmsg_type), e.g. SCM_RIGHTS.

data*

The payload of the control message. If the control message type is known by the socket module, it is represented as a mixed value (array, object, number, etc.) with structure specific to the control message type. If the control message cannot be decoded, data is set to a string value containing the raw payload.

PeerCredentials: Object

Represents a credentials information object returned by peercred().

Properties
NameTypeDescription
uidnumber

The effective user ID the remote socket endpoint.

gidnumber

The effective group ID the remote socket endpoint.

pidnumber

The ID of the process the remote socket endpoint belongs to.

ReceivedMessage: Object

Represents a message object returned by recvmsg().

Properties
NameTypeAttributesDescription
flagsnumber

Integer value containing bitwise OR-ed MSG_* result flags returned by the underlying receive call.

lengthnumber

Integer value containing the number of bytes returned by the recvmsg() syscall, which might be larger than the received data in case MSG_TRUNC was passed.

addressSocketAddress

The address from which the message was received.

datastring[] | string

An array of strings, each representing the received message data. Each string corresponds to one buffer size specified in the sizes argument. If a single receive size was passed instead of an array of sizes, data will hold a string containing the received data.

ancillaryControlMessage[]optional(optional)

An array of received control messages. Only included if a non-zero positive ancillarySize was passed to recvmsg().

SocketAddress: Object

Properties
NameTypeAttributesDefaultDescription
familynumber

Address family, one of AF_INET, AF_INET6, AF_UNIX or AF_PACKET.

addressstring

IPv4/IPv6 address string (AF_INET or AF_INET6 only) or hardware address in hexadecimal notation (AF_PACKET only).

portnumberoptional(optional)

Port number (AF_INET or AF_INET6 only).

flowinfonumberoptional(optional)

IPv6 flow information (AF_INET6 only).

interfacestring | numberoptional(optional)

Link local address scope (for IPv6 sockets) or bound network interface (for packet sockets), either a network device name string or a nonzero positive integer representing a network interface index (AF_INET6 and AF_PACKET only).

pathstring

Domain socket filesystem path (AF_UNIX only).

protocolnumberoptional0(optional, default: 0)

Physical layer protocol (AF_PACKET only).

hardware_typenumberoptional0(optional, default: 0)

ARP hardware type (AF_PACKET only).

packet_typenumberoptionalPACKET_HOST(optional, default: PACKET_HOST)

Packet type (AF_PACKET only).

Table of Contents
\ No newline at end of file + print(`Failed to retrieve peer address: ${sock.error()}\n`);

Type Definitions

ControlMessage: Object

Represents a single control (ancillary data) message returned in the ancillary array by recvmsg().

Properties
NameTypeDescription
levelnumber

The message socket level (cmsg_level), e.g. SOL_SOCKET.

typenumber

The protocol specific message type (cmsg_type), e.g. SCM_RIGHTS.

data*

The payload of the control message. If the control message type is known by the socket module, it is represented as a mixed value (array, object, number, etc.) with structure specific to the control message type. If the control message cannot be decoded, data is set to a string value containing the raw payload.

PeerCredentials: Object

Represents a credentials information object returned by peercred().

Properties
NameTypeDescription
uidnumber

The effective user ID the remote socket endpoint.

gidnumber

The effective group ID the remote socket endpoint.

pidnumber

The ID of the process the remote socket endpoint belongs to.

ReceivedMessage: Object

Represents a message object returned by recvmsg().

Properties
NameTypeAttributesDescription
flagsnumber

Integer value containing bitwise OR-ed MSG_* result flags returned by the underlying receive call.

lengthnumber

Integer value containing the number of bytes returned by the recvmsg() syscall, which might be larger than the received data in case MSG_TRUNC was passed.

addressSocketAddress

The address from which the message was received.

datastring[] | string

An array of strings, each representing the received message data. Each string corresponds to one buffer size specified in the sizes argument. If a single receive size was passed instead of an array of sizes, data will hold a string containing the received data.

ancillaryControlMessage[]optional(optional)

An array of received control messages. Only included if a non-zero positive ancillarySize was passed to recvmsg().

SocketAddress: Object

Properties
NameTypeAttributesDefaultDescription
familynumber

Address family, one of AF_INET, AF_INET6, AF_UNIX or AF_PACKET.

addressstring

IPv4/IPv6 address string (AF_INET or AF_INET6 only) or hardware address in hexadecimal notation (AF_PACKET only).

portnumberoptional(optional)

Port number (AF_INET or AF_INET6 only).

flowinfonumberoptional(optional)

IPv6 flow information (AF_INET6 only).

interfacestring | numberoptional(optional)

Link local address scope (for IPv6 sockets) or bound network interface (for packet sockets), either a network device name string or a nonzero positive integer representing a network interface index (AF_INET6 and AF_PACKET only).

pathstring

Domain socket filesystem path (AF_UNIX only).

protocolnumberoptional0(optional, default: 0)

Physical layer protocol (AF_PACKET only).

hardware_typenumberoptional0(optional, default: 0)

ARP hardware type (AF_PACKET only).

packet_typenumberoptionalPACKET_HOST(optional, default: PACKET_HOST)

Packet type (AF_PACKET only).

ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-struct.html b/module-struct.html index 9925d43..28acc74 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:
NameTypeDescription
formatstring

The format string.

inputstring

The input string to unpack.

offsetnumber(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 c1714ee..57aff40 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:
NameTypeDescription
values*(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:
NameTypeDescription
inputstring

The input string to unpack.

offsetnumber(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 ffd9067..0f49da4 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 5d3454b..dc788b2 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/module-uloop.handle.html b/module-uloop.handle.html index 6235453..5a9a767 100644 --- a/module-uloop.handle.html +++ b/module-uloop.handle.html @@ -1,6 +1,6 @@ Class: handle

uloop. handle

Represents a uloop handle instance as returned by handle().

Example
const handle = uloop.handle(…);
+    

uloop. handle

Represents a uloop handle instance as returned by handle().

Example
const handle = uloop.handle(…);
 
 handle.fileno();
 handle.handle();
@@ -11,4 +11,4 @@
 const fd = handle.fileno();
 printf("File descriptor number: %d\n", fd);

handle() → {module:fs.file|module:fs.proc|module:socket.socket}

Returns the underlying file or socket instance.

This method returns the underlying file or socket instance associated with the uloop handle.

Returns: module:fs.file | module:fs.proc | module:socket.socket

The underlying file or socket instance associated with the handle.

Example
// Get the associated file or socket instance
 const fileOrSocket = handle.handle();
-printf("Handle: %s\n", fileOrSocket); // e.g. <socket 0x5> or <fs.proc …>
Table of Contents
\ No newline at end of file +printf("Handle: %s\n", fileOrSocket); // e.g. <socket 0x5> or <fs.proc …>
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-uloop.html b/module-uloop.html index 0399990..18c6832 100644 --- a/module-uloop.html +++ b/module-uloop.html @@ -1,6 +1,6 @@ Module: uloop

OpenWrt uloop event loop

The uloop binding provides functions for integrating with the OpenWrt uloop library.

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

import { init, handle, timer, interval, process, signal, task, run } from 'uloop';
+    

OpenWrt uloop event loop

The uloop binding provides functions for integrating with the OpenWrt uloop library.

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

import { init, handle, timer, interval, process, signal, task, run } from 'uloop';
 
 init();
 
@@ -104,4 +104,4 @@
 });
 
 // Later enable the timer with a timeout of 500 milliseconds
-myTimer.set(500);

Type Definitions

Event Mode Constants

The ULOOP_* constants are passed as bitwise OR-ed number to the handle() function to specify the IO events that should be monitored on the given handle.

Properties
NameTypeDescription
ULOOP_READnumber

File or socket is readable.

ULOOP_WRITEnumber

File or socket is writable.

ULOOP_EDGE_TRIGGERnumber

Enable edge-triggered event mode.

ULOOP_BLOCKINGnumber

Do not make descriptor non-blocking.

Table of Contents
\ No newline at end of file +myTimer.set(500);

Type Definitions

Event Mode Constants

The ULOOP_* constants are passed as bitwise OR-ed number to the handle() function to specify the IO events that should be monitored on the given handle.

Properties
NameTypeDescription
ULOOP_READnumber

File or socket is readable.

ULOOP_WRITEnumber

File or socket is writable.

ULOOP_EDGE_TRIGGERnumber

Enable edge-triggered event mode.

ULOOP_BLOCKINGnumber

Do not make descriptor non-blocking.

ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-uloop.interval.html b/module-uloop.interval.html index 52dd7dd..0eb6c98 100644 --- a/module-uloop.interval.html +++ b/module-uloop.interval.html @@ -1,6 +1,6 @@ Class: interval

uloop. interval

Represents a uloop interval timer instance as returned by interval().

Example
const intv = uloop.interval(…);
+    

uloop. interval

Represents a uloop interval timer instance as returned by interval().

Example
const intv = uloop.interval(…);
 
 intv.set(…);
 intv.remaining();
@@ -28,4 +28,4 @@
 if (success)
     printf("Interval disabled successfully\n");
 else
-    printf("Error occurred while disabling interval: ${uloop.error()}\n");
Table of Contents
\ No newline at end of file + printf("Error occurred while disabling interval: ${uloop.error()}\n");
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-uloop.pipe.html b/module-uloop.pipe.html index e610784..3f6b4bd 100644 --- a/module-uloop.pipe.html +++ b/module-uloop.pipe.html @@ -1,6 +1,6 @@ Class: pipe

uloop. pipe

Represents a uloop task communication pipe instance, passed as sole argument to the task function by task().

Example
*
+    

uloop. pipe

Represents a uloop task communication pipe instance, passed as sole argument to the task function by task().

Example
*
 const task = uloop.task((pipe) => {
     …
     pipe.send();
@@ -31,4 +31,4 @@
 if (hasInputCallback)
     printf("Input callback is registered on task handle\n");
 else
-    printf("No input callback on the task handle\n");
Table of Contents
\ No newline at end of file + printf("No input callback on the task handle\n");
ucode Documentation
Table of Contents
\ No newline at end of file diff --git a/module-uloop.process.html b/module-uloop.process.html index 49108ac..0ba2c2c 100644 --- a/module-uloop.process.html +++ b/module-uloop.process.html @@ -1,6 +1,6 @@ Class: process

uloop. process

Represents a uloop process instance as returned by process().

Example
const proc = uloop.process(…);
+    

uloop. process

Represents a uloop process instance as returned by process().

Example
const proc = uloop.process(…);
 
 proc.pid();
 
@@ -8,7 +8,7 @@
 
 proc.delete();

pid() → {number}

Returns the process ID.

This method returns the process ID (PID) of the operating system process launched by process().

Returns: number

The process ID (PID) of the associated launched process.

Example
const proc = uloop.process(…);
 
-printf("Process ID: %d\n", proc.pid());
Table of Contents

uloop. signal

Represents a uloop signal Unix process signal handler as returned by signal().

Example
const sighandler = uloop.signal(…);
+    

uloop. signal

Represents a uloop signal Unix process signal handler as returned by signal().

Example
const sighandler = uloop.signal(…);
 
 sighandler.signo();
 sighandler.delete();

Methods

delete() → {boolean}

Uninstalls the signal handler.

This method uninstalls the signal handler, restoring the previous or default handler for the signal, and releasing any associated resources.

Returns: boolean

Returns true on success.

Example
// Uninstall the signal handler and restore the previous/default handler
 const sighandler = uloop.signal(…);
 sighandler.delete();

signo() → {number}

Returns the associated signal number.

This method returns the signal number that this uloop signal handler is configured to respond to.

Returns: number

The signal number that this handler is responding to.

Example
// Get the signal number that the uloop signal handler is responding to
 const sighandler = uloop.signal("SIGINT", () => printf("Cought INT\n"));
-printf("Signal number: %d\n", sighandler.signo());
Table of Contents
\ No newline at end of file +printf("Signal number: %d\n", sighandler.signo());
Table of Contents
\ No newline at end of file diff --git a/module-uloop.task.html b/module-uloop.task.html index a7ce9c3..10cf902 100644 --- a/module-uloop.task.html +++ b/module-uloop.task.html @@ -1,6 +1,6 @@ Class: task

uloop. task

Represents a uloop task instance as returned by task().

Example
const task = uloop.task(…);
+    

uloop. task

Represents a uloop task instance as returned by task().

Example
const task = uloop.task(…);
 
 task.pid();
 task.finished();
@@ -19,7 +19,7 @@
 else
     die(`Error terminating task process: ${uloop.error()}\n`);

pid() → {number}

Returns the process ID.

This method returns the process ID (PID) of the underlying forked process launched by task().

Returns: number

The process ID (PID) of the forked task process.

Example
const task = uloop.task(…);
 
-printf("Process ID: %d\n", task.pid());
Table of Contents

uloop. timer

Represents a uloop timer instance as returned by timer().

Example
const timeout = uloop.timer(…);
+    

uloop. timer

Represents a uloop timer instance as returned by timer().

Example
const timeout = uloop.timer(…);
 
 timeout.set(…);
 timeout.remaining();
@@ -16,4 +16,4 @@
 timeout.set(1000);
 
 // Disable the uloop timer
-timeout.set();
Table of Contents
\ No newline at end of file +timeout.set();
Table of Contents
\ No newline at end of file diff --git a/module-zlib.html b/module-zlib.html index d506de9..19bf064 100644 --- a/module-zlib.html +++ b/module-zlib.html @@ -1,7 +1,7 @@ Module: zlib

Zlib bindings

The zlib module provides single-call-oriented functions for interacting with zlib data.

Methods

deflate(str_or_resource, gzipopt, nullable, levelopt, nullable) → {string}nullable

Compresses data in Zlib or gzip format.

If the input argument is a plain string, it is directly compressed.

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

Throws an exception on errors.

Returns the compressed data.

Parameters:
NameTypeDescription
str_or_resourcestring

The string or resource object to be parsed as JSON.

gzipboolean(optional, nullable, default: false)

Add a gzip header if true (creates a gzip-compliant output, otherwise defaults to Zlib)

levelnumber(optional, nullable, default: Z_DEFAULT_COMPRESSION)

The compression level (0-9).

Returns: string
Example
// deflate content using default compression
+    

Zlib bindings

The zlib module provides single-call-oriented functions for interacting with zlib data.

Methods

deflate(str_or_resource, gzipopt, nullable, levelopt, nullable) → {string}nullable

Compresses data in Zlib or gzip format.

If the input argument is a plain string, it is directly compressed.

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

Throws an exception on errors.

Returns the compressed data.

Parameters:
NameTypeDescription
str_or_resourcestring

The string or resource object to be parsed as JSON.

gzipboolean(optional, nullable, default: false)

Add a gzip header if true (creates a gzip-compliant output, otherwise defaults to Zlib)

levelnumber(optional, nullable, default: Z_DEFAULT_COMPRESSION)

The compression level (0-9).

Returns: string
Example
// deflate content using default compression
 const deflated = deflate(content);
 
 // deflate content using fastest compression
-const deflated = deflate(content, Z_BEST_SPEED);

inflate(str_or_resource) → {string}nullable

Decompresses data in Zlib or gzip format.

If the input argument is a plain string, it is directly decompressed.

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

Throws an exception on errors.

Returns the decompressed data.

Parameters:
NameTypeDescription
str_or_resourcestring

The string or resource object to be parsed as JSON.

Returns: string

Type Definitions

Compression levels

Constants representing predefined compression levels.

Properties
NameTypeDescription
Z_NO_COMPRESSION.number
Z_BEST_SPEED.number
Z_BEST_COMPRESSION.number
Z_DEFAULT_COMPRESSIONnumber

default compromise between speed and compression (currently equivalent to level 6).

Table of Contents
\ No newline at end of file +const deflated = deflate(content, Z_BEST_SPEED);

inflate(str_or_resource) → {string}nullable

Decompresses data in Zlib or gzip format.

If the input argument is a plain string, it is directly decompressed.

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

Throws an exception on errors.

Returns the decompressed data.

Parameters:
NameTypeDescription
str_or_resourcestring

The string or resource object to be parsed as JSON.

Returns: string

Type Definitions

Compression levels

Constants representing predefined compression levels.

Properties
NameTypeDescription
Z_NO_COMPRESSION.number
Z_BEST_SPEED.number
Z_BEST_COMPRESSION.number
Z_DEFAULT_COMPRESSIONnumber

default compromise between speed and compression (currently equivalent to level 6).

Table of Contents
\ No newline at end of file diff --git a/tutorial-01-usage.html b/tutorial-01-usage.html index f4d9213..8e03bb6 100644 --- a/tutorial-01-usage.html +++ b/tutorial-01-usage.html @@ -1,8 +1,8 @@ Tutorial: Usage

Usage

The ucode command line utility provides a set of options and arguments for executing and compiling ucode programs. Here is a detailed explanation of each option and its usage:

  • -h: Display the help message, which provides an overview of the available options and their usage.

  • -e "expression": Execute the given expression as a ucode program. This option allows you to provide a single-line ucode expression for immediate execution.

  • -p "expression": Execute the given expression as a ucode program and print the result after execution.

  • -c [-s] [-o output.uc] input.uc [input2.uc ...]: Compile the specified source file(s) to bytecode instead of executing them. By default, the compiled bytecode is written to ./uc.out. The -s option omits debug information, reducing the size of the compiled bytecode. The -o option allows specifying the output file path for the compiled bytecode.

  • -t: Enable VM (Virtual Machine) execution tracing. This option enables tracing of the ucode program's execution, providing detailed information for debugging purposes.

  • -g interval: Perform periodic garbage collection at regular intervals defined by the interval parameter. Garbage collection is a memory management process that frees up memory occupied by objects that are no longer in use.

  • -S: Enable strict mode, which enforces strict adherence to ucode language rules and prevents the use of certain potentially error-prone or unsafe language features.

  • -R: Process source file(s) as raw script code. This is the default mode of operation, where the ucode interpreter treats the source files as direct ucode script code.

  • -T[flag,flag,...]: Process the source file(s) as templates instead of raw script code. This option enables the usage of Jinja-like templates with embedded ECMAScript 6 code. The flags provide additional control over template processing, such as preserving leading whitespace or trailing newlines.

  • -D [name=]value: Define a global variable in the ucode program. If the name parameter is omitted, a JSON dictionary is expected as the value, where each property becomes a global variable with its corresponding value. If name is specified, it defines a global variable with the provided value, parsed as JSON or as a literal string if JSON parsing fails.

  • -F [name=]path: Similar to the -D option, but reads the value from a file specified by the path parameter. The file must contain a single, well-formed JSON dictionary.

  • -U name: Undefine the given global variable name. This option removes the specified global variable from the ucode program's scope.

  • -l [name=]library: Preload the specified library for use in the ucode program. Optionally, the library can be aliased to a different name within the program.

  • -L pattern: Prepend the provided pattern to the default library search paths. This option allows specifying custom paths for loading libraries. If the pattern does not contain an asterisk (*), it is added twice, once with /*.so and once with /*.uc appended to it.

Examples

Here are some examples showcasing the invocation of the ucode program with different options:

  1. Execute a ucode expression:

    ucode -e "print('Hello, World!\n');"
    +    

    Usage

    The ucode command line utility provides a set of options and arguments for executing and compiling ucode programs. Here is a detailed explanation of each option and its usage:

    • -h: Display the help message, which provides an overview of the available options and their usage.

    • -e "expression": Execute the given expression as a ucode program. This option allows you to provide a single-line ucode expression for immediate execution.

    • -p "expression": Execute the given expression as a ucode program and print the result after execution.

    • -c [-s] [-o output.uc] input.uc [input2.uc ...]: Compile the specified source file(s) to bytecode instead of executing them. By default, the compiled bytecode is written to ./uc.out. The -s option omits debug information, reducing the size of the compiled bytecode. The -o option allows specifying the output file path for the compiled bytecode.

    • -t: Enable VM (Virtual Machine) execution tracing. This option enables tracing of the ucode program's execution, providing detailed information for debugging purposes.

    • -g interval: Perform periodic garbage collection at regular intervals defined by the interval parameter. Garbage collection is a memory management process that frees up memory occupied by objects that are no longer in use.

    • -S: Enable strict mode, which enforces strict adherence to ucode language rules and prevents the use of certain potentially error-prone or unsafe language features.

    • -R: Process source file(s) as raw script code. This is the default mode of operation, where the ucode interpreter treats the source files as direct ucode script code.

    • -T[flag,flag,...]: Process the source file(s) as templates instead of raw script code. This option enables the usage of Jinja-like templates with embedded ECMAScript 6 code. The flags provide additional control over template processing, such as preserving leading whitespace or trailing newlines.

    • -D [name=]value: Define a global variable in the ucode program. If the name parameter is omitted, a JSON dictionary is expected as the value, where each property becomes a global variable with its corresponding value. If name is specified, it defines a global variable with the provided value, parsed as JSON or as a literal string if JSON parsing fails.

    • -F [name=]path: Similar to the -D option, but reads the value from a file specified by the path parameter. The file must contain a single, well-formed JSON dictionary.

    • -U name: Undefine the given global variable name. This option removes the specified global variable from the ucode program's scope.

    • -l [name=]library: Preload the specified library for use in the ucode program. Optionally, the library can be aliased to a different name within the program.

    • -L pattern: Prepend the provided pattern to the default library search paths. This option allows specifying custom paths for loading libraries. If the pattern does not contain an asterisk (*), it is added twice, once with /*.so and once with /*.uc appended to it.

    Examples

    Here are some examples showcasing the invocation of the ucode program with different options:

    1. Execute a ucode expression:

      ucode -e "print('Hello, World!\n');"
       
    2. Execute a ucode expression and print the result:

      ucode -p "2 ** 3"
       
    3. Execute a ucode program from a source file:

      ucode program.uc
       
    4. Compile a ucode program to bytecode:

      ucode -c program.uc
       
    5. Compile a ucode program to bytecode with a specified output file:

      ucode -c -o compiled.uc program.uc
      -
    Table of Contents
    \ No newline at end of file +
Table of Contents
\ No newline at end of file diff --git a/tutorial-02-syntax.html b/tutorial-02-syntax.html index 30e88a9..acda444 100644 --- a/tutorial-02-syntax.html +++ b/tutorial-02-syntax.html @@ -1,6 +1,6 @@ Tutorial: Syntax

Syntax

The ucode programming language features a syntax that closely resembles ECMAScript 6. However, the ucode interpreter supports two distinct syntax modes: template mode and raw mode.

In template mode, ucode consumes Jinja-like templates that allow for the embedding of script code within the template structure. This mode enables the combination of expressive template constructs with JavaScript like functionality.

On the other hand, raw mode in ucode directly consumes ECMAScript 6-like syntax without any template-specific markup. This mode is mainly useful to develop standalone applications or libraries.

Template mode

By default, ucode is executed in raw mode, means it expects a given source file to only contain script code. By invoking the ucode interpreter with the -T flag or by using the utpl alias, the ucode interpreter is switched into template mode where the source file is expected to be a plaintext file containing template blocks containing ucode script expressions or comments.

Block types

There are three kinds of blocks; expression blocks, statement blocks and comment blocks. The former two embed code logic using ucode's JavaScript-like syntax while the latter comment block type is simply discarded during processing.

1. Statement block

Statement blocks are enclosed in an opening {% and a closing %} tag and may contain any number of script code statements, even entire programs.

It is allowed to omit the closing %} of a statement block to parse the entire remaining source text after the opening tag as ucode script.

By default, statement blocks produce no output and the entire block is reduced to an empty string during template evaluation but contained script code might invoke functions such as print() to explicitly output contents.

For example the following template would result in The epoch is odd or The epoch is even, depending on the current epoch value:

The epoch is {% if (time() % 2): %}odd{% else %}even{% endif %}!

2. Expression block

Expression blocks are enclosed in an opening {{ and a closing }} tag and may only contain a single expression statement (multiple expressions may be chained with comma). The implicit result of the rightmost evaluated expression is used as output when processing the block.

For example the template Hello world, {{ getenv("USER") }}! would result in the output "Hello world, user!" where user would correspond to the name of the current user executing the ucode interpreter.

3. Comment block

Comment blocks, which are denoted with an opening {# and a closing #} tag may contain arbitrary text except the closing #} tag itself. Comments blocks are completely stripped during processing and are replaced with an empty string.

The following example template would result in the output "Hello world":

Hello {# mad #}word

Whitespace handling

Each block start tag may be suffixed with a dash to strip any whitespace before the block and likewise any block end tag may be prefixed with a dash to strip any whitespace following the block.

Without using whitespace stripping, the following example:

This is a first line
+    

Syntax

The ucode programming language features a syntax that closely resembles ECMAScript 6. However, the ucode interpreter supports two distinct syntax modes: template mode and raw mode.

In template mode, ucode consumes Jinja-like templates that allow for the embedding of script code within the template structure. This mode enables the combination of expressive template constructs with JavaScript like functionality.

On the other hand, raw mode in ucode directly consumes ECMAScript 6-like syntax without any template-specific markup. This mode is mainly useful to develop standalone applications or libraries.

Template mode

By default, ucode is executed in raw mode, means it expects a given source file to only contain script code. By invoking the ucode interpreter with the -T flag or by using the utpl alias, the ucode interpreter is switched into template mode where the source file is expected to be a plaintext file containing template blocks containing ucode script expressions or comments.

Block types

There are three kinds of blocks; expression blocks, statement blocks and comment blocks. The former two embed code logic using ucode's JavaScript-like syntax while the latter comment block type is simply discarded during processing.

1. Statement block

Statement blocks are enclosed in an opening {% and a closing %} tag and may contain any number of script code statements, even entire programs.

It is allowed to omit the closing %} of a statement block to parse the entire remaining source text after the opening tag as ucode script.

By default, statement blocks produce no output and the entire block is reduced to an empty string during template evaluation but contained script code might invoke functions such as print() to explicitly output contents.

For example the following template would result in The epoch is odd or The epoch is even, depending on the current epoch value:

The epoch is {% if (time() % 2): %}odd{% else %}even{% endif %}!

2. Expression block

Expression blocks are enclosed in an opening {{ and a closing }} tag and may only contain a single expression statement (multiple expressions may be chained with comma). The implicit result of the rightmost evaluated expression is used as output when processing the block.

For example the template Hello world, {{ getenv("USER") }}! would result in the output "Hello world, user!" where user would correspond to the name of the current user executing the ucode interpreter.

3. Comment block

Comment blocks, which are denoted with an opening {# and a closing #} tag may contain arbitrary text except the closing #} tag itself. Comments blocks are completely stripped during processing and are replaced with an empty string.

The following example template would result in the output "Hello world":

Hello {# mad #}word

Whitespace handling

Each block start tag may be suffixed with a dash to strip any whitespace before the block and likewise any block end tag may be prefixed with a dash to strip any whitespace following the block.

Without using whitespace stripping, the following example:

This is a first line
 {% for (x in [1, 2, 3]): %}
 This is item {{ x }}.
 {% endfor %}
@@ -224,4 +224,4 @@
 
   print(a);              // { }
 %}
-

5.7. Precedence

Operator precedence determines the order in which operators are evaluated in an expression. In ucode, operators have different precedence levels, as outline in the table below.

PrecedenceOperator typeAssociativity
19Grouping ( … )n/a
18Property access … . …left-to-right
18Optional chaining … ?. …left-to-right
18Computed propery access … [ … ]n/a
18Function call … (…)n/a
17Postfix increment … ++n/a
17Postfix decrement … --n/a
16Logical not ! …n/a
16Bitwise not ~ …n/a
16Unary plus + …n/a
16Unary negation - …n/a
16Prefix increment ++ …n/a
16Prefix decrement -- …n/a
16Property deletion delete …n/a
15Exponentiation … ** …right-to-left
14Multiplication … * …left-to-right
14Division … / …left-to-right
14Remainder … % …left-to-right
13Addition … + …left-to-right
13Substraction … - …left-to-right
12Bitwise left shift … << …left-to-right
12Bitwise right shift … >> …left-to-right
11Less than … < …left-to-right
11Less than or equal … <= …left-to-right
11Greater than … > …left-to-right
11Greater than or equal … >= …left-to-right
11In … in …left-to-right
10Equality … == …left-to-right
10Inequality … != …left-to-right
10Strict equality … === …left-to-right
10Strict inequality … !== …left-to-right
9Bitwise AND … & …left-to-right
8Bitwise XOR … ^ …left-to-right
7Bitwise OR … | …left-to-right
6Logical AND … && …left-to-right
5Logical OR … || …left-to-right
5Nullish coalescing … ?? …left-to-right
4Assignment … = …right-to-left
4Assignment … += …right-to-left
4Assignment … -= …right-to-left
4Assignment … **= …right-to-left
4Assignment … *= …right-to-left
4Assignment … /= …right-to-left
4Assignment … %= …right-to-left
4Assignment … <<= …right-to-left
4Assignment … >>= …right-to-left
4Assignment … &= …right-to-left
4Assignment … ^= …right-to-left
4Assignment … |= …right-to-left
4Assignment … &&= …right-to-left
4Assignment … ||= …right-to-left
4Assignment … ??= …right-to-left
3Ternary … ? … : …right-to-left
2Arrow … => …right-to-left
2Spread ... …n/a
1Sequence … , …left-to-right

Operators with a higher precedence value are evaluated before operators with a lower precedence value. When operators have the same precedence, their associativity determines the order of evaluation (e.g., left-to-right or right-to-left).

Table of Contents
\ No newline at end of file +

5.7. Precedence

Operator precedence determines the order in which operators are evaluated in an expression. In ucode, operators have different precedence levels, as outline in the table below.

PrecedenceOperator typeAssociativity
19Grouping ( … )n/a
18Property access … . …left-to-right
18Optional chaining … ?. …left-to-right
18Computed propery access … [ … ]n/a
18Function call … (…)n/a
17Postfix increment … ++n/a
17Postfix decrement … --n/a
16Logical not ! …n/a
16Bitwise not ~ …n/a
16Unary plus + …n/a
16Unary negation - …n/a
16Prefix increment ++ …n/a
16Prefix decrement -- …n/a
16Property deletion delete …n/a
15Exponentiation … ** …right-to-left
14Multiplication … * …left-to-right
14Division … / …left-to-right
14Remainder … % …left-to-right
13Addition … + …left-to-right
13Substraction … - …left-to-right
12Bitwise left shift … << …left-to-right
12Bitwise right shift … >> …left-to-right
11Less than … < …left-to-right
11Less than or equal … <= …left-to-right
11Greater than … > …left-to-right
11Greater than or equal … >= …left-to-right
11In … in …left-to-right
10Equality … == …left-to-right
10Inequality … != …left-to-right
10Strict equality … === …left-to-right
10Strict inequality … !== …left-to-right
9Bitwise AND … & …left-to-right
8Bitwise XOR … ^ …left-to-right
7Bitwise OR … | …left-to-right
6Logical AND … && …left-to-right
5Logical OR … || …left-to-right
5Nullish coalescing … ?? …left-to-right
4Assignment … = …right-to-left
4Assignment … += …right-to-left
4Assignment … -= …right-to-left
4Assignment … **= …right-to-left
4Assignment … *= …right-to-left
4Assignment … /= …right-to-left
4Assignment … %= …right-to-left
4Assignment … <<= …right-to-left
4Assignment … >>= …right-to-left
4Assignment … &= …right-to-left
4Assignment … ^= …right-to-left
4Assignment … |= …right-to-left
4Assignment … &&= …right-to-left
4Assignment … ||= …right-to-left
4Assignment … ??= …right-to-left
3Ternary … ? … : …right-to-left
2Arrow … => …right-to-left
2Spread ... …n/a
1Sequence … , …left-to-right

Operators with a higher precedence value are evaluated before operators with a lower precedence value. When operators have the same precedence, their associativity determines the order of evaluation (e.g., left-to-right or right-to-left).

Table of Contents
\ No newline at end of file diff --git a/tutorial-03-memory.html b/tutorial-03-memory.html index fca0472..ab7f423 100644 --- a/tutorial-03-memory.html +++ b/tutorial-03-memory.html @@ -1,6 +1,6 @@ Tutorial: Memory Management

Memory Management

The ucode scripting language utilizes a reference count-based garbage collector as its primary method of memory management. When assigning an array or object value, the reference count is incremented. When a local variable holding a reference goes out of scope, the reference count is decremented. If the reference count reaches zero, a recursive traversal is performed to decrease the reference count of any nested references. Once the traversal is complete, the top-level array or object structure is freed.

Example 1:

x = [ { a: 1 }, { b: 2 }, { c: 3 } ];
+    

Memory Management

The ucode scripting language utilizes a reference count-based garbage collector as its primary method of memory management. When assigning an array or object value, the reference count is incremented. When a local variable holding a reference goes out of scope, the reference count is decremented. If the reference count reaches zero, a recursive traversal is performed to decrease the reference count of any nested references. Once the traversal is complete, the top-level array or object structure is freed.

Example 1:

x = [ { a: 1 }, { b: 2 }, { c: 3 } ];
 // `x` holds a reference to `[...]` (refcount 1)
 // `x[0]` holds a reference to `{ a: 1 }` (refcount 1)
 // `x[1]` holds a reference to `{ b: 2 }` (refcount 1)
@@ -31,4 +31,4 @@
 // `a` holds a reference to itself (refcount 1)
 

Example 3:

x = { y: { z: [ ] } }; x.y.z = x;
 // `x` holds a reference to itself through `x.y.z` (refcount 1)
-

In these examples, cyclic references are created where objects or arrays point back to themselves or create a circular chain. Since each element within the cycle maintains a reference, the reference count for each object or array never reaches zero, resulting in a memory leak. The reference count-based garbage collector cannot automatically reclaim memory in such cases.

To address cyclic structures and avoid memory leaks, ucode provides a secondary mark-and-sweep garbage collector. This collector can be enabled by passing the -g flag to the ucode interpreter or manually triggered using the gc() function during runtime. The mark-and-sweep collector identifies and frees unreachable objects, including those involved in cyclic references.

Table of Contents
\ No newline at end of file +

In these examples, cyclic references are created where objects or arrays point back to themselves or create a circular chain. Since each element within the cycle maintains a reference, the reference count for each object or array never reaches zero, resulting in a memory leak. The reference count-based garbage collector cannot automatically reclaim memory in such cases.

To address cyclic structures and avoid memory leaks, ucode provides a secondary mark-and-sweep garbage collector. This collector can be enabled by passing the -g flag to the ucode interpreter or manually triggered using the gc() function during runtime. The mark-and-sweep collector identifies and frees unreachable objects, including those involved in cyclic references.

Table of Contents
\ No newline at end of file