diff --git a/data/search.json b/data/search.json index 0e661952..17b601a2 100644 --- a/data/search.json +++ b/data/search.json @@ -1 +1 @@ -{"list":[{"title":"module:core","link":"core","description":"

Builtin functions

\n

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

"},{"title":"module:core#arrtoip","link":"arrtoip","description":"

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

\n

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

\n

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

"},{"title":"module:core#assert","link":"assert","description":"

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

\n

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

"},{"title":"module:core#b64dec","link":"b64dec","description":"

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

\n"},{"title":"module:core#b64enc","link":"b64enc","description":"

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

\n"},{"title":"module:core#call","link":"call","description":"

Calls the given function value with a modified environment.

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

\n

Forwards exceptions thrown by the invoked function.

"},{"title":"module:core#chr","link":"chr","description":"

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

\n

Returns a new strings consisting of the given byte values.

"},{"title":"module:core#clock","link":"clock","description":"

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

\n

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

\n

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

\n

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

"},{"title":"module:core#die","link":"die","description":"

Raise an exception with the given message and abort execution.

"},{"title":"module:core#exists","link":"exists","description":"

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

\n

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

"},{"title":"module:core#exit","link":"exit","description":"

Terminate the interpreter with the given exit code.

\n

This function does not return.

"},{"title":"module:core#filter","link":"filter","description":"

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

\n

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

\n
    \n
  1. The array value
  2. \n
  3. The current index
  4. \n
  5. The array being filtered
  6. \n
\n

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

"},{"title":"module:core#gc","link":"gc","description":"

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

\n

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

\n

The following operations are defined:

\n\n

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

"},{"title":"module:core#getenv","link":"getenv","description":"

Query an environment variable or then entire environment.

\n

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

"},{"title":"module:core#gmtime","link":"gmtime","description":"

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

\n

See localtime() for details on the return value.

"},{"title":"module:core#hex","link":"hex","description":"

Converts the given hexadecimal string into a number.

\n

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

"},{"title":"module:core#hexdec","link":"hexdec","description":"

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

\n

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

\n

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

\n

Returns the decoded byte string on success.

"},{"title":"module:core#hexenc","link":"hexenc","description":"

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

"},{"title":"module:core#include","link":"include","description":"

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

\n

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

\n

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

"},{"title":"module:core#index","link":"index","description":"

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

\n

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

\n

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

"},{"title":"module:core#int","link":"int","description":"

Converts the given value to an integer.

\n

Returns NaN if the value is not convertible.

"},{"title":"module:core#iptoarr","link":"iptoarr","description":"

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

\n

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

\n

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

"},{"title":"module:core#join","link":"join","description":"

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

\n

Returns null if the second argument is not an array.

"},{"title":"module:core#json","link":"json","description":"

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

\n

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

\n

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

\n

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

\n

Returns the parsed JSON data.

"},{"title":"module:core#keys","link":"keys","description":"

Enumerates all object key names.

\n

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

"},{"title":"module:core#lc","link":"lc","description":"

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

\n

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

"},{"title":"module:core#length","link":"length","description":"

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

\n

Returns the length of the given value.

\n\n

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

"},{"title":"module:core#loadfile","link":"loadfile","description":"

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

\n

See loadstring() for details.

\n

Returns the compiled program entry function.

\n

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

"},{"title":"module:core#loadstring","link":"loadstring","description":"

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

\n

The optional options dictionary overrides parse and compile options.

\n\n

The following keys in the options dictionary are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
KeyTypeDescription
lstrip_blocksboolStrip leading whitespace before statement template blocks
trim_blocksboolStrip newline after statement template blocks
strict_declarationsboolTreat access to undefined variables as fatal error
raw_modeboolCompile source in script mode, don't treat it as template
module_search_patharrayOverride compile time module search path
force_dynlink_listarrayList of module names to treat as dynamic extensions
\n

Unrecognized keys are ignored, unspecified options default to those of the\nrunning program.

\n

Returns the compiled program entry function.

\n

Throws an exception on compilation errors.

"},{"title":"module:core#localtime","link":"localtime","description":"

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

\n

The resulting dictionary contains the following fields:

\n\n

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

"},{"title":"module:core#ltrim","link":"ltrim","description":"

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

\n

Returns the left trimmed string.

"},{"title":"module:core#map","link":"map","description":"

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

\n

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

"},{"title":"module:core#match","link":"match","description":"

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

\n

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

\n

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

\n

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

"},{"title":"module:core#max","link":"max","description":"

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

"},{"title":"module:core#min","link":"min","description":"

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

"},{"title":"module:core#ord","link":"ord","description":"

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

\n

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

\n

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

"},{"title":"module:core#pop","link":"pop","description":"

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

\n

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

"},{"title":"module:core#print","link":"print","description":"

Print any of the given values to stdout.

\n

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

\n

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

\n

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

\n

Examples:

\n
print(1 != 2);                       // Will print 'true'\nprint(0xff);                         // Will print '255'\nprint(2e3);                          // Will print '2000'\nprint(null);                         // Will print nothing\nprint({ hello: true, world: 123 });  // Will print '{ "hello": true, "world": 123 }'\nprint([1,2,3]);                      // Will print '[ 1, 2, 3 ]'\n\nprint(proto({ foo: "bar" },          // Will print 'MyObj'\n  { tostring: () => "MyObj" }));     // instead of '{ "foo": "bar" }'\n\n
\n

Returns the amount of bytes printed.

"},{"title":"module:core#printf","link":"printf","description":"

Formats the given arguments according to the given format string and outputs\nthe result to stdout.

\n

Ucode supports a restricted subset of the formats allowed by the underlying\nlibc's printf() implementation, namely it allows the d, i, o, u,\nx, X, e, E, f, F, g, G, c and s conversions.

\n

Additionally, an ucode specific J format is implemented, which causes the\ncorresponding value to be formatted as JSON string. By prefixing the J\nformat letter with a precision specifier, the resulting JSON output will be\npretty printed. A precision of 0 will use tabs for indentation, any other\npositive precision will use that many spaces for indentation while a negative\nor omitted precision specifier will turn off pretty printing.

\n

Other format specifiers such as n or z are not accepted and returned\nverbatim. Format specifiers including * directives are rejected as well.

\n

Returns the number of bytes written to the standard output.

"},{"title":"module:core#proto","link":"proto","description":"

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

\n

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

\n

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

\n

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

"},{"title":"module:core#push","link":"push","description":"

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

\n

Returns the last pushed value.

"},{"title":"module:core#regexp","link":"regexp","description":"

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

\n\n

Returns the compiled regular expression value.

"},{"title":"module:core#render","link":"render","description":"

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

\n

The second argument is treated as the scope.

\n

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

\n

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

"},{"title":"module:core#replace","link":"replace","description":"

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

\n\n

Returns a new string with the pattern replaced.

"},{"title":"module:core#reverse","link":"reverse","description":"

Reverse the order of the given input array or string.

\n

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

\n

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

"},{"title":"module:core#rindex","link":"rindex","description":"

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

\n

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

\n

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

"},{"title":"module:core#rtrim","link":"rtrim","description":"

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

\n

Returns the right trimmed string.

"},{"title":"module:core#shift","link":"shift","description":"

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

\n

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

"},{"title":"module:core#signal","link":"signal","description":"

Set or query process signal handler function.

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

"},{"title":"module:core#sleep","link":"sleep","description":"

Pause execution for the given amount of milliseconds.

"},{"title":"module:core#slice","link":"slice","description":"

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

\n

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

"},{"title":"module:core#sort","link":"sort","description":"

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

\n

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

\n

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

\n

Returns the sorted input array.

"},{"title":"module:core#sourcepath","link":"sourcepath","description":"

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

"},{"title":"module:core#splice","link":"splice","description":"

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

\n

The array grows or shrinks as necessary.

\n

Returns the modified input array.

"},{"title":"module:core#split","link":"split","description":"

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

\n

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

\n

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

\n

Returns a new array containing the resulting pieces.

"},{"title":"module:core#sprintf","link":"sprintf","description":"

Formats the given arguments according to the given format string.

\n

See printf() for details.

\n

Returns the formatted string.

"},{"title":"module:core#substr","link":"substr","description":"

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

\n\n

Returns the extracted substring.

"},{"title":"module:core#system","link":"system","description":"

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

\n

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

\n\n

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

\n

Returns the program exit code.

"},{"title":"module:core#time","link":"time","description":"

Returns the current UNIX epoch.

"},{"title":"module:core#timegm","link":"timegm","description":"

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

\n

See timelocal() for details.

"},{"title":"module:core#timelocal","link":"timelocal","description":"

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

\n

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

\n

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

"},{"title":"module:core#trace","link":"trace","description":"

Enables or disables VM opcode tracing.

\n

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

\n

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

"},{"title":"module:core#trim","link":"trim","description":"

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

\n

Returns the trimmed string.

"},{"title":"module:core#type","link":"type","description":"

Query the type of the given value.

\n

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

\n

Returns null when no value or null is passed.

"},{"title":"module:core#uc","link":"uc","description":"

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

\n

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

"},{"title":"module:core#uchr","link":"uchr","description":"

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

\n

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

\n

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

"},{"title":"module:core#uniq","link":"uniq","description":"

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

\n"},{"title":"module:core#unshift","link":"unshift","description":"

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

\n

Returns the last value added to the array.

"},{"title":"module:core#values","link":"values","description":"

Returns an array containing all values of the given object.

\n

Returns null if no object was passed.

"},{"title":"module:core#warn","link":"warn","description":"

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

\n

Returns the amount of bytes printed.

"},{"title":"module:core#wildcard","link":"wildcard","description":"

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

\n\n

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

"},{"title":"module:debug","link":"debug","description":"

Debugger Module

\n

This module provides runtime debug functionality for ucode scripts.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { memdump, traceback } from 'debug';\n\nlet stacktrace = traceback(1);\n\nmemdump("/tmp/dump.txt");\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as debug from 'debug';\n\nlet stacktrace = debug.traceback(1);\n\ndebug.memdump("/tmp/dump.txt");\n
\n

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

\n

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

"},{"title":"module:debug#getinfo","link":"getinfo","description":"

Obtain information about the given value.

\n

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

\n

Returns a dictionary with value type specific details.

\n

Returns null if a null value was provided.

"},{"title":"module:debug#getlocal","link":"getlocal","description":"

Obtain local variable.

\n

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

\n

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

\n

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

\n

Returns a dictionary holding information about the given variable.

\n

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

\n

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

\n

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

"},{"title":"module:debug#getupval","link":"getupval","description":"

Obtain captured variable (upvalue).

\n

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

\n

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

\n

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

\n

Returns a dictionary holding information about the given variable.

\n

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

\n

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

\n

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

\n

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

"},{"title":"module:debug#memdump","link":"memdump","description":"

Write a memory dump report to the given file.

\n

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

\n

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

\n

Returns true if the report has been written.

\n

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

"},{"title":"module:debug#setlocal","link":"setlocal","description":"

Set local variable.

\n

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

\n

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

\n

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

\n

Returns a dictionary holding information about the updated variable.

\n

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

\n

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

\n

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

"},{"title":"module:debug#setupval","link":"setupval","description":"

Set upvalue.

\n

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

\n

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

\n

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

\n

Returns a dictionary holding information about the updated variable.

\n

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

\n

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

\n

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

\n

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

"},{"title":"module:debug#sourcepos","link":"sourcepos","description":"

Obtain information about the current source position.

\n

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

\n

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

\n

Returns null if this function was invoked from C code.

"},{"title":"module:debug#traceback","link":"traceback","description":"

Capture call stack trace.

\n

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

\n

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

"},{"title":"module:debug.LocalInfo","link":"LocalInfo"},{"title":"module:debug.SourcePosition","link":"SourcePosition"},{"title":"module:debug.StackTraceEntry","link":"StackTraceEntry"},{"title":"module:debug.UpvalInfo","link":"UpvalInfo"},{"title":"module:debug.UpvalRef","link":"UpvalRef"},{"title":"module:debug.ValueInformation","link":"ValueInformation"},{"title":"module:fs","link":"fs","description":"

Filesystem Access

\n

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

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { readlink, popen } from 'fs';\n\nlet dest = readlink('/sys/class/net/eth0');\nlet proc = popen('ps ww');\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as fs from 'fs';\n\nlet dest = fs.readlink('/sys/class/net/eth0');\nlet proc = fs.popen('ps ww');\n
\n

Additionally, the filesystem module namespace may also be imported by invoking\nthe ucode interpreter with the -lfs switch.

"},{"title":"module:fs#access","link":"access","description":"

Checks the accessibility of a file or directory.

\n

The optional modes argument specifies the access modes which should be\nchecked. A file is only considered accessible if all access modes specified\nin the modes argument are possible.

\n

The following modes are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ModeDescription
"r"Tests whether the file is readable.
"w"Tests whether the file is writable.
"x"Tests whether the file is executable.
"f"Tests whether the file exists.
\n

Returns true if the given path is accessible or false when it is not.

\n

Returns null if an error occurred, e.g. due to inaccessible intermediate\npath components, invalid path arguments etc.

"},{"title":"module:fs#basename","link":"basename","description":"

Retrieves the base name of a path.

\n

Returns the base name component of the specified path.

\n

Returns null if the path argument is not a string.

"},{"title":"module:fs#chdir","link":"chdir","description":"

Changes the current working directory to the specified path.

\n

Returns true if the permission change was successful.

\n

Returns null if an error occurred, e.g. due to insufficient permissions or\ninvalid arguments.

"},{"title":"module:fs#chmod","link":"chmod","description":"

Changes the permission mode bits of a file or directory.

\n

Returns true if the permission change was successful.

\n

Returns null if an error occurred, e.g. due to insufficient permissions or\ninvalid arguments.

"},{"title":"module:fs#chown","link":"chown","description":"

Changes the owner and group of a file or directory.

\n

The user and group may be specified either as uid or gid number respectively,\nor as a string containing the user or group name, in which case it is\nresolved to the proper uid/gid first.

\n

If either the user or group parameter is omitted or given as -1,\nit is not changed.

\n

Returns true if the ownership change was successful.

\n

Returns null if an error occurred or if a user/group name cannot be\nresolved to a uid/gid value.

"},{"title":"module:fs#dirname","link":"dirname","description":"

Retrieves the directory name of a path.

\n

Returns the directory name component of the specified path.

\n

Returns null if the path argument is not a string.

"},{"title":"module:fs#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs#fdopen","link":"fdopen","description":"

Associates a file descriptor number with a file handle object.

\n

The mode argument controls how the file handle object is opened\nand must match the open mode of the underlying descriptor.

\n

It may be set to one of the following values:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ModeDescription
"r"Opens a file stream for reading. The file descriptor must be valid and opened in read mode.
"w"Opens a file stream for writing. The file descriptor must be valid and opened in write mode.
"a"Opens a file stream for appending. The file descriptor must be valid and opened in write mode.
"r+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"w+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"a+"Opens a file stream for both reading and appending. The file descriptor must be valid and opened in read/write mode.
\n

Returns the file handle object associated with the file descriptor.

"},{"title":"module:fs#getcwd","link":"getcwd","description":"

Retrieves the current working directory.

\n

Returns a string containing the current working directory path.

\n

Returns null if an error occurred.

"},{"title":"module:fs#lsdir","link":"lsdir","description":"

Lists the content of a directory.

\n

Returns a sorted array of the names of files and directories in the specified\ndirectory.

\n

Returns null if an error occurred, e.g. if the specified directory cannot\nbe opened.

"},{"title":"module:fs#lstat","link":"lstat","description":"

Retrieves information about a file or directory, without following symbolic\nlinks.

\n

Returns an object containing information about the file or directory.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#mkdir","link":"mkdir","description":"

Creates a new directory.

\n

Returns true if the directory was successfully created.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#mkstemp","link":"mkstemp","description":"

Creates a unique, ephemeral temporary file.

\n

Creates a new temporary file, opens it in read and write mode, unlinks it and\nreturns a file handle object referring to the yet open but deleted file.

\n

Upon closing the handle, the associated file will automatically vanish from\nthe system.

\n

The optional path template argument may be used to override the path and name\nchosen for the temporary file. If the path template contains no path element,\n/tmp/ is prepended, if it does not end with XXXXXX, then * .XXXXXX is\nappended to it. The XXXXXX sequence is replaced with a random value\nensuring uniqueness of the temporary file name.

\n

Returns a file handle object referring to the ephemeral file on success.

\n

Returns null if an error occurred, e.g. on insufficient permissions or\ninaccessible directory.

"},{"title":"module:fs#open","link":"open","description":"

Opens a file.

\n

The mode argument specifies the way the file is opened, it may\nstart with one of the following values:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ModeDescription
"r"Opens a file for reading. The file must exist.
"w"Opens a file for writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a"Opens a file for appending. Data is written at the end of the file. If the file does not exist, it is created.
"r+"Opens a file for both reading and writing. The file must exist.
"w+"Opens a file for both reading and writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a+"Opens a file for both reading and appending. Data can be read and written at the end of the file. If the file does not exist, it is created.
\n

Additionally, the following flag characters may be appended to\nthe mode value:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
FlagDescription
"x"Opens a file for exclusive creation. If the file exists, the open call fails.
"e"Opens a file with the O_CLOEXEC flag set, ensuring that the file descriptor is closed on exec calls.
\n

If the mode is one of "w…" or "a…", the permission argument\ncontrols the filesystem permissions bits used when creating\nthe file.

\n

Returns a file handle object associated with the opened file.

"},{"title":"module:fs#opendir","link":"opendir","description":"

Opens a directory and returns a directory handle associated with the open\ndirectory descriptor.

\n

Returns a director handle referring to the open directory.

\n

Returns null if an error occurred.

"},{"title":"module:fs#pipe","link":"pipe","description":"

Creates a pipe and returns file handle objects associated with the read- and\nwrite end of the pipe respectively.

\n

Returns a two element array containing both a file handle object open in read\nmode referring to the read end of the pipe and a file handle object open in\nwrite mode referring to the write end of the pipe.

\n

Returns null if an error occurred.

"},{"title":"module:fs#popen","link":"popen","description":"

Starts a process and returns a handle representing the executed process.

\n

The handle will be connected to the process stdin or stdout, depending on the\nvalue of the mode argument.

\n

The mode argument may be either "r" to open the process for reading (connect\nto its stdin) or "w" to open the process for writing (connect to its stdout).

\n

The mode character "r" or "w" may be optionally followed by "e" to apply the\nFD_CLOEXEC flag onto the open descriptor.

\n

Returns a process handle referring to the executed process.

\n

Returns null if an error occurred.

"},{"title":"module:fs#readfile","link":"readfile","description":"

Reads the content of a file, optionally limited to the given amount of bytes.

\n

Returns a string containing the file contents.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#readlink","link":"readlink","description":"

Reads the target path of a symbolic link.

\n

Returns a string containing the target path.

\n

Returns null if an error occurred.

"},{"title":"module:fs#realpath","link":"realpath","description":"

Resolves the absolute path of a file or directory.

\n

Returns a string containing the resolved path.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#rename","link":"rename","description":"

Renames or moves a file or directory.

\n

Returns true if the rename operation was successful.

\n

Returns null if an error occurred.

"},{"title":"module:fs#rmdir","link":"rmdir","description":"

Removes the specified directory.

\n

Returns true if the directory was successfully removed.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#stat","link":"stat","description":"

Retrieves information about a file or directory.

\n

Returns an object containing information about the file or directory.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#symlink","link":"symlink","description":"

Creates a new symbolic link.

\n

Returns true if the symlink was successfully created.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#unlink","link":"unlink","description":"

Removes the specified file or symbolic link.

\n

Returns true if the unlink operation was successful.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#writefile","link":"writefile","description":"

Writes the given data to a file, optionally truncated to the given amount\nof bytes.

\n

In case the given data is not a string, it is converted to a string before\nbeing written into the file. String values are written as-is, integer and\ndouble values are written in decimal notation, boolean values are written as\ntrue or false while arrays and objects are converted to their JSON\nrepresentation before being written into the file. The null value is\nrepresented by an empty string so writefile(…, null) would write an empty\nfile. Resource values are written in the form <type address>, e.g.\n<fs.file 0x7f60f0981760>.

\n

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

\n

If a file already exists at the given path, it is truncated. If no file\nexists, it is created with default permissions 0o666 masked by the currently\neffective umask.

\n

Returns the number of bytes written.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs.FileStatResult","link":"FileStatResult"},{"title":"module:fs.dir","link":"dir","description":"

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

"},{"title":"module:fs.dir#close","link":"close","description":"

Closes the directory handle.

\n

Closes the underlying file descriptor referring to the opened directory.

\n

Returns true if the handle was properly closed.

\n

Returns null if an error occurred.

"},{"title":"module:fs.dir#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs.dir#read","link":"read","description":"

Read the next entry from the open directory.

\n

Returns a string containing the entry name.

\n

Returns null if there are no more entries to read.

\n

Returns null if an error occurred.

"},{"title":"module:fs.dir#seek","link":"seek","description":"

Set read position.

\n

Sets the read position within the open directory handle to the given offset\nvalue. The offset value should be obtained by a previous call to tell() as\nthe specific integer values are implementation defined.

\n

Returns true if the read position was set.

\n

Returns null if an error occurred.

"},{"title":"module:fs.dir#tell","link":"tell","description":"

Obtain current read position.

\n

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

\n

Returns an integer referring to the current position.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file","link":"file","description":"

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

"},{"title":"module:fs.file#close","link":"close","description":"

Closes the file handle.

\n

Upon calling close() on the handle, buffered data is flushed and the\nunderlying file descriptor is closed.

\n

Returns true if the handle was properly closed.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs.file#fileno","link":"fileno","description":"

Obtains the number of the handle's underlying file descriptor.

\n

Returns the descriptor number.

\n

Returns null on error.

"},{"title":"module:fs.file#flush","link":"flush","description":"

Forces a write of all buffered data to the underlying handle.

\n

Returns true if the data was successfully flushed.

\n

Returns null on error.

"},{"title":"module:fs.file#isatty","link":"isatty","description":"

Check for TTY.

\n

Checks whether the open file handle refers to a TTY (terminal) device.

\n

Returns true if the handle refers to a terminal.

\n

Returns false if the handle refers to another kind of file.

\n

Returns null on error.

"},{"title":"module:fs.file#read","link":"read","description":"

Reads a chunk of data from the file handle.

\n

The length argument may be either a positive number of bytes to read, in\nwhich case the read call returns up to that many bytes, or a string to\nspecify a dynamic read size.

\n\n

Returns a string containing the read data.

\n

Returns an empty string on EOF.

\n

Returns null if a read error occurred.

"},{"title":"module:fs.file#seek","link":"seek","description":"

Set file read position.

\n

Set the read position of the open file handle to the given offset and\nposition.

\n

Returns true if the read position was set.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file#tell","link":"tell","description":"

Obtain current read position.

\n

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

\n

Returns an integer containing the current read offset in bytes.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file#write","link":"write","description":"

Writes a chunk of data to the file handle.

\n

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

\n

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

\n

Returns the number of bytes written.

\n

Returns null if a write error occurred.

"},{"title":"module:fs.proc","link":"proc","description":"

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

"},{"title":"module:fs.proc#close","link":"close","description":"

Closes the program handle and awaits program termination.

\n

Upon calling close() on the handle, the program's input or output stream\n(depending on the open mode) is closed. Afterwards, the function awaits the\ntermination of the underlying program and returns its exit code.

\n\n

Returns a negative signal number if the program was terminated by a signal.

\n

Returns a positive exit code if the program terminated normally.

\n

Returns null if an error occurred.

"},{"title":"module:fs.proc#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs.proc#fileno","link":"fileno","description":"

Obtains the number of the handle's underlying file descriptor.

\n

Returns the descriptor number.

\n

Returns null on error.

"},{"title":"module:fs.proc#flush","link":"flush","description":"

Forces a write of all buffered data to the underlying handle.

\n

Returns true if the data was successfully flushed.

\n

Returns null on error.

"},{"title":"module:fs.proc#read","link":"read","description":"

Reads a chunk of data from the program handle.

\n

The length argument may be either a positive number of bytes to read, in\nwhich case the read call returns up to that many bytes, or a string to\nspecify a dynamic read size.

\n\n

Returns a string containing the read data.

\n

Returns an empty string on EOF.

\n

Returns null if a read error occurred.

"},{"title":"module:fs.proc#write","link":"write","description":"

Writes a chunk of data to the program handle.

\n

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

\n

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

\n

Returns the number of bytes written.

\n

Returns null if a write error occurred.

"},{"title":"module:math","link":"math","description":"

Mathematical Functions

\n

The math module bundles various mathematical and trigonometrical functions.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { pow, rand } from 'math';\n\nlet x = pow(2, 5);\nlet y = rand();\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as math from 'math';\n\nlet x = math.pow(2, 5);\nlet y = math.rand();\n
\n

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

"},{"title":"module:math#abs","link":"abs","description":"

Returns the absolute value of the given numeric value.

"},{"title":"module:math#atan2","link":"atan2","description":"

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

\n

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

\n\n

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

"},{"title":"module:math#cos","link":"cos","description":"

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

\n

Returns the resulting consine value.

\n

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

"},{"title":"module:math#exp","link":"exp","description":"

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

\n

On success, returns the exponential value of x.

\n\n

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

"},{"title":"module:math#isnan","link":"isnan","description":"

Tests whether x is a NaN double.

\n

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

\n

Returns true if the value is NaN, otherwise false.

\n

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

"},{"title":"module:math#log","link":"log","description":"

Calculates the natural logarithm of x.

\n

On success, returns the natural logarithm of x.

\n\n

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

"},{"title":"module:math#pow","link":"pow","description":"

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

\n

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

\n\n

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

"},{"title":"module:math#rand","link":"rand","description":"

Produces a pseudo-random positive integer.

\n

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

\n

The {@link module:math~srand srand()} function sets its argument as the\nseed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are\nrepeatable by calling {@link module:math~srand srand()} with the same\nseed value.

\n

If no seed value is explicitly set by calling\n{@link module:math~srand srand()} prior to the first call to rand(),\nthe math module will automatically seed the PRNG once, using the current\ntime of day in milliseconds as seed value.

"},{"title":"module:math#sin","link":"sin","description":"

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

\n

Returns the resulting sine value.

\n\n

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

"},{"title":"module:math#sqrt","link":"sqrt","description":"

Calculates the nonnegative square root of x.

\n

Returns the resulting square root value.

\n\n

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

"},{"title":"module:math#srand","link":"srand","description":"

Seeds the pseudo-random number generator.

\n

This functions seeds the PRNG with the given value and thus affects the\npseudo-random integer sequence produced by subsequent calls to\n{@link module:math~rand rand()}.

\n

Setting the same seed value will result in the same pseudo-random numbers\nproduced by {@link module:math~rand rand()}.

"},{"title":"module:struct","link":"struct","description":"

Handle Packed Binary Data

\n

The struct module provides routines for interpreting byte strings as packed\nbinary data.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { pack, unpack } from 'struct';\n\nlet buffer = pack('bhl', -13, 1234, 444555666);\nlet values = unpack('bhl', buffer);\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as struct from 'struct';\n\nlet buffer = struct.pack('bhl', -13, 1234, 444555666);\nlet values = struct.unpack('bhl', buffer);\n
\n

Additionally, the struct module namespace may also be imported by invoking\nthe ucode interpreter with the -lstruct switch.

\n

Format Strings

\n

Format strings describe the data layout when packing and unpacking data.\nThey are built up from format-characters, which specify the type of data\nbeing packed/unpacked. In addition, special characters control the byte\norder, size and alignment.

\n

Each format string consists of an optional prefix character which describes\nthe overall properties of the data and one or more format characters which\ndescribe the actual data values and padding.

\n

Byte Order, Size, and Alignment

\n

By default, C types are represented in the machine's native format and byte\norder, and properly aligned by skipping pad bytes if necessary (according to\nthe rules used by the C compiler).

\n

This behavior is chosen so that the bytes of a packed struct correspond\nexactly to the memory layout of the corresponding C struct.

\n

Whether to use native byte ordering and padding or standard formats depends\non the application.

\n

Alternatively, the first character of the format string can be used to indicate\nthe byte order, size and alignment of the packed data, according to the\nfollowing table:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
CharacterByte orderSizeAlignment
@nativenativenative
=nativestandardnone
<little-endianstandardnone
>big-endianstandardnone
!network (= big-endian)standardnone
\n

If the first character is not one of these, '@' is assumed.

\n

Native byte order is big-endian or little-endian, depending on the\nhost system. For example, Intel x86, AMD64 (x86-64), and Apple M1 are\nlittle-endian; IBM z and many legacy architectures are big-endian.

\n

Native size and alignment are determined using the C compiler's\nsizeof expression. This is always combined with native byte order.

\n

Standard size depends only on the format character; see the table in\nthe format-characters section.

\n

Note the difference between '@' and '=': both use native byte order,\nbut the size and alignment of the latter is standardized.

\n

The form '!' represents the network byte order which is always big-endian\nas defined in IETF RFC 1700.

\n

There is no way to indicate non-native byte order (force byte-swapping); use\nthe appropriate choice of '<' or '>'.

\n

Notes:

\n

(1) Padding is only automatically added between successive structure members.\nNo padding is added at the beginning or the end of the encoded struct.

\n

(2) No padding is added when using non-native size and alignment, e.g.\nwith '<', '>', '=', and '!'.

\n

(3) To align the end of a structure to the alignment requirement of a\nparticular type, end the format with the code for that type with a repeat\ncount of zero.

\n

Format Characters

\n

Format characters have the following meaning; the conversion between C and\nucode values should be obvious given their types. The 'Standard size' column\nrefers to the size of the packed value in bytes when using standard size;\nthat is, when the format string starts with one of '<', '>', '!' or\n'='. When using native size, the size of the packed value is platform\ndependent.

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
FormatC TypeUcode typeStandard sizeNotes
xpad byteno value(7)
ccharstring1
bsigned charint1(1), (2)
Bunsigned charint1(2)
?_Boolbool1(1)
hshortint2(2)
Hunsigned shortint2(2)
iintint4(2)
Iunsigned intint4(2)
llongint4(2)
Lunsigned longint4(2)
qlong longint8(2)
Qunsigned long longint8(2)
nssize_tint(3)
Nsize_tint(3)
e(6)double2(4)
ffloatdouble4(4)
ddoubledouble8(4)
schar[]double(9)
pchar[]double(8)
Pvoid *int(5)
*char[]string(10)
\n

Notes:

\n\n

A format character may be preceded by an integral repeat count. For example,\nthe format string '4h' means exactly the same as 'hhhh'.

\n

Whitespace characters between formats are ignored; a count and its format\nmust not contain whitespace though.

\n

When packing a value x using one of the integer formats ('b',\n'B', 'h', 'H', 'i', 'I', 'l', 'L',\n'q', 'Q'), if x is outside the valid range for that format, a type\nerror exception is raised.

\n

For the '?' format character, the return value is either true or false.\nWhen packing, the truish result value of the argument is used. Either 0 or 1\nin the native or standard bool representation will be packed, and any\nnon-zero value will be true when unpacking.

\n

Examples

\n

Note:\nNative byte order examples (designated by the '@' format prefix or\nlack of any prefix character) may not match what the reader's\nmachine produces as\nthat depends on the platform and compiler.

\n

Pack and unpack integers of three different sizes, using big endian\nordering:

\n
import { pack, unpack } from 'struct';\n\npack(">bhl", 1, 2, 3);  // "\\x01\\x00\\x02\\x00\\x00\\x00\\x03"\nunpack(">bhl", "\\x01\\x00\\x02\\x00\\x00\\x00\\x03");  // [ 1, 2, 3 ]\n
\n

Attempt to pack an integer which is too large for the defined field:

\n
$ ucode -lstruct -p 'struct.pack(">h", 99999)'\nType error: Format 'h' requires numeric argument between -32768 and 32767\nIn [-p argument], line 1, byte 24:\n\n `struct.pack(">h", 99999)`\n  Near here -------------^\n
\n

Demonstrate the difference between 's' and 'c' format characters:

\n
import { pack } from 'struct';\n\npack("@ccc", "1", "2", "3");  // "123"\npack("@3s", "123");           // "123"\n
\n

The ordering of format characters may have an impact on size in native\nmode since padding is implicit. In standard mode, the user is\nresponsible for inserting any desired padding.

\n

Note in the first pack() call below that three NUL bytes were added after\nthe packed '#' to align the following integer on a four-byte boundary.\nIn this example, the output was produced on a little endian machine:

\n
import { pack } from 'struct';\n\npack("@ci", "#", 0x12131415);  // "#\\x00\\x00\\x00\\x15\\x14\\x13\\x12"\npack("@ic", 0x12131415, "#");  // "\\x15\\x14\\x13\\x12#"\n
\n

The following format 'ih0i' results in two pad bytes being added at the\nend, assuming the platform's ints are aligned on 4-byte boundaries:

\n
import { pack } from 'struct';\n\npack("ih0i", 0x01010101, 0x0202);  // "\\x01\\x01\\x01\\x01\\x02\\x02\\x00\\x00"\n
\n

Use the wildcard format to extract the remainder of the input data:

\n
import { unpack } from 'struct';\n\nunpack("ccc*", "foobarbaz");   // [ "f", "o", "o", "barbaz" ]\nunpack("ccc3*", "foobarbaz");  // [ "f", "o", "o", "bar" ]\n
\n

Use the wildcard format to pack binary stings as-is into the result data:

\n
import { pack } from 'struct';\n\npack("h*h", 0x0101, "\\x02\\x00\\x03", 0x0404);  // "\\x01\\x01\\x02\\x00\\x03\\x04\\x04"\npack("c3*c", "a", "foobar", "c");  // "afooc"\n
"},{"title":"module:struct#new","link":"new","description":"

Precompile format string.

\n

The new() function precompiles the given format string argument and returns\na struct object instance useful for packing and unpacking multiple items\nwithout having to recompute the internal format each time.

\n

Returns an precompiled struct format instance.

\n

Raises a runtime exception if the format string is invalid.

"},{"title":"module:struct#pack","link":"pack","description":"

Pack given values according to specified format.

\n

The pack() function creates a byte string containing the argument values\npacked according to the given format string.

\n

Returns the packed string.

\n

Raises a runtime exception if a given argument value does not match the\nrequired type of the corresponding format string directive or if and invalid\nformat string is provided.

"},{"title":"module:struct#unpack","link":"unpack","description":"

Unpack given byte string according to specified format.

\n

The unpack() function interpretes a byte string according to the given\nformat string and returns the resulting values. If the optional offset\nargument is given, unpacking starts from this byte position within the input.\nIf not specified, the start offset defaults to 0, the start of the given\ninput string.

\n

Returns an array of unpacked values.

\n

Raises a runtime exception if the format string is invalid or if an invalid\ninput string or offset value is given.

"},{"title":"module:struct.instance","link":"instance","description":"

Represents a struct instance created by new().

"},{"title":"module:struct.instance#pack","link":"pack","description":"

Pack given values.

\n

The pack() function creates a byte string containing the argument values\npacked according to the given format instance.

\n

Returns the packed string.

\n

Raises a runtime exception if a given argument value does not match the\nrequired type of the corresponding format string directive.

"},{"title":"module:struct.instance#unpack","link":"unpack","description":"

Unpack given byte string.

\n

The unpack() function interpretes a byte string according to the given\nformat instance and returns the resulting values. If the optional offset\nargument is given, unpacking starts from this byte position within the input.\nIf not specified, the start offset defaults to 0, the start of the given\ninput string.

\n

Returns an array of unpacked values.

\n

Raises a runtime exception if an invalid input string or offset value is\ngiven.

"}]} \ No newline at end of file +{"list":[{"title":"module:core","link":"core","description":"

Builtin functions

\n

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

"},{"title":"module:core#arrtoip","link":"arrtoip","description":"

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

\n

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

\n

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

"},{"title":"module:core#assert","link":"assert","description":"

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

\n

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

"},{"title":"module:core#b64dec","link":"b64dec","description":"

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

\n"},{"title":"module:core#b64enc","link":"b64enc","description":"

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

\n"},{"title":"module:core#call","link":"call","description":"

Calls the given function value with a modified environment.

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

\n

Forwards exceptions thrown by the invoked function.

"},{"title":"module:core#chr","link":"chr","description":"

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

\n

Returns a new strings consisting of the given byte values.

"},{"title":"module:core#clock","link":"clock","description":"

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

\n

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

\n

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

\n

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

"},{"title":"module:core#die","link":"die","description":"

Raise an exception with the given message and abort execution.

"},{"title":"module:core#exists","link":"exists","description":"

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

\n

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

"},{"title":"module:core#exit","link":"exit","description":"

Terminate the interpreter with the given exit code.

\n

This function does not return.

"},{"title":"module:core#filter","link":"filter","description":"

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

\n

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

\n
    \n
  1. The array value
  2. \n
  3. The current index
  4. \n
  5. The array being filtered
  6. \n
\n

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

"},{"title":"module:core#gc","link":"gc","description":"

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

\n

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

\n

The following operations are defined:

\n\n

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

"},{"title":"module:core#getenv","link":"getenv","description":"

Query an environment variable or then entire environment.

\n

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

"},{"title":"module:core#gmtime","link":"gmtime","description":"

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

\n

See localtime() for details on the return value.

"},{"title":"module:core#hex","link":"hex","description":"

Converts the given hexadecimal string into a number.

\n

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

"},{"title":"module:core#hexdec","link":"hexdec","description":"

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

\n

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

\n

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

\n

Returns the decoded byte string on success.

"},{"title":"module:core#hexenc","link":"hexenc","description":"

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

"},{"title":"module:core#include","link":"include","description":"

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

\n

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

\n

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

"},{"title":"module:core#index","link":"index","description":"

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

\n

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

\n

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

"},{"title":"module:core#int","link":"int","description":"

Converts the given value to an integer.

\n

Returns NaN if the value is not convertible.

"},{"title":"module:core#iptoarr","link":"iptoarr","description":"

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

\n

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

\n

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

"},{"title":"module:core#join","link":"join","description":"

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

\n

Returns null if the second argument is not an array.

"},{"title":"module:core#json","link":"json","description":"

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

\n

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

\n

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

\n

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

\n

Returns the parsed JSON data.

"},{"title":"module:core#keys","link":"keys","description":"

Enumerates all object key names.

\n

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

"},{"title":"module:core#lc","link":"lc","description":"

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

\n

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

"},{"title":"module:core#length","link":"length","description":"

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

\n

Returns the length of the given value.

\n\n

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

"},{"title":"module:core#loadfile","link":"loadfile","description":"

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

\n

See loadstring() for details.

\n

Returns the compiled program entry function.

\n

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

"},{"title":"module:core#loadstring","link":"loadstring","description":"

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

\n

The optional options dictionary overrides parse and compile options.

\n\n

The following keys in the options dictionary are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
KeyTypeDescription
lstrip_blocksboolStrip leading whitespace before statement template blocks
trim_blocksboolStrip newline after statement template blocks
strict_declarationsboolTreat access to undefined variables as fatal error
raw_modeboolCompile source in script mode, don't treat it as template
module_search_patharrayOverride compile time module search path
force_dynlink_listarrayList of module names to treat as dynamic extensions
\n

Unrecognized keys are ignored, unspecified options default to those of the\nrunning program.

\n

Returns the compiled program entry function.

\n

Throws an exception on compilation errors.

"},{"title":"module:core#localtime","link":"localtime","description":"

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

\n

The resulting dictionary contains the following fields:

\n\n

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

"},{"title":"module:core#ltrim","link":"ltrim","description":"

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

\n

Returns the left trimmed string.

"},{"title":"module:core#map","link":"map","description":"

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

\n

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

"},{"title":"module:core#match","link":"match","description":"

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

\n

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

\n

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

\n

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

"},{"title":"module:core#max","link":"max","description":"

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

"},{"title":"module:core#min","link":"min","description":"

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

"},{"title":"module:core#ord","link":"ord","description":"

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

\n

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

\n

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

"},{"title":"module:core#pop","link":"pop","description":"

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

\n

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

"},{"title":"module:core#print","link":"print","description":"

Print any of the given values to stdout.

\n

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

\n

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

\n

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

\n

Examples:

\n
print(1 != 2);                       // Will print 'true'\nprint(0xff);                         // Will print '255'\nprint(2e3);                          // Will print '2000'\nprint(null);                         // Will print nothing\nprint({ hello: true, world: 123 });  // Will print '{ "hello": true, "world": 123 }'\nprint([1,2,3]);                      // Will print '[ 1, 2, 3 ]'\n\nprint(proto({ foo: "bar" },          // Will print 'MyObj'\n  { tostring: () => "MyObj" }));     // instead of '{ "foo": "bar" }'\n\n
\n

Returns the amount of bytes printed.

"},{"title":"module:core#printf","link":"printf","description":"

Formats the given arguments according to the given format string and outputs\nthe result to stdout.

\n

Ucode supports a restricted subset of the formats allowed by the underlying\nlibc's printf() implementation, namely it allows the d, i, o, u,\nx, X, e, E, f, F, g, G, c and s conversions.

\n

Additionally, an ucode specific J format is implemented, which causes the\ncorresponding value to be formatted as JSON string. By prefixing the J\nformat letter with a precision specifier, the resulting JSON output will be\npretty printed. A precision of 0 will use tabs for indentation, any other\npositive precision will use that many spaces for indentation while a negative\nor omitted precision specifier will turn off pretty printing.

\n

Other format specifiers such as n or z are not accepted and returned\nverbatim. Format specifiers including * directives are rejected as well.

\n

Returns the number of bytes written to the standard output.

"},{"title":"module:core#proto","link":"proto","description":"

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

\n

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

\n

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

\n

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

"},{"title":"module:core#push","link":"push","description":"

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

\n

Returns the last pushed value.

"},{"title":"module:core#regexp","link":"regexp","description":"

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

\n\n

Returns the compiled regular expression value.

"},{"title":"module:core#render","link":"render","description":"

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

\n

The second argument is treated as the scope.

\n

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

\n

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

"},{"title":"module:core#replace","link":"replace","description":"

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

\n\n

Returns a new string with the pattern replaced.

"},{"title":"module:core#reverse","link":"reverse","description":"

Reverse the order of the given input array or string.

\n

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

\n

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

"},{"title":"module:core#rindex","link":"rindex","description":"

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

\n

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

\n

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

"},{"title":"module:core#rtrim","link":"rtrim","description":"

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

\n

Returns the right trimmed string.

"},{"title":"module:core#shift","link":"shift","description":"

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

\n

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

"},{"title":"module:core#signal","link":"signal","description":"

Set or query process signal handler function.

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

\n

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

"},{"title":"module:core#sleep","link":"sleep","description":"

Pause execution for the given amount of milliseconds.

"},{"title":"module:core#slice","link":"slice","description":"

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

\n

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

"},{"title":"module:core#sort","link":"sort","description":"

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

\n

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

\n

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

\n

Returns the sorted input array.

"},{"title":"module:core#sourcepath","link":"sourcepath","description":"

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

"},{"title":"module:core#splice","link":"splice","description":"

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

\n

The array grows or shrinks as necessary.

\n

Returns the modified input array.

"},{"title":"module:core#split","link":"split","description":"

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

\n

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

\n

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

\n

Returns a new array containing the resulting pieces.

"},{"title":"module:core#sprintf","link":"sprintf","description":"

Formats the given arguments according to the given format string.

\n

See printf() for details.

\n

Returns the formatted string.

"},{"title":"module:core#substr","link":"substr","description":"

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

\n\n

Returns the extracted substring.

"},{"title":"module:core#system","link":"system","description":"

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

\n

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

\n\n

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

\n

Returns the program exit code.

"},{"title":"module:core#time","link":"time","description":"

Returns the current UNIX epoch.

"},{"title":"module:core#timegm","link":"timegm","description":"

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

\n

See timelocal() for details.

"},{"title":"module:core#timelocal","link":"timelocal","description":"

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

\n

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

\n

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

"},{"title":"module:core#trace","link":"trace","description":"

Enables or disables VM opcode tracing.

\n

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

\n

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

"},{"title":"module:core#trim","link":"trim","description":"

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

\n

Returns the trimmed string.

"},{"title":"module:core#type","link":"type","description":"

Query the type of the given value.

\n

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

\n

Returns null when no value or null is passed.

"},{"title":"module:core#uc","link":"uc","description":"

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

\n

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

"},{"title":"module:core#uchr","link":"uchr","description":"

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

\n

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

\n

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

"},{"title":"module:core#uniq","link":"uniq","description":"

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

\n"},{"title":"module:core#unshift","link":"unshift","description":"

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

\n

Returns the last value added to the array.

"},{"title":"module:core#values","link":"values","description":"

Returns an array containing all values of the given object.

\n

Returns null if no object was passed.

"},{"title":"module:core#warn","link":"warn","description":"

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

\n

Returns the amount of bytes printed.

"},{"title":"module:core#wildcard","link":"wildcard","description":"

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

\n\n

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

"},{"title":"module:debug","link":"debug","description":"

Debugger Module

\n

This module provides runtime debug functionality for ucode scripts.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { memdump, traceback } from 'debug';\n\nlet stacktrace = traceback(1);\n\nmemdump("/tmp/dump.txt");\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as debug from 'debug';\n\nlet stacktrace = debug.traceback(1);\n\ndebug.memdump("/tmp/dump.txt");\n
\n

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

\n

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

"},{"title":"module:debug#getinfo","link":"getinfo","description":"

Obtain information about the given value.

\n

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

\n

Returns a dictionary with value type specific details.

\n

Returns null if a null value was provided.

"},{"title":"module:debug#getlocal","link":"getlocal","description":"

Obtain local variable.

\n

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

\n

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

\n

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

\n

Returns a dictionary holding information about the given variable.

\n

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

\n

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

\n

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

"},{"title":"module:debug#getupval","link":"getupval","description":"

Obtain captured variable (upvalue).

\n

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

\n

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

\n

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

\n

Returns a dictionary holding information about the given variable.

\n

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

\n

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

\n

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

\n

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

"},{"title":"module:debug#memdump","link":"memdump","description":"

Write a memory dump report to the given file.

\n

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

\n

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

\n

Returns true if the report has been written.

\n

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

"},{"title":"module:debug#setlocal","link":"setlocal","description":"

Set local variable.

\n

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

\n

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

\n

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

\n

Returns a dictionary holding information about the updated variable.

\n

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

\n

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

\n

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

"},{"title":"module:debug#setupval","link":"setupval","description":"

Set upvalue.

\n

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

\n

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

\n

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

\n

Returns a dictionary holding information about the updated variable.

\n

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

\n

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

\n

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

\n

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

"},{"title":"module:debug#sourcepos","link":"sourcepos","description":"

Obtain information about the current source position.

\n

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

\n

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

\n

Returns null if this function was invoked from C code.

"},{"title":"module:debug#traceback","link":"traceback","description":"

Capture call stack trace.

\n

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

\n

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

"},{"title":"module:debug.LocalInfo","link":"LocalInfo"},{"title":"module:debug.SourcePosition","link":"SourcePosition"},{"title":"module:debug.StackTraceEntry","link":"StackTraceEntry"},{"title":"module:debug.UpvalInfo","link":"UpvalInfo"},{"title":"module:debug.UpvalRef","link":"UpvalRef"},{"title":"module:debug.ValueInformation","link":"ValueInformation"},{"title":"module:fs","link":"fs","description":"

Filesystem Access

\n

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

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { readlink, popen } from 'fs';\n\nlet dest = readlink('/sys/class/net/eth0');\nlet proc = popen('ps ww');\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as fs from 'fs';\n\nlet dest = fs.readlink('/sys/class/net/eth0');\nlet proc = fs.popen('ps ww');\n
\n

Additionally, the filesystem module namespace may also be imported by invoking\nthe ucode interpreter with the -lfs switch.

"},{"title":"module:fs#access","link":"access","description":"

Checks the accessibility of a file or directory.

\n

The optional modes argument specifies the access modes which should be\nchecked. A file is only considered accessible if all access modes specified\nin the modes argument are possible.

\n

The following modes are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ModeDescription
"r"Tests whether the file is readable.
"w"Tests whether the file is writable.
"x"Tests whether the file is executable.
"f"Tests whether the file exists.
\n

Returns true if the given path is accessible or false when it is not.

\n

Returns null if an error occurred, e.g. due to inaccessible intermediate\npath components, invalid path arguments etc.

"},{"title":"module:fs#basename","link":"basename","description":"

Retrieves the base name of a path.

\n

Returns the base name component of the specified path.

\n

Returns null if the path argument is not a string.

"},{"title":"module:fs#chdir","link":"chdir","description":"

Changes the current working directory to the specified path.

\n

Returns true if the permission change was successful.

\n

Returns null if an error occurred, e.g. due to insufficient permissions or\ninvalid arguments.

"},{"title":"module:fs#chmod","link":"chmod","description":"

Changes the permission mode bits of a file or directory.

\n

Returns true if the permission change was successful.

\n

Returns null if an error occurred, e.g. due to insufficient permissions or\ninvalid arguments.

"},{"title":"module:fs#chown","link":"chown","description":"

Changes the owner and group of a file or directory.

\n

The user and group may be specified either as uid or gid number respectively,\nor as a string containing the user or group name, in which case it is\nresolved to the proper uid/gid first.

\n

If either the user or group parameter is omitted or given as -1,\nit is not changed.

\n

Returns true if the ownership change was successful.

\n

Returns null if an error occurred or if a user/group name cannot be\nresolved to a uid/gid value.

"},{"title":"module:fs#dirname","link":"dirname","description":"

Retrieves the directory name of a path.

\n

Returns the directory name component of the specified path.

\n

Returns null if the path argument is not a string.

"},{"title":"module:fs#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs#fdopen","link":"fdopen","description":"

Associates a file descriptor number with a file handle object.

\n

The mode argument controls how the file handle object is opened\nand must match the open mode of the underlying descriptor.

\n

It may be set to one of the following values:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ModeDescription
"r"Opens a file stream for reading. The file descriptor must be valid and opened in read mode.
"w"Opens a file stream for writing. The file descriptor must be valid and opened in write mode.
"a"Opens a file stream for appending. The file descriptor must be valid and opened in write mode.
"r+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"w+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"a+"Opens a file stream for both reading and appending. The file descriptor must be valid and opened in read/write mode.
\n

Returns the file handle object associated with the file descriptor.

"},{"title":"module:fs#getcwd","link":"getcwd","description":"

Retrieves the current working directory.

\n

Returns a string containing the current working directory path.

\n

Returns null if an error occurred.

"},{"title":"module:fs#lsdir","link":"lsdir","description":"

Lists the content of a directory.

\n

Returns a sorted array of the names of files and directories in the specified\ndirectory.

\n

Returns null if an error occurred, e.g. if the specified directory cannot\nbe opened.

"},{"title":"module:fs#lstat","link":"lstat","description":"

Retrieves information about a file or directory, without following symbolic\nlinks.

\n

Returns an object containing information about the file or directory.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#mkdir","link":"mkdir","description":"

Creates a new directory.

\n

Returns true if the directory was successfully created.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#mkstemp","link":"mkstemp","description":"

Creates a unique, ephemeral temporary file.

\n

Creates a new temporary file, opens it in read and write mode, unlinks it and\nreturns a file handle object referring to the yet open but deleted file.

\n

Upon closing the handle, the associated file will automatically vanish from\nthe system.

\n

The optional path template argument may be used to override the path and name\nchosen for the temporary file. If the path template contains no path element,\n/tmp/ is prepended, if it does not end with XXXXXX, then * .XXXXXX is\nappended to it. The XXXXXX sequence is replaced with a random value\nensuring uniqueness of the temporary file name.

\n

Returns a file handle object referring to the ephemeral file on success.

\n

Returns null if an error occurred, e.g. on insufficient permissions or\ninaccessible directory.

"},{"title":"module:fs#open","link":"open","description":"

Opens a file.

\n

The mode argument specifies the way the file is opened, it may\nstart with one of the following values:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ModeDescription
"r"Opens a file for reading. The file must exist.
"w"Opens a file for writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a"Opens a file for appending. Data is written at the end of the file. If the file does not exist, it is created.
"r+"Opens a file for both reading and writing. The file must exist.
"w+"Opens a file for both reading and writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a+"Opens a file for both reading and appending. Data can be read and written at the end of the file. If the file does not exist, it is created.
\n

Additionally, the following flag characters may be appended to\nthe mode value:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
FlagDescription
"x"Opens a file for exclusive creation. If the file exists, the open call fails.
"e"Opens a file with the O_CLOEXEC flag set, ensuring that the file descriptor is closed on exec calls.
\n

If the mode is one of "w…" or "a…", the permission argument\ncontrols the filesystem permissions bits used when creating\nthe file.

\n

Returns a file handle object associated with the opened file.

"},{"title":"module:fs#opendir","link":"opendir","description":"

Opens a directory and returns a directory handle associated with the open\ndirectory descriptor.

\n

Returns a director handle referring to the open directory.

\n

Returns null if an error occurred.

"},{"title":"module:fs#pipe","link":"pipe","description":"

Creates a pipe and returns file handle objects associated with the read- and\nwrite end of the pipe respectively.

\n

Returns a two element array containing both a file handle object open in read\nmode referring to the read end of the pipe and a file handle object open in\nwrite mode referring to the write end of the pipe.

\n

Returns null if an error occurred.

"},{"title":"module:fs#popen","link":"popen","description":"

Starts a process and returns a handle representing the executed process.

\n

The handle will be connected to the process stdin or stdout, depending on the\nvalue of the mode argument.

\n

The mode argument may be either "r" to open the process for reading (connect\nto its stdin) or "w" to open the process for writing (connect to its stdout).

\n

The mode character "r" or "w" may be optionally followed by "e" to apply the\nFD_CLOEXEC flag onto the open descriptor.

\n

Returns a process handle referring to the executed process.

\n

Returns null if an error occurred.

"},{"title":"module:fs#readfile","link":"readfile","description":"

Reads the content of a file, optionally limited to the given amount of bytes.

\n

Returns a string containing the file contents.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#readlink","link":"readlink","description":"

Reads the target path of a symbolic link.

\n

Returns a string containing the target path.

\n

Returns null if an error occurred.

"},{"title":"module:fs#realpath","link":"realpath","description":"

Resolves the absolute path of a file or directory.

\n

Returns a string containing the resolved path.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#rename","link":"rename","description":"

Renames or moves a file or directory.

\n

Returns true if the rename operation was successful.

\n

Returns null if an error occurred.

"},{"title":"module:fs#rmdir","link":"rmdir","description":"

Removes the specified directory.

\n

Returns true if the directory was successfully removed.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#stat","link":"stat","description":"

Retrieves information about a file or directory.

\n

Returns an object containing information about the file or directory.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs#symlink","link":"symlink","description":"

Creates a new symbolic link.

\n

Returns true if the symlink was successfully created.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#unlink","link":"unlink","description":"

Removes the specified file or symbolic link.

\n

Returns true if the unlink operation was successful.

\n

Returns null if an error occurred, e.g. due to inexistent path.

"},{"title":"module:fs#writefile","link":"writefile","description":"

Writes the given data to a file, optionally truncated to the given amount\nof bytes.

\n

In case the given data is not a string, it is converted to a string before\nbeing written into the file. String values are written as-is, integer and\ndouble values are written in decimal notation, boolean values are written as\ntrue or false while arrays and objects are converted to their JSON\nrepresentation before being written into the file. The null value is\nrepresented by an empty string so writefile(…, null) would write an empty\nfile. Resource values are written in the form <type address>, e.g.\n<fs.file 0x7f60f0981760>.

\n

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

\n

If a file already exists at the given path, it is truncated. If no file\nexists, it is created with default permissions 0o666 masked by the currently\neffective umask.

\n

Returns the number of bytes written.

\n

Returns null if an error occurred, e.g. due to insufficient permissions.

"},{"title":"module:fs.FileStatResult","link":"FileStatResult"},{"title":"module:fs.dir","link":"dir","description":"

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

"},{"title":"module:fs.dir#close","link":"close","description":"

Closes the directory handle.

\n

Closes the underlying file descriptor referring to the opened directory.

\n

Returns true if the handle was properly closed.

\n

Returns null if an error occurred.

"},{"title":"module:fs.dir#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs.dir#read","link":"read","description":"

Read the next entry from the open directory.

\n

Returns a string containing the entry name.

\n

Returns null if there are no more entries to read.

\n

Returns null if an error occurred.

"},{"title":"module:fs.dir#seek","link":"seek","description":"

Set read position.

\n

Sets the read position within the open directory handle to the given offset\nvalue. The offset value should be obtained by a previous call to tell() as\nthe specific integer values are implementation defined.

\n

Returns true if the read position was set.

\n

Returns null if an error occurred.

"},{"title":"module:fs.dir#tell","link":"tell","description":"

Obtain current read position.

\n

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

\n

Returns an integer referring to the current position.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file","link":"file","description":"

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

"},{"title":"module:fs.file#close","link":"close","description":"

Closes the file handle.

\n

Upon calling close() on the handle, buffered data is flushed and the\nunderlying file descriptor is closed.

\n

Returns true if the handle was properly closed.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs.file#fileno","link":"fileno","description":"

Obtains the number of the handle's underlying file descriptor.

\n

Returns the descriptor number.

\n

Returns null on error.

"},{"title":"module:fs.file#flush","link":"flush","description":"

Forces a write of all buffered data to the underlying handle.

\n

Returns true if the data was successfully flushed.

\n

Returns null on error.

"},{"title":"module:fs.file#isatty","link":"isatty","description":"

Check for TTY.

\n

Checks whether the open file handle refers to a TTY (terminal) device.

\n

Returns true if the handle refers to a terminal.

\n

Returns false if the handle refers to another kind of file.

\n

Returns null on error.

"},{"title":"module:fs.file#read","link":"read","description":"

Reads a chunk of data from the file handle.

\n

The length argument may be either a positive number of bytes to read, in\nwhich case the read call returns up to that many bytes, or a string to\nspecify a dynamic read size.

\n\n

Returns a string containing the read data.

\n

Returns an empty string on EOF.

\n

Returns null if a read error occurred.

"},{"title":"module:fs.file#seek","link":"seek","description":"

Set file read position.

\n

Set the read position of the open file handle to the given offset and\nposition.

\n

Returns true if the read position was set.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file#tell","link":"tell","description":"

Obtain current read position.

\n

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

\n

Returns an integer containing the current read offset in bytes.

\n

Returns null if an error occurred.

"},{"title":"module:fs.file#write","link":"write","description":"

Writes a chunk of data to the file handle.

\n

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

\n

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

\n

Returns the number of bytes written.

\n

Returns null if a write error occurred.

"},{"title":"module:fs.proc","link":"proc","description":"

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

"},{"title":"module:fs.proc#close","link":"close","description":"

Closes the program handle and awaits program termination.

\n

Upon calling close() on the handle, the program's input or output stream\n(depending on the open mode) is closed. Afterwards, the function awaits the\ntermination of the underlying program and returns its exit code.

\n\n

Returns a negative signal number if the program was terminated by a signal.

\n

Returns a positive exit code if the program terminated normally.

\n

Returns null if an error occurred.

"},{"title":"module:fs.proc#error","link":"error","description":"

Query error information.

\n

Returns a string containing a description of the last occurred error or\nnull if there is no error information.

"},{"title":"module:fs.proc#fileno","link":"fileno","description":"

Obtains the number of the handle's underlying file descriptor.

\n

Returns the descriptor number.

\n

Returns null on error.

"},{"title":"module:fs.proc#flush","link":"flush","description":"

Forces a write of all buffered data to the underlying handle.

\n

Returns true if the data was successfully flushed.

\n

Returns null on error.

"},{"title":"module:fs.proc#read","link":"read","description":"

Reads a chunk of data from the program handle.

\n

The length argument may be either a positive number of bytes to read, in\nwhich case the read call returns up to that many bytes, or a string to\nspecify a dynamic read size.

\n\n

Returns a string containing the read data.

\n

Returns an empty string on EOF.

\n

Returns null if a read error occurred.

"},{"title":"module:fs.proc#write","link":"write","description":"

Writes a chunk of data to the program handle.

\n

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

\n

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

\n

Returns the number of bytes written.

\n

Returns null if a write error occurred.

"},{"title":"module:log","link":"log","description":"

System logging functions

\n

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

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { openlog, syslog, LOG_PID, LOG_USER, LOG_ERR } from 'log';\n\nopenlog("my-log-ident", LOG_PID, LOG_USER);\nsyslog(LOG_ERR, "An error occurred!");\n\n// OpenWrt specific ulog functions\nimport { ulog_open, ulog, ULOG_SYSLOG, LOG_DAEMON, LOG_INFO } from 'log';\n\nulog_open(ULOG_SYSLOG, LOG_DAEMON, "my-log-ident");\nulog(LOG_INFO, "The current epoch is %d", time());\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as log from 'log';\n\nlog.openlog("my-log-ident", log.LOG_PID, log.LOG_USER);\nlog.syslog(log.LOG_ERR, "An error occurred!");\n\n// OpenWrt specific ulog functions\nlog.ulog_open(log.ULOG_SYSLOG, log.LOG_DAEMON, "my-log-ident");\nlog.ulog(log.LOG_INFO, "The current epoch is %d", time());\n
\n

Additionally, the log module namespace may also be imported by invoking the\nucode interpreter with the -llog switch.

\n

Constants

\n

The log module declares a number of numeric constants to specify logging\nfacility, priority and option values, as well as ulog specific channels.

\n

Syslog Options

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Constant NameDescription
LOG_PIDInclude PID with each message.
LOG_CONSLog to console if error occurs while sending to syslog.
LOG_NDELAYOpen the connection to the logger immediately.
LOG_ODELAYDelay open until the first message is logged.
LOG_NOWAITDo not wait for child processes created during logging.
\n

Syslog Facilities

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Constant NameDescription
LOG_AUTHAuthentication/authorization messages.
LOG_AUTHPRIVPrivate authentication messages.
LOG_CRONClock daemon (cron and at commands).
LOG_DAEMONSystem daemons without separate facility values.
LOG_FTPFTP server daemon.
LOG_KERNKernel messages.
LOG_LPRLine printer subsystem.
LOG_MAILMail system.
LOG_NEWSNetwork news subsystem.
LOG_SYSLOGMessages generated internally by syslogd.
LOG_USERGeneric user-level messages.
LOG_UUCPUUCP subsystem.
LOG_LOCAL0Local use 0 (custom facility).
LOG_LOCAL1Local use 1 (custom facility).
LOG_LOCAL2Local use 2 (custom facility).
LOG_LOCAL3Local use 3 (custom facility).
LOG_LOCAL4Local use 4 (custom facility).
LOG_LOCAL5Local use 5 (custom facility).
LOG_LOCAL6Local use 6 (custom facility).
LOG_LOCAL7Local use 7 (custom facility).
\n

Syslog Priorities

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Constant NameDescription
LOG_EMERGSystem is unusable.
LOG_ALERTAction must be taken immediately.
LOG_CRITCritical conditions.
LOG_ERRError conditions.
LOG_WARNINGWarning conditions.
LOG_NOTICENormal, but significant, condition.
LOG_INFOInformational message.
LOG_DEBUGDebug-level message.
\n

Ulog channels

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Constant NameDescription
ULOG_KMSGLog messages to /dev/kmsg (dmesg).
ULOG_STDIOLog messages to stdout.
ULOG_SYSLOGLog messages to syslog.
"},{"title":"module:log#ERR","link":"ERR","description":"

Invoke ulog with LOG_ERR.

\n

This function is convenience wrapper for ulog(LOG_ERR, ...).

\n

See {@link module:log#ulog|ulog()} for details.

"},{"title":"module:log#INFO","link":"INFO","description":"

Invoke ulog with LOG_INFO.

\n

This function is convenience wrapper for ulog(LOG_INFO, ...).

\n

See {@link module:log#ulog|ulog()} for details.

"},{"title":"module:log#NOTE","link":"NOTE","description":"

Invoke ulog with LOG_NOTICE.

\n

This function is convenience wrapper for ulog(LOG_NOTICE, ...).

\n

See {@link module:log#ulog|ulog()} for details.

"},{"title":"module:log#WARN","link":"WARN","description":"

Invoke ulog with LOG_WARNING.

\n

This function is convenience wrapper for ulog(LOG_WARNING, ...).

\n

See {@link module:log#ulog|ulog()} for details.

"},{"title":"module:log#closelog","link":"closelog","description":"

Close connection to system logger.

\n

The usage of this function is optional, and usually an explicit log\nconnection tear down is not required.

"},{"title":"module:log#openlog","link":"openlog","description":"

Open connection to system logger.

\n

The openlog() function instructs the program to establish a connection to\nthe system log service and configures the default facility and identification\nfor use in subsequent log operations. It may be omitted, in which case the\nfirst call to syslog() will implicitly call openlog() with a default\nident value representing the program name and a default LOG_USER facility.

\n

The log option argument may be either a single string value containing an\noption name, an array of option name strings or a numeric value representing\na bitmask of LOG_* option constants.

\n

The facility argument may be either a single string value containing a\nfacility name or one of the numeric LOG_* facility constants in the module\nnamespace.

\n

Returns true if the system openlog() function was invoked.

\n

Returns false if an invalid argument, such as an unrecognized option or\nfacility name, was provided.

"},{"title":"module:log#syslog","link":"syslog","description":"

Log a message to the system logger.

\n

This function logs a message to the system logger. The function behaves in a\nsprintf-like manner, allowing the use of format strings and associated\narguments to construct log messages.

\n

If the openlog function has not been called explicitly before, syslog()\nimplicitly calls openlog(), using a default ident and LOG_USER facility\nvalue before logging the message.

\n

If the format argument is not a string and not null, it will be\nimplicitly converted to a string and logged as-is, without further format\nstring processing.

\n

Returns true if a message was passed to the system syslog() function.

\n

Returns false if an invalid priority value or an empty message was given.

"},{"title":"module:log#ulog","link":"ulog","description":"

Log a message via the ulog mechanism.

\n

The ulog() function outputs the given log message to all configured ulog\nchannels unless the given priority level exceeds the globally configured ulog\npriority threshold. See {@link module:log#ulog_threshold|ulog_threshold()}\nfor details.

\n

The ulog() function is OpenWrt specific and may not be present on other\nsystems. Use syslog() instead for portability to non-OpenWrt environments.

\n

Like syslog(), the function behaves in a sprintf-like manner, allowing the\nuse of format strings and associated arguments to construct log messages.

\n

If the ulog_open() function has not been called explicitly before, ulog()\nimplicitly configures certain defaults, see\n{@link module:log#ulog_open|ulog_open()} for a detailled description.

\n

If the format argument is not a string and not null, it will be\nimplicitly converted to a string and logged as-is, without further format\nstring processing.

\n

Returns true if a message was passed to the underlying ulog() function.

\n

Returns false if an invalid priority value or an empty message was given.

"},{"title":"module:log#ulog_close","link":"ulog_close","description":"

Close ulog logger.

\n

Resets the ulog channels, the default facility and the log ident value to\ndefaults.

\n

In case the "syslog" channel has been configured, the underlying\ncloselog() function will be invoked.

\n

The usage of this function is optional, and usually an explicit ulog teardown\nis not required.

\n

The ulog_close() function is OpenWrt specific and may not be present on\nother systems. Use closelog() in conjunction with syslog() instead for\nportability to non-OpenWrt environments.

"},{"title":"module:log#ulog_open","link":"ulog_open","description":"

Configure ulog logger.

\n

This functions configures the ulog mechanism and is analogeous to using the\nopenlog() function in conjuncton with syslog().

\n

The ulog_open() function is OpenWrt specific and may not be present on\nother systems. Use openlog() and syslog() instead for portability to\nnon-OpenWrt environments.

\n

A program may use multiple channels to simultaneously output messages using\ndifferent means. The channel argument may either be a single string value\ncontaining a channel name, an array of channel names or a numeric value\nrepresenting a bitmask of ULOG_* channel constants.

\n

The facility argument may be either a single string value containing a\nfacility name or one of the numeric LOG_* facility constants in the module\nnamespace.

\n

The default facility value varies, depending on the execution context of the\nprogram. In OpenWrt's preinit boot phase, or when stdout is not connected to\nan interactive terminal, the facility defaults to "daemon" (LOG_DAEMON),\notherwise to "user" (LOG_USER).

\n

Likewise, the default channel is selected depending on the context. During\nOpenWrt's preinit boot phase, the "kmsg" channel is used, for interactive\nterminals the "stdio" one and for all other cases the "syslog" channel\nis selected.

\n

Returns true if ulog was configured.

\n

Returns false if an invalid argument, such as an unrecognized channel or\nfacility name, was provided.

"},{"title":"module:log#ulog_threshold","link":"ulog_threshold","description":"

Set ulog priority threshold.

\n

This function configures the application wide log message threshold for log\nmessages emitted with ulog(). Any message with a priority higher (= less\nsevere) than the threshold priority will be discarded. This is useful to\nimplement application wide verbosity settings without having to wrap ulog()\ninvocations into a helper function or guarding code.

\n

When no explicit threshold has been set, LOG_DEBUG is used by default,\nallowing log messages with all known priorities.

\n

The ulog_threshold() function is OpenWrt specific and may not be present on\nother systems. There is no syslog equivalent to this ulog specific threshold\nmechanism.

\n

The priority argument may be either a string value containing a priority name\nor one of the numeric LOG_* priority constants in the module namespace.

\n

Returns true if a threshold was set.

\n

Returns false if an invalid priority value was given.

"},{"title":"module:log.LogFacility","link":"LogFacility","description":"

The following log facility strings are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
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).
"},{"title":"module:log.LogOption","link":"LogOption","description":"

The following log option strings are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
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.
"},{"title":"module:log.LogPriority","link":"LogPriority","description":"

The following log priority strings are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
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.
"},{"title":"module:log.UlogChannel","link":"UlogChannel","description":"

The following ulog channel strings are recognized:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ChannelDescription
"kmsg"Log to /dev/kmsg, log messages appear in dmesg.
"syslog"Use standard syslog() mechanism.
"stdio"Use stderr for log output.
"},{"title":"module:math","link":"math","description":"

Mathematical Functions

\n

The math module bundles various mathematical and trigonometrical functions.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { pow, rand } from 'math';\n\nlet x = pow(2, 5);\nlet y = rand();\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as math from 'math';\n\nlet x = math.pow(2, 5);\nlet y = math.rand();\n
\n

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

"},{"title":"module:math#abs","link":"abs","description":"

Returns the absolute value of the given numeric value.

"},{"title":"module:math#atan2","link":"atan2","description":"

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

\n

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

\n\n

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

"},{"title":"module:math#cos","link":"cos","description":"

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

\n

Returns the resulting consine value.

\n

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

"},{"title":"module:math#exp","link":"exp","description":"

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

\n

On success, returns the exponential value of x.

\n\n

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

"},{"title":"module:math#isnan","link":"isnan","description":"

Tests whether x is a NaN double.

\n

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

\n

Returns true if the value is NaN, otherwise false.

\n

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

"},{"title":"module:math#log","link":"log","description":"

Calculates the natural logarithm of x.

\n

On success, returns the natural logarithm of x.

\n\n

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

"},{"title":"module:math#pow","link":"pow","description":"

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

\n

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

\n\n

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

"},{"title":"module:math#rand","link":"rand","description":"

Produces a pseudo-random positive integer.

\n

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

\n

The {@link module:math~srand srand()} function sets its argument as the\nseed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are\nrepeatable by calling {@link module:math~srand srand()} with the same\nseed value.

\n

If no seed value is explicitly set by calling\n{@link module:math~srand srand()} prior to the first call to rand(),\nthe math module will automatically seed the PRNG once, using the current\ntime of day in milliseconds as seed value.

"},{"title":"module:math#sin","link":"sin","description":"

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

\n

Returns the resulting sine value.

\n\n

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

"},{"title":"module:math#sqrt","link":"sqrt","description":"

Calculates the nonnegative square root of x.

\n

Returns the resulting square root value.

\n\n

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

"},{"title":"module:math#srand","link":"srand","description":"

Seeds the pseudo-random number generator.

\n

This functions seeds the PRNG with the given value and thus affects the\npseudo-random integer sequence produced by subsequent calls to\n{@link module:math~rand rand()}.

\n

Setting the same seed value will result in the same pseudo-random numbers\nproduced by {@link module:math~rand rand()}.

"},{"title":"module:struct","link":"struct","description":"

Handle Packed Binary Data

\n

The struct module provides routines for interpreting byte strings as packed\nbinary data.

\n

Functions can be individually imported and directly accessed using the\n{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}\nsyntax:

\n
import { pack, unpack } from 'struct';\n\nlet buffer = pack('bhl', -13, 1234, 444555666);\nlet values = unpack('bhl', buffer);\n
\n

Alternatively, the module namespace can be imported\nusing a wildcard import statement:

\n
import * as struct from 'struct';\n\nlet buffer = struct.pack('bhl', -13, 1234, 444555666);\nlet values = struct.unpack('bhl', buffer);\n
\n

Additionally, the struct module namespace may also be imported by invoking\nthe ucode interpreter with the -lstruct switch.

\n

Format Strings

\n

Format strings describe the data layout when packing and unpacking data.\nThey are built up from format-characters, which specify the type of data\nbeing packed/unpacked. In addition, special characters control the byte\norder, size and alignment.

\n

Each format string consists of an optional prefix character which describes\nthe overall properties of the data and one or more format characters which\ndescribe the actual data values and padding.

\n

Byte Order, Size, and Alignment

\n

By default, C types are represented in the machine's native format and byte\norder, and properly aligned by skipping pad bytes if necessary (according to\nthe rules used by the C compiler).

\n

This behavior is chosen so that the bytes of a packed struct correspond\nexactly to the memory layout of the corresponding C struct.

\n

Whether to use native byte ordering and padding or standard formats depends\non the application.

\n

Alternatively, the first character of the format string can be used to indicate\nthe byte order, size and alignment of the packed data, according to the\nfollowing table:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
CharacterByte orderSizeAlignment
@nativenativenative
=nativestandardnone
<little-endianstandardnone
>big-endianstandardnone
!network (= big-endian)standardnone
\n

If the first character is not one of these, '@' is assumed.

\n

Native byte order is big-endian or little-endian, depending on the\nhost system. For example, Intel x86, AMD64 (x86-64), and Apple M1 are\nlittle-endian; IBM z and many legacy architectures are big-endian.

\n

Native size and alignment are determined using the C compiler's\nsizeof expression. This is always combined with native byte order.

\n

Standard size depends only on the format character; see the table in\nthe format-characters section.

\n

Note the difference between '@' and '=': both use native byte order,\nbut the size and alignment of the latter is standardized.

\n

The form '!' represents the network byte order which is always big-endian\nas defined in IETF RFC 1700.

\n

There is no way to indicate non-native byte order (force byte-swapping); use\nthe appropriate choice of '<' or '>'.

\n

Notes:

\n

(1) Padding is only automatically added between successive structure members.\nNo padding is added at the beginning or the end of the encoded struct.

\n

(2) No padding is added when using non-native size and alignment, e.g.\nwith '<', '>', '=', and '!'.

\n

(3) To align the end of a structure to the alignment requirement of a\nparticular type, end the format with the code for that type with a repeat\ncount of zero.

\n

Format Characters

\n

Format characters have the following meaning; the conversion between C and\nucode values should be obvious given their types. The 'Standard size' column\nrefers to the size of the packed value in bytes when using standard size;\nthat is, when the format string starts with one of '<', '>', '!' or\n'='. When using native size, the size of the packed value is platform\ndependent.

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
FormatC TypeUcode typeStandard sizeNotes
xpad byteno value(7)
ccharstring1
bsigned charint1(1), (2)
Bunsigned charint1(2)
?_Boolbool1(1)
hshortint2(2)
Hunsigned shortint2(2)
iintint4(2)
Iunsigned intint4(2)
llongint4(2)
Lunsigned longint4(2)
qlong longint8(2)
Qunsigned long longint8(2)
nssize_tint(3)
Nsize_tint(3)
e(6)double2(4)
ffloatdouble4(4)
ddoubledouble8(4)
schar[]double(9)
pchar[]double(8)
Pvoid *int(5)
*char[]string(10)
\n

Notes:

\n\n

A format character may be preceded by an integral repeat count. For example,\nthe format string '4h' means exactly the same as 'hhhh'.

\n

Whitespace characters between formats are ignored; a count and its format\nmust not contain whitespace though.

\n

When packing a value x using one of the integer formats ('b',\n'B', 'h', 'H', 'i', 'I', 'l', 'L',\n'q', 'Q'), if x is outside the valid range for that format, a type\nerror exception is raised.

\n

For the '?' format character, the return value is either true or false.\nWhen packing, the truish result value of the argument is used. Either 0 or 1\nin the native or standard bool representation will be packed, and any\nnon-zero value will be true when unpacking.

\n

Examples

\n

Note:\nNative byte order examples (designated by the '@' format prefix or\nlack of any prefix character) may not match what the reader's\nmachine produces as\nthat depends on the platform and compiler.

\n

Pack and unpack integers of three different sizes, using big endian\nordering:

\n
import { pack, unpack } from 'struct';\n\npack(">bhl", 1, 2, 3);  // "\\x01\\x00\\x02\\x00\\x00\\x00\\x03"\nunpack(">bhl", "\\x01\\x00\\x02\\x00\\x00\\x00\\x03");  // [ 1, 2, 3 ]\n
\n

Attempt to pack an integer which is too large for the defined field:

\n
$ ucode -lstruct -p 'struct.pack(">h", 99999)'\nType error: Format 'h' requires numeric argument between -32768 and 32767\nIn [-p argument], line 1, byte 24:\n\n `struct.pack(">h", 99999)`\n  Near here -------------^\n
\n

Demonstrate the difference between 's' and 'c' format characters:

\n
import { pack } from 'struct';\n\npack("@ccc", "1", "2", "3");  // "123"\npack("@3s", "123");           // "123"\n
\n

The ordering of format characters may have an impact on size in native\nmode since padding is implicit. In standard mode, the user is\nresponsible for inserting any desired padding.

\n

Note in the first pack() call below that three NUL bytes were added after\nthe packed '#' to align the following integer on a four-byte boundary.\nIn this example, the output was produced on a little endian machine:

\n
import { pack } from 'struct';\n\npack("@ci", "#", 0x12131415);  // "#\\x00\\x00\\x00\\x15\\x14\\x13\\x12"\npack("@ic", 0x12131415, "#");  // "\\x15\\x14\\x13\\x12#"\n
\n

The following format 'ih0i' results in two pad bytes being added at the\nend, assuming the platform's ints are aligned on 4-byte boundaries:

\n
import { pack } from 'struct';\n\npack("ih0i", 0x01010101, 0x0202);  // "\\x01\\x01\\x01\\x01\\x02\\x02\\x00\\x00"\n
\n

Use the wildcard format to extract the remainder of the input data:

\n
import { unpack } from 'struct';\n\nunpack("ccc*", "foobarbaz");   // [ "f", "o", "o", "barbaz" ]\nunpack("ccc3*", "foobarbaz");  // [ "f", "o", "o", "bar" ]\n
\n

Use the wildcard format to pack binary stings as-is into the result data:

\n
import { pack } from 'struct';\n\npack("h*h", 0x0101, "\\x02\\x00\\x03", 0x0404);  // "\\x01\\x01\\x02\\x00\\x03\\x04\\x04"\npack("c3*c", "a", "foobar", "c");  // "afooc"\n
"},{"title":"module:struct#new","link":"new","description":"

Precompile format string.

\n

The new() function precompiles the given format string argument and returns\na struct object instance useful for packing and unpacking multiple items\nwithout having to recompute the internal format each time.

\n

Returns an precompiled struct format instance.

\n

Raises a runtime exception if the format string is invalid.

"},{"title":"module:struct#pack","link":"pack","description":"

Pack given values according to specified format.

\n

The pack() function creates a byte string containing the argument values\npacked according to the given format string.

\n

Returns the packed string.

\n

Raises a runtime exception if a given argument value does not match the\nrequired type of the corresponding format string directive or if and invalid\nformat string is provided.

"},{"title":"module:struct#unpack","link":"unpack","description":"

Unpack given byte string according to specified format.

\n

The unpack() function interpretes a byte string according to the given\nformat string and returns the resulting values. If the optional offset\nargument is given, unpacking starts from this byte position within the input.\nIf not specified, the start offset defaults to 0, the start of the given\ninput string.

\n

Returns an array of unpacked values.

\n

Raises a runtime exception if the format string is invalid or if an invalid\ninput string or offset value is given.

"},{"title":"module:struct.instance","link":"instance","description":"

Represents a struct instance created by new().

"},{"title":"module:struct.instance#pack","link":"pack","description":"

Pack given values.

\n

The pack() function creates a byte string containing the argument values\npacked according to the given format instance.

\n

Returns the packed string.

\n

Raises a runtime exception if a given argument value does not match the\nrequired type of the corresponding format string directive.

"},{"title":"module:struct.instance#unpack","link":"unpack","description":"

Unpack given byte string.

\n

The unpack() function interpretes a byte string according to the given\nformat instance and returns the resulting values. If the optional offset\nargument is given, unpacking starts from this byte position within the input.\nIf not specified, the start offset defaults to 0, the start of the given\ninput string.

\n

Returns an array of unpacked values.

\n

Raises a runtime exception if an invalid input string or offset value is\ngiven.

"}]} \ No newline at end of file diff --git a/index.html b/index.html index 6aa10eed..31ac6c8d 100644 --- a/index.html +++ b/index.html @@ -1,6 +1,6 @@ ucode - Reference Documentation
On this page

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
+    
On this page

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
-
\ No newline at end of file +
ucode Documentation
\ No newline at end of file diff --git a/lib.c.html b/lib.c.html index 5a252e60..971f3e8b 100644 --- a/lib.c.html +++ b/lib.c.html @@ -1,6 +1,6 @@ Source: lib.c
On this page

lib.c

/*
+    
On this page

lib.c

/*
  * Copyright (C) 2020-2021 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -5792,4 +5792,4 @@
 
 	return NULL;
 }
-
\ No newline at end of file +
ucode Documentation
\ No newline at end of file diff --git a/lib_debug.c.html b/lib_debug.c.html index c5cc47bf..12150aa1 100644 --- a/lib_debug.c.html +++ b/lib_debug.c.html @@ -1,6 +1,6 @@ Source: lib/debug.c
On this page

lib_debug.c

/*
+    
On this page

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);
 }
-
\ No newline at end of file +
ucode Documentation
\ No newline at end of file diff --git a/lib_fs.c.html b/lib_fs.c.html index 468c4762..93b942e8 100644 --- a/lib_fs.c.html +++ b/lib_fs.c.html @@ -1,6 +1,6 @@ Source: lib/fs.c
On this page

lib_fs.c

/*
+    
On this page

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
@@ -2707,4 +2707,4 @@
 	ucv_object_add(scope, "stdout", uc_resource_new(file_type, stdout));
 	ucv_object_add(scope, "stderr", uc_resource_new(file_type, stderr));
 }
-
\ No newline at end of file +
ucode Documentation
\ No newline at end of file diff --git a/lib_log.c.html b/lib_log.c.html new file mode 100644 index 00000000..1244f2aa --- /dev/null +++ b/lib_log.c.html @@ -0,0 +1,1077 @@ +Source: lib/log.c
On this page

lib_log.c

/*
+ * Copyright (C) 2023 Jo-Philipp Wich <jo@mein.io>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+/**
+ * # 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
+ * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import 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!");
+ *
+ *   // OpenWrt specific ulog functions
+ *   import { ulog_open, ulog, ULOG_SYSLOG, LOG_DAEMON, LOG_INFO } from 'log';
+ *
+ *   ulog_open(ULOG_SYSLOG, LOG_DAEMON, "my-log-ident");
+ *   ulog(LOG_INFO, "The current epoch is %d", time());
+ *   ```
+ *
+ * Alternatively, the module namespace can be imported
+ * using a wildcard import statement:
+ *
+ *   ```
+ *   import * as log from 'log';
+ *
+ *   log.openlog("my-log-ident", log.LOG_PID, log.LOG_USER);
+ *   log.syslog(log.LOG_ERR, "An error occurred!");
+ *
+ *   // OpenWrt specific ulog functions
+ *   log.ulog_open(log.ULOG_SYSLOG, log.LOG_DAEMON, "my-log-ident");
+ *   log.ulog(log.LOG_INFO, "The current epoch is %d", time());
+ *   ```
+ *
+ * Additionally, the log module namespace may also be imported by invoking the
+ * `ucode` interpreter with the `-llog` switch.
+ *
+ * ## Constants
+ *
+ * The `log` module declares a number of numeric constants to specify logging
+ * facility, priority and option values, as well as ulog specific channels.
+ *
+ * ### Syslog Options
+ *
+ * | Constant Name | Description                                             |
+ * |---------------|---------------------------------------------------------|
+ * | `LOG_PID`     | Include PID with each message.                          |
+ * | `LOG_CONS`    | Log to console if error occurs while sending to syslog. |
+ * | `LOG_NDELAY`  | Open the connection to the logger immediately.          |
+ * | `LOG_ODELAY`  | Delay open until the first message is logged.           |
+ * | `LOG_NOWAIT`  | Do not wait for child processes created during logging. |
+ *
+ * ### Syslog Facilities
+ *
+ * | Constant Name  | Description                                      |
+ * |----------------|--------------------------------------------------|
+ * | `LOG_AUTH`     | Authentication/authorization messages.           |
+ * | `LOG_AUTHPRIV` | Private authentication messages.                 |
+ * | `LOG_CRON`     | Clock daemon (cron and at commands).             |
+ * | `LOG_DAEMON`   | System daemons without separate facility values. |
+ * | `LOG_FTP`      | FTP server daemon.                               |
+ * | `LOG_KERN`     | Kernel messages.                                 |
+ * | `LOG_LPR`      | Line printer subsystem.                          |
+ * | `LOG_MAIL`     | Mail system.                                     |
+ * | `LOG_NEWS`     | Network news subsystem.                          |
+ * | `LOG_SYSLOG`   | Messages generated internally by syslogd.        |
+ * | `LOG_USER`     | Generic user-level messages.                     |
+ * | `LOG_UUCP`     | UUCP subsystem.                                  |
+ * | `LOG_LOCAL0`   | Local use 0 (custom facility).                   |
+ * | `LOG_LOCAL1`   | Local use 1 (custom facility).                   |
+ * | `LOG_LOCAL2`   | Local use 2 (custom facility).                   |
+ * | `LOG_LOCAL3`   | Local use 3 (custom facility).                   |
+ * | `LOG_LOCAL4`   | Local use 4 (custom facility).                   |
+ * | `LOG_LOCAL5`   | Local use 5 (custom facility).                   |
+ * | `LOG_LOCAL6`   | Local use 6 (custom facility).                   |
+ * | `LOG_LOCAL7`   | Local use 7 (custom facility).                   |
+ *
+ * ### Syslog Priorities
+ *
+ * | Constant Name | Description                         |
+ * |---------------|-------------------------------------|
+ * | `LOG_EMERG`   | System is unusable.                 |
+ * | `LOG_ALERT`   | Action must be taken immediately.   |
+ * | `LOG_CRIT`    | Critical conditions.                |
+ * | `LOG_ERR`     | Error conditions.                   |
+ * | `LOG_WARNING` | Warning conditions.                 |
+ * | `LOG_NOTICE`  | Normal, but significant, condition. |
+ * | `LOG_INFO`    | Informational message.              |
+ * | `LOG_DEBUG`   | Debug-level message.                |
+ *
+ * ### Ulog channels
+ *
+ * | Constant Name | Description                          |
+ * |---------------|--------------------------------------|
+ * | `ULOG_KMSG`   | Log messages to `/dev/kmsg` (dmesg). |
+ * | `ULOG_STDIO`  | Log messages to stdout.              |
+ * | `ULOG_SYSLOG` | Log messages to syslog.              |
+ *
+ * @module log
+ */
+
+#include <syslog.h>
+#include <errno.h>
+
+#ifdef HAVE_ULOG
+#include <libubox/ulog.h>
+#endif
+
+#include "ucode/module.h"
+
+
+static char log_ident[32];
+
+/**
+ * The following log option strings are recognized:
+ *
+ * | Log Option | Description                                                |
+ * |------------|------------------------------------------------------------|
+ * | `"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.    |
+ *
+ * @typedef {string} module:log.LogOption
+ * @enum {module:log.LogOption}
+ *
+ */
+static const struct { const char *name; int value; } log_options[] = {
+	{ "pid", LOG_PID },
+	{ "cons", LOG_CONS },
+	{ "ndelay", LOG_NDELAY },
+	{ "odelay", LOG_ODELAY },
+	{ "nowait", LOG_NOWAIT },
+};
+
+/**
+ * The following log facility strings are recognized:
+ *
+ * | Facility     | Description                                      |
+ * |--------------|--------------------------------------------------|
+ * | `"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).                   |
+ *
+ * @typedef {string} module:log.LogFacility
+ * @enum {module:log.LogFacility}
+ */
+static const struct { const char *name; int value; } log_facilities[] = {
+	{ "auth", LOG_AUTH },
+#ifdef LOG_AUTHPRIV
+	{ "authpriv", LOG_AUTHPRIV },
+#endif
+	{ "cron", LOG_CRON },
+	{ "daemon", LOG_DAEMON },
+#ifdef LOG_FTP
+	{ "ftp", LOG_FTP },
+#endif
+	{ "kern", LOG_KERN },
+	{ "lpr", LOG_LPR },
+	{ "mail", LOG_MAIL },
+	{ "news", LOG_NEWS },
+	{ "syslog", LOG_SYSLOG },
+	{ "user", LOG_USER },
+	{ "uucp", LOG_UUCP },
+	{ "local0", LOG_LOCAL0 },
+	{ "local1", LOG_LOCAL1 },
+	{ "local2", LOG_LOCAL2 },
+	{ "local3", LOG_LOCAL3 },
+	{ "local4", LOG_LOCAL4 },
+	{ "local5", LOG_LOCAL5 },
+	{ "local6", LOG_LOCAL6 },
+	{ "local7", LOG_LOCAL7 },
+};
+
+/**
+ * The following log priority strings are recognized:
+ *
+ * | Priority    | Description                         |
+ * |-------------|-------------------------------------|
+ * | `"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.                |
+ *
+ * @typedef {string} module:log.LogPriority
+ * @enum {module:log.LogPriority}
+ */
+static const struct { const char *name; int value; } log_priorities[] = {
+	{ "emerg", LOG_EMERG },
+	{ "alert", LOG_ALERT },
+	{ "crit", LOG_CRIT },
+	{ "err", LOG_ERR },
+	{ "warning", LOG_WARNING },
+	{ "notice", LOG_NOTICE },
+	{ "info", LOG_INFO },
+	{ "debug", LOG_DEBUG },
+};
+
+
+static int
+parse_facility(uc_value_t *facility)
+{
+	char *s;
+	int rv;
+
+	switch (ucv_type(facility)) {
+	case UC_STRING:
+		s = ucv_string_get(facility);
+
+		for (size_t i = 0; i < ARRAY_SIZE(log_facilities); i++)
+			if (s && !strcasecmp(s, log_facilities[i].name))
+				return log_facilities[i].value;
+
+		return -1;
+
+	case UC_INTEGER:
+		rv = ucv_int64_get(facility);
+
+		if (errno == ERANGE || rv < 0)
+			return -1;
+
+		return rv;
+
+	case UC_NULL:
+		return 0;
+
+	default:
+		return -1;
+	}
+}
+
+static int
+parse_options(uc_value_t *option)
+{
+	char *s;
+	int rv;
+
+	switch (ucv_type(option)) {
+	case UC_ARRAY:
+		rv = 0;
+
+		for (size_t i = 0; i < ucv_array_length(option); i++) {
+			uc_value_t *opt = ucv_array_get(option, i);
+			char *s = ucv_string_get(opt);
+
+			for (size_t j = 0; j < ARRAY_SIZE(log_options); j++) {
+				if (s && !strcasecmp(log_options[j].name, s))
+					rv |= log_options[j].value;
+				else
+					return -1;
+			}
+		}
+
+		return rv;
+
+	case UC_STRING:
+		s = ucv_string_get(option);
+
+		for (size_t i = 0; i < ARRAY_SIZE(log_options); i++)
+			if (s && !strcasecmp(s, log_options[i].name))
+				return log_options[i].value;
+
+		return -1;
+
+	case UC_INTEGER:
+		rv = ucv_int64_get(option);
+
+		if (errno == ERANGE || rv < 0)
+			return -1;
+
+		return rv;
+
+	case UC_NULL:
+		return 0;
+
+	default:
+		return -1;
+	}
+}
+
+static int
+parse_priority(uc_value_t *priority)
+{
+	char *s;
+	int rv;
+
+	switch (ucv_type(priority)) {
+	case UC_STRING:
+		s = ucv_string_get(priority);
+
+		for (size_t i = 0; i < ARRAY_SIZE(log_priorities); i++)
+			if (s && !strcasecmp(s, log_priorities[i].name))
+				return log_priorities[i].value;
+
+		return -1;
+
+	case UC_INTEGER:
+		rv = ucv_int64_get(priority);
+
+		if (errno == ERANGE || rv < 0)
+			return -1;
+
+		return rv;
+
+	case UC_NULL:
+		return LOG_INFO;
+
+	default:
+		return -1;
+	}
+}
+
+static char *
+parse_ident(uc_vm_t *vm, uc_value_t *ident)
+{
+	if (!ident)
+		return NULL;
+
+	char *s = ucv_to_string(vm, ident);
+
+	snprintf(log_ident, sizeof(log_ident), "%s", s ? s : "");
+	free(s);
+
+	return log_ident[0] ? log_ident : NULL;
+}
+
+/**
+ * Open connection to system logger.
+ *
+ * The `openlog()` function instructs the program to establish a connection to
+ * the system log service and configures the default facility and identification
+ * for use in subsequent log operations. It may be omitted, in which case the
+ * first call to `syslog()` will implicitly call `openlog()` with a default
+ * ident value representing the program name and a default `LOG_USER` facility.
+ *
+ * The log option argument may be either a single string value containing an
+ * option name, an array of option name strings or a numeric value representing
+ * a bitmask of `LOG_*` option constants.
+ *
+ * The facility argument may be either a single string value containing a
+ * facility name or one of the numeric `LOG_*` facility constants in the module
+ * namespace.
+ *
+ * Returns `true` if the system `openlog()` function was invoked.
+ *
+ * Returns `false` if an invalid argument, such as an unrecognized option or
+ * facility name, was provided.
+ *
+ * @function module:log#openlog
+ *
+ * @param {string} [ident]
+ * A string identifying the program name. If omitted, the name of the calling
+ * process is used by default.
+ *
+ * @param {number|module:log.LogOption|module:log.LogOption[]} [options]
+ * Logging options to use.
+ *
+ * See {@link module:log.LogOption|LogOption} for recognized option names.
+ *
+ * @param {number|module:log.LogFacility} [facility="user"]
+ * The facility to use for log messages generated by subsequent syslog calls.
+ *
+ * See {@link module:log.LogFacility|LogFacility} for recognized facility names.
+ *
+ * @returns {boolean}
+ *
+ * @example
+ * // Example usage of openlog function
+ * openlog("myapp", LOG_PID | LOG_NDELAY, LOG_LOCAL0);
+ *
+ * // Using option names instead of bitmask and LOG_USER facility
+ * openlog("myapp", [ "pid", "ndelay" ], "user");
+ */
+static uc_value_t *
+uc_openlog(uc_vm_t *vm, size_t nargs)
+{
+	char *ident = parse_ident(vm, uc_fn_arg(0));
+	int options = parse_options(uc_fn_arg(1));
+	int facility = parse_facility(uc_fn_arg(2));
+
+	if (options == -1 || facility == -1)
+		return ucv_boolean_new(false);
+
+	openlog(ident, options, facility);
+
+	return ucv_boolean_new(true);
+}
+
+/**
+ * Log a message to the system logger.
+ *
+ * This function logs a message to the system logger. The function behaves in a
+ * sprintf-like manner, allowing the use of format strings and associated
+ * arguments to construct log messages.
+ *
+ * If the `openlog` function has not been called explicitly before, `syslog()`
+ * implicitly calls `openlog()`, using a default ident and `LOG_USER` facility
+ * value before logging the message.
+ *
+ * If the `format` argument is not a string and not `null`, it will be
+ * implicitly converted to a string and logged as-is, without further format
+ * string processing.
+ *
+ * Returns `true` if a message was passed to the system `syslog()` function.
+ *
+ * Returns `false` if an invalid priority value or an empty message was given.
+ *
+ * @function module:log#syslog
+ *
+ * @param {number|module:log.LogPriority} priority
+ * Log message priority. May be either a number value (potentially bitwise OR-ed
+ * with a log facility constant) which is passed as-is to the system `syslog()`
+ * function or a priority name string.
+ *
+ * See {@link module:log.LogPriority|LogPriority} for recognized priority names.
+ *
+ * @param {*} format
+ * The sprintf-like format string for the log message, or any other, non-null,
+ * non-string value type which will be implicitly stringified and logged as-is.
+ *
+ * @param {...*} [args]
+ * In case a format string value was provided in the previous argument, then
+ * all subsequent arguments are used to replace the placeholders in the format
+ * string.
+ *
+ * @returns {boolean}
+ *
+ * @example
+ * // Example usage of syslog function with format string and arguments
+ * const username = "user123";
+ * const errorCode = 404;
+ * syslog(LOG_ERR, "User %s encountered error: %d", username, errorCode);
+ *
+ * // If openlog has not been called explicitly, it is implicitly called with defaults:
+ * syslog(LOG_INFO, "This message will be logged with default settings.");
+ *
+ * // Selectively override used facility by OR-ing numeric constant
+ * const password =" secret";
+ * syslog(LOG_DEBUG|LOG_AUTHPRIV, "The password %s has been wrong", secret);
+ *
+ * // Using priority names for logging
+ * syslog("emerg", "System shutdown imminent!");
+ *
+ * // Implicit stringification
+ * syslog("debug", { foo: 1, bar: true, baz: [1, 2, 3] });
+ */
+static uc_value_t *
+uc_syslog(uc_vm_t *vm, size_t nargs)
+{
+	int priority = parse_priority(uc_fn_arg(0));
+
+	if (priority == -1 || nargs < 2)
+		return ucv_boolean_new(false);
+
+	uc_value_t *fmt = uc_fn_arg(1), *msg;
+	uc_cfn_ptr_t fmtfn;
+	char *s;
+
+	switch (ucv_type(fmt)) {
+	case UC_STRING:
+		fmtfn = uc_stdlib_function("sprintf");
+		msg = fmtfn(vm, nargs - 1);
+
+		if (msg) {
+			syslog(priority, "%s", ucv_string_get(msg));
+			ucv_put(msg);
+
+			return ucv_boolean_new(true);
+		}
+
+		break;
+
+	case UC_NULL:
+		break;
+
+	default:
+		s = ucv_to_string(vm, fmt);
+
+		if (s) {
+			syslog(priority, "%s", s);
+			free(s);
+
+			return ucv_boolean_new(true);
+		}
+
+		break;
+	}
+
+	return ucv_boolean_new(false);
+}
+
+/**
+ * Close connection to system logger.
+ *
+ * The usage of this function is optional, and usually an explicit log
+ * connection tear down is not required.
+ *
+ * @function module:log#closelog
+ */
+static uc_value_t *
+uc_closelog(uc_vm_t *vm, size_t nargs)
+{
+	closelog();
+
+	return NULL;
+}
+
+
+#ifdef HAVE_ULOG
+/**
+ * The following ulog channel strings are recognized:
+ *
+ * | Channel    | Description                                       |
+ * |------------|---------------------------------------------------|
+ * | `"kmsg"`   | Log to `/dev/kmsg`, log messages appear in dmesg. |
+ * | `"syslog"` | Use standard `syslog()` mechanism.                |
+ * | `"stdio"`  | Use stderr for log output.                        |
+ *
+ * @typedef {string} module:log.UlogChannel
+ * @enum {module:log.UlogChannel}
+ */
+static const struct { const char *name; int value; } ulog_channels[] = {
+	{ "kmsg", ULOG_KMSG },
+	{ "syslog", ULOG_SYSLOG },
+	{ "stdio", ULOG_STDIO },
+};
+
+static int
+parse_channels(uc_value_t *channels)
+{
+	char *s;
+	int rv;
+
+	switch (ucv_type(channels)) {
+	case UC_ARRAY:
+		rv = 0;
+
+		for (size_t i = 0; i < ucv_array_length(channels); i++) {
+			uc_value_t *channel = ucv_array_get(channels, i);
+			char *s = ucv_string_get(channel);
+
+			for (size_t j = 0; j < ARRAY_SIZE(ulog_channels); j++) {
+				if (s && !strcasecmp(s, ulog_channels[j].name))
+					rv |= ulog_channels[j].value;
+				else
+					return -1;
+			}
+		}
+
+		return rv;
+
+	case UC_STRING:
+		s = ucv_string_get(channels);
+
+		for (size_t i = 0; i < ARRAY_SIZE(ulog_channels); i++)
+			if (s && !strcasecmp(s, ulog_channels[i].name))
+				return ulog_channels[i].value;
+
+		return -1;
+
+	case UC_INTEGER:
+		rv = ucv_uint64_get(channels);
+
+		if (errno == ERANGE)
+			return -1;
+
+		return rv & (ULOG_KMSG|ULOG_STDIO|ULOG_SYSLOG);
+
+	case UC_NULL:
+		return 0;
+
+	default:
+		return -1;
+	}
+}
+
+/**
+ * Configure ulog logger.
+ *
+ * This functions configures the ulog mechanism and is analogeous to using the
+ * `openlog()` function in conjuncton with `syslog()`.
+ *
+ * The `ulog_open()` function is OpenWrt specific and may not be present on
+ * other systems. Use `openlog()` and `syslog()` instead for portability to
+ * non-OpenWrt environments.
+ *
+ * A program may use multiple channels to simultaneously output messages using
+ * different means. The channel argument may either be a single string value
+ * containing a channel name, an array of channel names or a numeric value
+ * representing a bitmask of `ULOG_*` channel constants.
+ *
+ * The facility argument may be either a single string value containing a
+ * facility name or one of the numeric `LOG_*` facility constants in the module
+ * namespace.
+ *
+ * The default facility value varies, depending on the execution context of the
+ * program. In OpenWrt's preinit boot phase, or when stdout is not connected to
+ * an interactive terminal, the facility defaults to `"daemon"` (`LOG_DAEMON`),
+ * otherwise to `"user"` (`LOG_USER`).
+ *
+ * Likewise, the default channel is selected depending on the context. During
+ * OpenWrt's preinit boot phase, the `"kmsg"` channel is used, for interactive
+ * terminals the `"stdio"` one and for all other cases the `"syslog"` channel
+ * is selected.
+ *
+ * Returns `true` if ulog was configured.
+ *
+ * Returns `false` if an invalid argument, such as an unrecognized channel or
+ * facility name, was provided.
+ *
+ * @function module:log#ulog_open
+ *
+ * @param {number|module:log.UlogChannel|module:log.UlogChannel[]} [channel]
+ * Specifies the log channels to use.
+ *
+ * See {@link module:log.UlogChannel|UlogChannel} for recognized channel names.
+ *
+ * @param {number|module:log.LogFacility} [facility]
+ * The facility to use for log messages generated by subsequent `ulog()` calls.
+ *
+ * See {@link module:log.LogFacility|LogFacility} for recognized facility names.
+ *
+ * @param {string} [ident]
+ * A string identifying the program name. If omitted, the name of the calling
+ * process is used by default.
+ *
+ * @returns {boolean}
+ *
+ * @example
+ * // Log to dmesg and stderr
+ * ulog_open(["stdio", "kmsg"], "daemon", "my-program");
+ *
+ * // Use numeric constants and use implicit default ident
+ * ulog_open(ULOG_SYSLOG, LOG_LOCAL0);
+ */
+static uc_value_t *
+uc_ulog_open(uc_vm_t *vm, size_t nargs)
+{
+	int channels = parse_channels(uc_fn_arg(0));
+	int facility = parse_facility(uc_fn_arg(1));
+	char *ident = parse_ident(vm, uc_fn_arg(2));
+
+	if (channels == -1 || facility == -1)
+		return ucv_boolean_new(false);
+
+	ulog_open(channels, facility, ident);
+
+	return ucv_boolean_new(true);
+}
+
+static uc_value_t *
+uc_ulog_log_common(uc_vm_t *vm, size_t nargs, int priority)
+{
+	uc_value_t *fmt = uc_fn_arg(0), *msg;
+	uc_cfn_ptr_t fmtfn;
+	char *s;
+
+	switch (ucv_type(fmt)) {
+	case UC_STRING:
+		fmtfn = uc_stdlib_function("sprintf");
+		msg = fmtfn(vm, nargs);
+
+		if (msg) {
+			ulog(priority, "%s", ucv_string_get(msg));
+			ucv_put(msg);
+
+			return ucv_boolean_new(true);
+		}
+
+		break;
+
+	case UC_NULL:
+		break;
+
+	default:
+		s = ucv_to_string(vm, fmt);
+
+		if (s) {
+			ulog(priority, "%s", s);
+			free(s);
+
+			return ucv_boolean_new(true);
+		}
+
+		break;
+	}
+
+	return ucv_boolean_new(false);
+}
+
+/**
+ * Log a message via the ulog mechanism.
+ *
+ * The `ulog()` function outputs the given log message to all configured ulog
+ * channels unless the given priority level exceeds the globally configured ulog
+ * priority threshold. See {@link module:log#ulog_threshold|ulog_threshold()}
+ * for details.
+ *
+ * The `ulog()` function is OpenWrt specific and may not be present on other
+ * systems. Use `syslog()` instead for portability to non-OpenWrt environments.
+ *
+ * Like `syslog()`, the function behaves in a sprintf-like manner, allowing the
+ * use of format strings and associated arguments to construct log messages.
+ *
+ * If the `ulog_open()` function has not been called explicitly before, `ulog()`
+ * implicitly configures certain defaults, see
+ * {@link module:log#ulog_open|ulog_open()} for a detailled description.
+ *
+ * If the `format` argument is not a string and not `null`, it will be
+ * implicitly converted to a string and logged as-is, without further format
+ * string processing.
+ *
+ * Returns `true` if a message was passed to the underlying `ulog()` function.
+ *
+ * Returns `false` if an invalid priority value or an empty message was given.
+ *
+ * @function module:log#ulog
+ *
+ * @param {number|module:log.LogPriority} priority
+ * Log message priority. May be either a number value or a priority name string.
+ *
+ * See {@link module:log.LogPriority|LogPriority} for recognized priority names.
+ *
+ * @param {*} format
+ * The sprintf-like format string for the log message, or any other, non-null,
+ * non-string value type which will be implicitly stringified and logged as-is.
+ *
+ * @param {...*} [args]
+ * In case a format string value was provided in the previous argument, then
+ * all subsequent arguments are used to replace the placeholders in the format
+ * string.
+ *
+ * @returns {boolean}
+ *
+ * @example
+ * // Example usage of ulog function with format string and arguments
+ * const username = "user123";
+ * const errorCode = 404;
+ * ulog(LOG_ERR, "User %s encountered error: %d", username, errorCode);
+ *
+ * // Using priority names for logging
+ * ulog("err", "General error encountered");
+ *
+ * // Implicit stringification
+ * ulog("debug", { foo: 1, bar: true, baz: [1, 2, 3] });
+ *
+ * @see module:log#ulog_open
+ * @see module:log#ulog_threshold
+ * @see module:log#syslog
+ */
+static uc_value_t *
+uc_ulog_log(uc_vm_t *vm, size_t nargs)
+{
+	int priority = parse_priority(uc_fn_arg(0));
+
+	if (priority == -1 || nargs < 2)
+		return ucv_boolean_new(false);
+
+	return uc_ulog_log_common(vm, nargs - 1, priority);
+}
+
+/**
+ * Close ulog logger.
+ *
+ * Resets the ulog channels, the default facility and the log ident value to
+ * defaults.
+ *
+ * In case the `"syslog"` channel has been configured, the underlying
+ * `closelog()` function will be invoked.
+ *
+ * The usage of this function is optional, and usually an explicit ulog teardown
+ * is not required.
+ *
+ * The `ulog_close()` function is OpenWrt specific and may not be present on
+ * other systems. Use `closelog()` in conjunction with `syslog()` instead for
+ * portability to non-OpenWrt environments.
+ *
+ * @function module:log#ulog_close
+ *
+ * @see module:log#closelog
+ */
+static uc_value_t *
+uc_ulog_close(uc_vm_t *vm, size_t nargs)
+{
+	ulog_close();
+
+	return NULL;
+}
+
+/**
+ * Set ulog priority threshold.
+ *
+ * This function configures the application wide log message threshold for log
+ * messages emitted with `ulog()`. Any message with a priority higher (= less
+ * severe) than the threshold priority will be discarded. This is useful to
+ * implement application wide verbosity settings without having to wrap `ulog()`
+ * invocations into a helper function or guarding code.
+ *
+ * When no explicit threshold has been set, `LOG_DEBUG` is used by default,
+ * allowing log messages with all known priorities.
+ *
+ * The `ulog_threshold()` function is OpenWrt specific and may not be present on
+ * other systems. There is no syslog equivalent to this ulog specific threshold
+ * mechanism.
+ *
+ * The priority argument may be either a string value containing a priority name
+ * or one of the numeric `LOG_*` priority constants in the module namespace.
+ *
+ * Returns `true` if a threshold was set.
+ *
+ * Returns `false` if an invalid priority value was given.
+ *
+ * @function module:log#ulog_threshold
+ *
+ * @param {number|module:log.LogPriority} [priority]
+ * The priority threshold to configure.
+ *
+ * See {@link module:log.LogPriority|LogPriority} for recognized priority names.
+ *
+ * @returns {boolean}
+ *
+ * @example
+ * // Set threshold to "warning" or more severe
+ * ulog_threshold(LOG_WARNING);
+ *
+ * // This message will be supressed
+ * ulog(LOG_DEBUG, "Testing thresholds");
+ *
+ * // Using priority name
+ * ulog_threshold("debug");
+ */
+static uc_value_t *
+uc_ulog_threshold(uc_vm_t *vm, size_t nargs)
+{
+	int priority = parse_priority(uc_fn_arg(0));
+
+	if (priority == -1)
+		return ucv_boolean_new(false);
+
+	ulog_threshold(priority);
+
+	return ucv_boolean_new(true);
+}
+
+/**
+ * Invoke ulog with LOG_INFO.
+ *
+ * This function is convenience wrapper for `ulog(LOG_INFO, ...)`.
+ *
+ * See {@link module:log#ulog|ulog()} for details.
+ *
+ * @function module:log#INFO
+ *
+ * @param {*} format
+ * The sprintf-like format string for the log message, or any other, non-null,
+ * non-string value type which will be implicitly stringified and logged as-is.
+ *
+ * @param {...*} [args]
+ * In case a format string value was provided in the previous argument, then
+ * all subsequent arguments are used to replace the placeholders in the format
+ * string.
+ *
+ * @returns {boolean}
+ *
+ * @example
+ * INFO("This is an info log message");
+ */
+static uc_value_t *
+uc_ulog_INFO(uc_vm_t *vm, size_t nargs)
+{
+	return uc_ulog_log_common(vm, nargs, LOG_INFO);
+}
+
+/**
+ * Invoke ulog with LOG_NOTICE.
+ *
+ * This function is convenience wrapper for `ulog(LOG_NOTICE, ...)`.
+ *
+ * See {@link module:log#ulog|ulog()} for details.
+ *
+ * @function module:log#NOTE
+ *
+ * @param {*} format
+ * The sprintf-like format string for the log message, or any other, non-null,
+ * non-string value type which will be implicitly stringified and logged as-is.
+ *
+ * @param {...*} [args]
+ * In case a format string value was provided in the previous argument, then
+ * all subsequent arguments are used to replace the placeholders in the format
+ * string.
+ *
+ * @returns {boolean}
+ *
+ * @example
+ * NOTE("This is a notification log message");
+ */
+static uc_value_t *
+uc_ulog_NOTE(uc_vm_t *vm, size_t nargs)
+{
+	return uc_ulog_log_common(vm, nargs, LOG_NOTICE);
+}
+
+/**
+ * Invoke ulog with LOG_WARNING.
+ *
+ * This function is convenience wrapper for `ulog(LOG_WARNING, ...)`.
+ *
+ * See {@link module:log#ulog|ulog()} for details.
+ *
+ * @function module:log#WARN
+ *
+ * @param {*} format
+ * The sprintf-like format string for the log message, or any other, non-null,
+ * non-string value type which will be implicitly stringified and logged as-is.
+ *
+ * @param {...*} [args]
+ * In case a format string value was provided in the previous argument, then
+ * all subsequent arguments are used to replace the placeholders in the format
+ * string.
+ *
+ * @returns {boolean}
+ *
+ * @example
+ * WARN("This is a warning");
+ */
+static uc_value_t *
+uc_ulog_WARN(uc_vm_t *vm, size_t nargs)
+{
+	return uc_ulog_log_common(vm, nargs, LOG_WARNING);
+}
+
+/**
+ * Invoke ulog with LOG_ERR.
+ *
+ * This function is convenience wrapper for `ulog(LOG_ERR, ...)`.
+ *
+ * See {@link module:log#ulog|ulog()} for details.
+ *
+ * @function module:log#ERR
+ *
+ * @param {*} format
+ * The sprintf-like format string for the log message, or any other, non-null,
+ * non-string value type which will be implicitly stringified and logged as-is.
+ *
+ * @param {...*} [args]
+ * In case a format string value was provided in the previous argument, then
+ * all subsequent arguments are used to replace the placeholders in the format
+ * string.
+ *
+ * @returns {boolean}
+ *
+ * @example
+ * ERR("This is an error!");
+ */
+static uc_value_t *
+uc_ulog_ERR(uc_vm_t *vm, size_t nargs)
+{
+	return uc_ulog_log_common(vm, nargs, LOG_ERR);
+}
+#endif
+
+
+static const uc_function_list_t global_fns[] = {
+	{ "openlog",		uc_openlog },
+	{ "syslog",			uc_syslog },
+	{ "closelog",		uc_closelog },
+
+#ifdef HAVE_ULOG
+	{ "ulog_open",		uc_ulog_open },
+	{ "ulog",			uc_ulog_log },
+	{ "ulog_close",		uc_ulog_close },
+	{ "ulog_threshold",	uc_ulog_threshold },
+	{ "INFO",			uc_ulog_INFO },
+	{ "NOTE",			uc_ulog_NOTE },
+	{ "WARN",			uc_ulog_WARN },
+	{ "ERR",			uc_ulog_ERR },
+#endif
+};
+
+
+void uc_module_init(uc_vm_t *vm, uc_value_t *scope)
+{
+	uc_function_list_register(scope, global_fns);
+
+#define ADD_CONST(x) ucv_object_add(scope, #x, ucv_int64_new(x))
+
+	ADD_CONST(LOG_PID);
+	ADD_CONST(LOG_CONS);
+	ADD_CONST(LOG_NDELAY);
+	ADD_CONST(LOG_ODELAY);
+	ADD_CONST(LOG_NOWAIT);
+
+	ADD_CONST(LOG_AUTH);
+#ifdef LOG_AUTHPRIV
+	ADD_CONST(LOG_AUTHPRIV);
+#endif
+	ADD_CONST(LOG_CRON);
+	ADD_CONST(LOG_DAEMON);
+#ifdef LOG_FTP
+	ADD_CONST(LOG_FTP);
+#endif
+	ADD_CONST(LOG_KERN);
+	ADD_CONST(LOG_LPR);
+	ADD_CONST(LOG_MAIL);
+	ADD_CONST(LOG_NEWS);
+	ADD_CONST(LOG_SYSLOG);
+	ADD_CONST(LOG_USER);
+	ADD_CONST(LOG_UUCP);
+	ADD_CONST(LOG_LOCAL0);
+	ADD_CONST(LOG_LOCAL1);
+	ADD_CONST(LOG_LOCAL2);
+	ADD_CONST(LOG_LOCAL3);
+	ADD_CONST(LOG_LOCAL4);
+	ADD_CONST(LOG_LOCAL5);
+	ADD_CONST(LOG_LOCAL6);
+	ADD_CONST(LOG_LOCAL7);
+
+	ADD_CONST(LOG_EMERG);
+	ADD_CONST(LOG_ALERT);
+	ADD_CONST(LOG_CRIT);
+	ADD_CONST(LOG_ERR);
+	ADD_CONST(LOG_WARNING);
+	ADD_CONST(LOG_NOTICE);
+	ADD_CONST(LOG_INFO);
+	ADD_CONST(LOG_DEBUG);
+
+#ifdef HAVE_ULOG
+	ADD_CONST(ULOG_KMSG);
+	ADD_CONST(ULOG_SYSLOG);
+	ADD_CONST(ULOG_STDIO);
+#endif
+}
+
ucode Documentation
\ No newline at end of file diff --git a/lib_math.c.html b/lib_math.c.html index 545fe28f..332f400e 100644 --- a/lib_math.c.html +++ b/lib_math.c.html @@ -1,6 +1,6 @@ Source: lib/math.c
On this page

lib_math.c

/*
+    
On this page

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);
 }
-
\ No newline at end of file +
ucode Documentation
\ No newline at end of file diff --git a/lib_struct.c.html b/lib_struct.c.html index 06df2fcc..6f2e370a 100644 --- a/lib_struct.c.html +++ b/lib_struct.c.html @@ -1,6 +1,6 @@ Source: lib/struct.c
On this page

lib_struct.c

/*
+    
On this page

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);
 }
-
\ No newline at end of file +
ucode Documentation
\ No newline at end of file diff --git a/module-core.html b/module-core.html index 0c5a8052..daef245e 100644 --- a/module-core.html +++ b/module-core.html @@ -1,6 +1,6 @@ Module: core
On this page

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|null}

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
arrArray.<number>

The byte array to convert into an IP address string.

Returns:
Type: 
string | null
Example
arrtoip([ 192, 168, 1, 1 ])   // "192.168.1.1"
+    
On this page

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|null}

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
arrArray.<number>

The byte array to convert into an IP address string.

Returns:
Type: 
string | null
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)
@@ -270,4 +270,4 @@
 print(x, "\n");    // [ 1, 2, 3, 4, 5 ]

values(obj) → {Array|null}

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:
Type: 
Array | null
Example
values({ foo: true, bar: false });   // [true, false]

warn(…x) → {number}

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

Returns the amount of bytes printed.

Parameters:
NameTypeAttributesDescription
x*<repeatable>

The values to be printed.

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

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

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

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

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

Parameters:
NameTypeAttributesDescription
subject*

The subject to match against the wildcard pattern.

patternstring

The wildcard pattern.

nocaseboolean<optional>

Whether to perform case-insensitive matching.

Returns:
Type: 
boolean
Example
wildcard("file.txt", "*.txt");        // Returns true
 wildcard("file.txt", "*.TXT", true);  // Returns true (case-insensitive match)
-wildcard("file.txt", "*.jpg");        // Returns false
\ No newline at end of file +wildcard("file.txt", "*.jpg"); // Returns false
ucode Documentation
\ No newline at end of file diff --git a/module-debug.html b/module-debug.html index d805eea1..062a8322 100644 --- a/module-debug.html +++ b/module-debug.html @@ -1,6 +1,6 @@ Module: debug
On this page

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';
+    
On this page

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) → {module:debug.ValueInformation|null}

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.

Returns:
Type: 
module:debug.ValueInformation | null

getlocal(levelopt, variable) → {module:debug.LocalInfo|null}

Obtain local variable.

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

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

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

Returns a dictionary holding information about the given variable.

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

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

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

Parameters:
NameTypeAttributesDefaultDescription
levelnumber<optional>
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:
Type: 
module:debug.LocalInfo | null

getupval(target, variable) → {module:debug.UpvalInfo|null}

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:
Type: 
module:debug.UpvalInfo | null

memdump(file) → {boolean|null}

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:
Type: 
boolean | null

setlocal(levelopt, variable, valueopt) → {module:debug.LocalInfo|null}

Set local variable.

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

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

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

Returns a dictionary holding information about the updated variable.

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

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

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

Parameters:
NameTypeAttributesDefaultDescription
levelnumber<optional>
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>
null

The value to set the local variable to.

Returns:
Type: 
module:debug.LocalInfo | null

setupval(target, variable, value) → {module:debug.UpvalInfo|null}

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:
Type: 
module:debug.UpvalInfo | null

sourcepos() → {module:debug.SourcePosition|null}

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.

Returns:
Type: 
module:debug.SourcePosition | null

traceback(levelopt) → {Array.<module:debug.StackTraceEntry>}

Capture call stack trace.

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

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

Parameters:
NameTypeAttributesDefaultDescription
levelnumber<optional>
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:
Type: 
Array.<module:debug.StackTraceEntry>

Type Definitions

LocalInfo

Type:
  • 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

Type:
  • 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

Type:
  • 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.

strictboolean<optional>

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

filenamestring<optional>

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

linenumber<optional>

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

bytenumber<optional>

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

contextstring<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

Type:
  • 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

Type:
  • 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.

slotnumber<optional>

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

ValueInformation

Type:
  • 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.

markboolean<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.

refcountnumber<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.

unsignedboolean<optional>

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

addressnumber<optional>

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

lengthnumber<optional>

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

countnumber<optional>

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

constantboolean<optional>

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

prototype*<optional>

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

sourcestring<optional>

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

icaseboolean<optional>

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

globalboolean<optional>

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

newlineboolean<optional>

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

nsubnumber<optional>

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

namestring<optional>

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

arrowboolean<optional>

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

moduleboolean<optional>

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

strictboolean<optional>

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

varargboolean<optional>

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

nargsnumber<optional>

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

argnamesArray.<string><optional>

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

nupvalsnumber<optional>

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

upvalsArray.<module:debug.UpvalRef><optional>

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

filenamestring<optional>

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

linenumber<optional>

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

bytenumber<optional>

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

typestring<optional>

The resource type name. Only applicable to resource values.

\ 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) → {module:debug.ValueInformation|null}

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.

Returns:
Type: 
module:debug.ValueInformation | null

getlocal(levelopt, variable) → {module:debug.LocalInfo|null}

Obtain local variable.

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

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

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

Returns a dictionary holding information about the given variable.

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

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

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

Parameters:
NameTypeAttributesDefaultDescription
levelnumber<optional>
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:
Type: 
module:debug.LocalInfo | null

getupval(target, variable) → {module:debug.UpvalInfo|null}

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:
Type: 
module:debug.UpvalInfo | null

memdump(file) → {boolean|null}

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:
Type: 
boolean | null

setlocal(levelopt, variable, valueopt) → {module:debug.LocalInfo|null}

Set local variable.

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

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

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

Returns a dictionary holding information about the updated variable.

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

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

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

Parameters:
NameTypeAttributesDefaultDescription
levelnumber<optional>
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>
null

The value to set the local variable to.

Returns:
Type: 
module:debug.LocalInfo | null

setupval(target, variable, value) → {module:debug.UpvalInfo|null}

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:
Type: 
module:debug.UpvalInfo | null

sourcepos() → {module:debug.SourcePosition|null}

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.

Returns:
Type: 
module:debug.SourcePosition | null

traceback(levelopt) → {Array.<module:debug.StackTraceEntry>}

Capture call stack trace.

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

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

Parameters:
NameTypeAttributesDefaultDescription
levelnumber<optional>
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:
Type: 
Array.<module:debug.StackTraceEntry>

Type Definitions

LocalInfo

Type:
  • 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

Type:
  • 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

Type:
  • 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.

strictboolean<optional>

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

filenamestring<optional>

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

linenumber<optional>

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

bytenumber<optional>

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

contextstring<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

Type:
  • 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

Type:
  • 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.

slotnumber<optional>

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

ValueInformation

Type:
  • 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.

markboolean<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.

refcountnumber<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.

unsignedboolean<optional>

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

addressnumber<optional>

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

lengthnumber<optional>

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

countnumber<optional>

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

constantboolean<optional>

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

prototype*<optional>

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

sourcestring<optional>

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

icaseboolean<optional>

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

globalboolean<optional>

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

newlineboolean<optional>

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

nsubnumber<optional>

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

namestring<optional>

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

arrowboolean<optional>

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

moduleboolean<optional>

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

strictboolean<optional>

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

varargboolean<optional>

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

nargsnumber<optional>

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

argnamesArray.<string><optional>

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

nupvalsnumber<optional>

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

upvalsArray.<module:debug.UpvalRef><optional>

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

filenamestring<optional>

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

linenumber<optional>

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

bytenumber<optional>

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

typestring<optional>

The resource type name. Only applicable to resource values.

ucode Documentation
\ No newline at end of file diff --git a/module-fs.dir.html b/module-fs.dir.html index 33696838..2f2b966a 100644 --- a/module-fs.dir.html +++ b/module-fs.dir.html @@ -1,6 +1,6 @@ Class: dir
On this page

fs. dir

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

Example
const handle = opendir(…);
+    
On this page

fs. dir

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

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

tell() → {number|null}

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:
Type: 
number | null
\ No newline at end of file +print(handle.read(), "\n"); // prints the first entry again

tell() → {number|null}

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:
Type: 
number | null
ucode Documentation
\ No newline at end of file diff --git a/module-fs.file.html b/module-fs.file.html index 04957c56..70b23515 100644 --- a/module-fs.file.html +++ b/module-fs.file.html @@ -1,6 +1,6 @@ Class: file
On this page

fs. file

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

Example
const handle = open(…);
+    
On this page

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(…);
@@ -45,4 +45,4 @@
 fp.seek(-10, 2);            // set position to ten bytes before EOF ...
 print(fp.read(100), "\n");  // ... reads 10 bytes at most

tell() → {number|null}

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:
Type: 
number | null

write(data) → {number|null}

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:
Type: 
number | null
Example
const fp = open("file.txt", "w");
 
-fp.write("Hello world!\n");
\ No newline at end of file +fp.write("Hello world!\n");
ucode Documentation
\ No newline at end of file diff --git a/module-fs.html b/module-fs.html index 6e169720..04fda7bd 100644 --- a/module-fs.html +++ b/module-fs.html @@ -1,6 +1,6 @@ Module: fs
On this page

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';
+    
On this page

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

Type:
  • 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.).

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

Type Definitions

FileStatResult

Type:
  • 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
\ No newline at end of file diff --git a/module-fs.proc.html b/module-fs.proc.html index 9f30f004..25f63662 100644 --- a/module-fs.proc.html +++ b/module-fs.proc.html @@ -1,6 +1,6 @@ Class: proc
On this page

fs. proc

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

Example
const handle = popen(…);
+    
On this page

fs. proc

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

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

write(data) → {number|null}

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:
Type: 
number | null
Example
const fp = popen("command", "w");
 
-fp.write("Hello world!\n");
\ No newline at end of file +fp.write("Hello world!\n");
ucode Documentation
\ No newline at end of file diff --git a/module-log.html b/module-log.html new file mode 100644 index 00000000..ea0bac55 --- /dev/null +++ b/module-log.html @@ -0,0 +1,61 @@ +Module: log
On this page

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!");
+
+// OpenWrt specific ulog functions
+import { ulog_open, ulog, ULOG_SYSLOG, LOG_DAEMON, LOG_INFO } from 'log';
+
+ulog_open(ULOG_SYSLOG, LOG_DAEMON, "my-log-ident");
+ulog(LOG_INFO, "The current epoch is %d", time());
+

Alternatively, the module namespace can be imported using a wildcard import statement:

import * as log from 'log';
+
+log.openlog("my-log-ident", log.LOG_PID, log.LOG_USER);
+log.syslog(log.LOG_ERR, "An error occurred!");
+
+// OpenWrt specific ulog functions
+log.ulog_open(log.ULOG_SYSLOG, log.LOG_DAEMON, "my-log-ident");
+log.ulog(log.LOG_INFO, "The current epoch is %d", time());
+

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

Constants

The log module declares a number of numeric constants to specify logging facility, priority and option values, as well as ulog specific channels.

Syslog Options

Constant NameDescription
LOG_PIDInclude PID with each message.
LOG_CONSLog to console if error occurs while sending to syslog.
LOG_NDELAYOpen the connection to the logger immediately.
LOG_ODELAYDelay open until the first message is logged.
LOG_NOWAITDo not wait for child processes created during logging.

Syslog Facilities

Constant NameDescription
LOG_AUTHAuthentication/authorization messages.
LOG_AUTHPRIVPrivate authentication messages.
LOG_CRONClock daemon (cron and at commands).
LOG_DAEMONSystem daemons without separate facility values.
LOG_FTPFTP server daemon.
LOG_KERNKernel messages.
LOG_LPRLine printer subsystem.
LOG_MAILMail system.
LOG_NEWSNetwork news subsystem.
LOG_SYSLOGMessages generated internally by syslogd.
LOG_USERGeneric user-level messages.
LOG_UUCPUUCP subsystem.
LOG_LOCAL0Local use 0 (custom facility).
LOG_LOCAL1Local use 1 (custom facility).
LOG_LOCAL2Local use 2 (custom facility).
LOG_LOCAL3Local use 3 (custom facility).
LOG_LOCAL4Local use 4 (custom facility).
LOG_LOCAL5Local use 5 (custom facility).
LOG_LOCAL6Local use 6 (custom facility).
LOG_LOCAL7Local use 7 (custom facility).

Syslog Priorities

Constant NameDescription
LOG_EMERGSystem is unusable.
LOG_ALERTAction must be taken immediately.
LOG_CRITCritical conditions.
LOG_ERRError conditions.
LOG_WARNINGWarning conditions.
LOG_NOTICENormal, but significant, condition.
LOG_INFOInformational message.
LOG_DEBUGDebug-level message.

Ulog channels

Constant NameDescription
ULOG_KMSGLog messages to /dev/kmsg (dmesg).
ULOG_STDIOLog messages to stdout.
ULOG_SYSLOGLog messages to syslog.

Methods

ERR(format, …argsopt) → {boolean}

Invoke ulog with LOG_ERR.

This function is convenience wrapper for ulog(LOG_ERR, ...).

See ulog() for details.

Parameters:
NameTypeAttributesDescription
format*

The sprintf-like format string for the log message, or any other, non-null, non-string value type which will be implicitly stringified and logged as-is.

args*<optional>
<repeatable>

In case a format string value was provided in the previous argument, then all subsequent arguments are used to replace the placeholders in the format string.

Returns:
Type: 
boolean
Example
ERR("This is an error!");

INFO(format, …argsopt) → {boolean}

Invoke ulog with LOG_INFO.

This function is convenience wrapper for ulog(LOG_INFO, ...).

See ulog() for details.

Parameters:
NameTypeAttributesDescription
format*

The sprintf-like format string for the log message, or any other, non-null, non-string value type which will be implicitly stringified and logged as-is.

args*<optional>
<repeatable>

In case a format string value was provided in the previous argument, then all subsequent arguments are used to replace the placeholders in the format string.

Returns:
Type: 
boolean
Example
INFO("This is an info log message");

NOTE(format, …argsopt) → {boolean}

Invoke ulog with LOG_NOTICE.

This function is convenience wrapper for ulog(LOG_NOTICE, ...).

See ulog() for details.

Parameters:
NameTypeAttributesDescription
format*

The sprintf-like format string for the log message, or any other, non-null, non-string value type which will be implicitly stringified and logged as-is.

args*<optional>
<repeatable>

In case a format string value was provided in the previous argument, then all subsequent arguments are used to replace the placeholders in the format string.

Returns:
Type: 
boolean
Example
NOTE("This is a notification log message");

WARN(format, …argsopt) → {boolean}

Invoke ulog with LOG_WARNING.

This function is convenience wrapper for ulog(LOG_WARNING, ...).

See ulog() for details.

Parameters:
NameTypeAttributesDescription
format*

The sprintf-like format string for the log message, or any other, non-null, non-string value type which will be implicitly stringified and logged as-is.

args*<optional>
<repeatable>

In case a format string value was provided in the previous argument, then all subsequent arguments are used to replace the placeholders in the format string.

Returns:
Type: 
boolean
Example
WARN("This is a warning");

closelog()

Close connection to system logger.

The usage of this function is optional, and usually an explicit log connection tear down is not required.

openlog(identopt, optionsopt, facilityopt) → {boolean}

Open connection to system logger.

The openlog() function instructs the program to establish a connection to the system log service and configures the default facility and identification for use in subsequent log operations. It may be omitted, in which case the first call to syslog() will implicitly call openlog() with a default ident value representing the program name and a default LOG_USER facility.

The log option argument may be either a single string value containing an option name, an array of option name strings or a numeric value representing a bitmask of LOG_* option constants.

The facility argument may be either a single string value containing a facility name or one of the numeric LOG_* facility constants in the module namespace.

Returns true if the system openlog() function was invoked.

Returns false if an invalid argument, such as an unrecognized option or facility name, was provided.

Parameters:
NameTypeAttributesDefaultDescription
identstring<optional>

A string identifying the program name. If omitted, the name of the calling process is used by default.

optionsnumber | module:log.LogOption | Array.<module:log.LogOption><optional>

Logging options to use.

See LogOption for recognized option names.

facilitynumber | module:log.LogFacility<optional>
"user"

The facility to use for log messages generated by subsequent syslog calls.

See LogFacility for recognized facility names.

Returns:
Type: 
boolean
Example
// Example usage of openlog function
+openlog("myapp", LOG_PID | LOG_NDELAY, LOG_LOCAL0);
+
+// Using option names instead of bitmask and LOG_USER facility
+openlog("myapp", [ "pid", "ndelay" ], "user");

syslog(priority, format, …argsopt) → {boolean}

Log a message to the system logger.

This function logs a message to the system logger. The function behaves in a sprintf-like manner, allowing the use of format strings and associated arguments to construct log messages.

If the openlog function has not been called explicitly before, syslog() implicitly calls openlog(), using a default ident and LOG_USER facility value before logging the message.

If the format argument is not a string and not null, it will be implicitly converted to a string and logged as-is, without further format string processing.

Returns true if a message was passed to the system syslog() function.

Returns false if an invalid priority value or an empty message was given.

Parameters:
NameTypeAttributesDescription
prioritynumber | module:log.LogPriority

Log message priority. May be either a number value (potentially bitwise OR-ed with a log facility constant) which is passed as-is to the system syslog() function or a priority name string.

See LogPriority for recognized priority names.

format*

The sprintf-like format string for the log message, or any other, non-null, non-string value type which will be implicitly stringified and logged as-is.

args*<optional>
<repeatable>

In case a format string value was provided in the previous argument, then all subsequent arguments are used to replace the placeholders in the format string.

Returns:
Type: 
boolean
Example
// Example usage of syslog function with format string and arguments
+const username = "user123";
+const errorCode = 404;
+syslog(LOG_ERR, "User %s encountered error: %d", username, errorCode);
+
+// If openlog has not been called explicitly, it is implicitly called with defaults:
+syslog(LOG_INFO, "This message will be logged with default settings.");
+
+// Selectively override used facility by OR-ing numeric constant
+const password =" secret";
+syslog(LOG_DEBUG|LOG_AUTHPRIV, "The password %s has been wrong", secret);
+
+// Using priority names for logging
+syslog("emerg", "System shutdown imminent!");
+
+// Implicit stringification
+syslog("debug", { foo: 1, bar: true, baz: [1, 2, 3] });

ulog(priority, format, …argsopt) → {boolean}

Log a message via the ulog mechanism.

The ulog() function outputs the given log message to all configured ulog channels unless the given priority level exceeds the globally configured ulog priority threshold. See ulog_threshold() for details.

The ulog() function is OpenWrt specific and may not be present on other systems. Use syslog() instead for portability to non-OpenWrt environments.

Like syslog(), the function behaves in a sprintf-like manner, allowing the use of format strings and associated arguments to construct log messages.

If the ulog_open() function has not been called explicitly before, ulog() implicitly configures certain defaults, see ulog_open() for a detailled description.

If the format argument is not a string and not null, it will be implicitly converted to a string and logged as-is, without further format string processing.

Returns true if a message was passed to the underlying ulog() function.

Returns false if an invalid priority value or an empty message was given.

Parameters:
NameTypeAttributesDescription
prioritynumber | module:log.LogPriority

Log message priority. May be either a number value or a priority name string.

See LogPriority for recognized priority names.

format*

The sprintf-like format string for the log message, or any other, non-null, non-string value type which will be implicitly stringified and logged as-is.

args*<optional>
<repeatable>

In case a format string value was provided in the previous argument, then all subsequent arguments are used to replace the placeholders in the format string.

Returns:
Type: 
boolean
Example
// Example usage of ulog function with format string and arguments
+const username = "user123";
+const errorCode = 404;
+ulog(LOG_ERR, "User %s encountered error: %d", username, errorCode);
+
+// Using priority names for logging
+ulog("err", "General error encountered");
+
+// Implicit stringification
+ulog("debug", { foo: 1, bar: true, baz: [1, 2, 3] });

ulog_close()

Close ulog logger.

Resets the ulog channels, the default facility and the log ident value to defaults.

In case the "syslog" channel has been configured, the underlying closelog() function will be invoked.

The usage of this function is optional, and usually an explicit ulog teardown is not required.

The ulog_close() function is OpenWrt specific and may not be present on other systems. Use closelog() in conjunction with syslog() instead for portability to non-OpenWrt environments.

ulog_open(channelopt, facilityopt, identopt) → {boolean}

Configure ulog logger.

This functions configures the ulog mechanism and is analogeous to using the openlog() function in conjuncton with syslog().

The ulog_open() function is OpenWrt specific and may not be present on other systems. Use openlog() and syslog() instead for portability to non-OpenWrt environments.

A program may use multiple channels to simultaneously output messages using different means. The channel argument may either be a single string value containing a channel name, an array of channel names or a numeric value representing a bitmask of ULOG_* channel constants.

The facility argument may be either a single string value containing a facility name or one of the numeric LOG_* facility constants in the module namespace.

The default facility value varies, depending on the execution context of the program. In OpenWrt's preinit boot phase, or when stdout is not connected to an interactive terminal, the facility defaults to "daemon" (LOG_DAEMON), otherwise to "user" (LOG_USER).

Likewise, the default channel is selected depending on the context. During OpenWrt's preinit boot phase, the "kmsg" channel is used, for interactive terminals the "stdio" one and for all other cases the "syslog" channel is selected.

Returns true if ulog was configured.

Returns false if an invalid argument, such as an unrecognized channel or facility name, was provided.

Parameters:
NameTypeAttributesDescription
channelnumber | module:log.UlogChannel | Array.<module:log.UlogChannel><optional>

Specifies the log channels to use.

See UlogChannel for recognized channel names.

facilitynumber | module:log.LogFacility<optional>

The facility to use for log messages generated by subsequent ulog() calls.

See LogFacility for recognized facility names.

identstring<optional>

A string identifying the program name. If omitted, the name of the calling process is used by default.

Returns:
Type: 
boolean
Example
// Log to dmesg and stderr
+ulog_open(["stdio", "kmsg"], "daemon", "my-program");
+
+// Use numeric constants and use implicit default ident
+ulog_open(ULOG_SYSLOG, LOG_LOCAL0);

ulog_threshold(priorityopt) → {boolean}

Set ulog priority threshold.

This function configures the application wide log message threshold for log messages emitted with ulog(). Any message with a priority higher (= less severe) than the threshold priority will be discarded. This is useful to implement application wide verbosity settings without having to wrap ulog() invocations into a helper function or guarding code.

When no explicit threshold has been set, LOG_DEBUG is used by default, allowing log messages with all known priorities.

The ulog_threshold() function is OpenWrt specific and may not be present on other systems. There is no syslog equivalent to this ulog specific threshold mechanism.

The priority argument may be either a string value containing a priority name or one of the numeric LOG_* priority constants in the module namespace.

Returns true if a threshold was set.

Returns false if an invalid priority value was given.

Parameters:
NameTypeAttributesDescription
prioritynumber | module:log.LogPriority<optional>

The priority threshold to configure.

See LogPriority for recognized priority names.

Returns:
Type: 
boolean
Example
// Set threshold to "warning" or more severe
+ulog_threshold(LOG_WARNING);
+
+// This message will be supressed
+ulog(LOG_DEBUG, "Testing thresholds");
+
+// Using priority name
+ulog_threshold("debug");

Type Definitions

LogFacility

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).
Type:
  • string

LogOption

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.
Type:
  • string

LogPriority

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.
Type:
  • string

UlogChannel

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.
Type:
  • string
ucode Documentation
\ No newline at end of file diff --git a/module-math.html b/module-math.html index 48ab2691..a2049972 100644 --- a/module-math.html +++ b/module-math.html @@ -1,6 +1,6 @@ Module: math
On this page

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';
+    
On this page

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:

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

Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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.

\ 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:

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

Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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:
Type: 
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
\ No newline at end of file diff --git a/module-struct.html b/module-struct.html index 5b9a8884..0d27dcaa 100644 --- a/module-struct.html +++ b/module-struct.html @@ -1,6 +1,6 @@ Module: struct
On this page

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';
+    
On this page

Handle Packed Binary Data

The struct module provides routines for interpreting byte strings as packed binary data.

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

import { pack, unpack } from 'struct';
 
 let buffer = pack('bhl', -13, 1234, 444555666);
 let values = unpack('bhl', buffer);
@@ -45,4 +45,4 @@
 const data = pack('!III', 1, 2, 3);

unpack(format, input, offsetopt) → {array}

Unpack given byte string according to specified format.

The unpack() function interpretes a byte string according to the given format string and returns the resulting values. If the optional offset argument is given, unpacking starts from this byte position within the input. If not specified, the start offset defaults to 0, the start of the given input string.

Returns an array of unpacked values.

Raises a runtime exception if the format string is invalid or if an invalid input string or offset value is given.

Parameters:
NameTypeAttributesDefaultDescription
formatstring

The format string.

inputstring

The input string to unpack.

offsetnumber<optional>
0

The offset within the input string to start unpacking from.

Returns:
Type: 
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 ]
\ No newline at end of file +print(numbers, "\n"); // [ 1, 2, 3 ]
ucode Documentation
\ No newline at end of file diff --git a/module-struct.instance.html b/module-struct.instance.html index 881a5569..69325287 100644 --- a/module-struct.instance.html +++ b/module-struct.instance.html @@ -1,9 +1,9 @@ Class: instance
On this page

struct. instance

Represents a struct instance created by new().

Example
const fmt = struct.new(…);
+    
On this page

struct. instance

Represents a struct instance created by new().

Example
const fmt = struct.new(…);
 
 fmt.pack(…);
 
 const values = fmt.unpack(…);

Methods

pack(…values) → {string}

Pack given values.

The pack() function creates a byte string containing the argument values packed according to the given format instance.

Returns the packed string.

Raises a runtime exception if a given argument value does not match the required type of the corresponding format string directive.

Parameters:
NameTypeAttributesDescription
values*<repeatable>

Variable number of values to pack.

Returns:
Type: 
string
Example
const fmt = struct.new(…);
 const data = fmt.pack(…);

unpack(input, offsetopt) → {array}

Unpack given byte string.

The unpack() function interpretes a byte string according to the given format instance and returns the resulting values. If the optional offset argument is given, unpacking starts from this byte position within the input. If not specified, the start offset defaults to 0, the start of the given input string.

Returns an array of unpacked values.

Raises a runtime exception if an invalid input string or offset value is given.

Parameters:
NameTypeAttributesDefaultDescription
inputstring

The input string to unpack.

offsetnumber<optional>
0

The offset within the input string to start unpacking from.

Returns:
Type: 
array
Example
const fmt = struct.new(…);
-const values = fmt.unpack(…);
\ No newline at end of file +const values = fmt.unpack(…);
ucode Documentation
\ No newline at end of file diff --git a/tutorial-01-usage.html b/tutorial-01-usage.html index 8afed764..c9791410 100644 --- a/tutorial-01-usage.html +++ b/tutorial-01-usage.html @@ -1,8 +1,8 @@ Tutorial: Usage
On this page

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');"
    +    
    On this page

    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
      -
    \ No newline at end of file +
ucode Documentation
\ No newline at end of file diff --git a/tutorial-02-syntax.html b/tutorial-02-syntax.html index 2bbb613f..1fa2abb3 100644 --- a/tutorial-02-syntax.html +++ b/tutorial-02-syntax.html @@ -1,6 +1,6 @@ Tutorial: Syntax
On this page

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
+    
On this page

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).

\ No newline at end of file +

5.7. Precedence

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

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

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

ucode Documentation
\ No newline at end of file diff --git a/tutorial-03-memory.html b/tutorial-03-memory.html index d57c50ad..86aaa894 100644 --- a/tutorial-03-memory.html +++ b/tutorial-03-memory.html @@ -1,6 +1,6 @@ Tutorial: Memory Management
On this page

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 } ];
+    
On this page

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.

\ No newline at end of file +

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

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

ucode Documentation
\ No newline at end of file