Modules

Modules. #

Modules contain accessible static symbols under a defined namespace. By default, importing another Cyber script returns its module with exported symbols.

Importing. #

Import declarations create a local alias to the module referenced by the import specifier. The Cyber CLI comes with some builtin modules like math and test. If the specifier does not refer to a builtin module, it looks for a Cyber script file relative to the current script’s directory. An embedder can integrate their own module loader.

import t 'test'
try t.eq(123, 123)

-- Imports are static declarations so they can be anywhere in the script.
import m 'math'
print m.cos(0)

-- Loading another Cyber script.
import foo 'bar.cy'
print foo.myFunc()
print foo.myVar

A Cyber script that is imported doesn’t evaluate its main block. Only static declarations are effectively loaded. If there is code in the main block, it will skip evaluation. In the following, only the print statement in the main.cy is evaluated.

-- main.cy
import a 'foo.cy'
print a.foo

-- foo.cy
import 'bar.cy'
export var foo: 123
print foo         -- Statement is ignored.

-- bar.cy
export var bar: 321
print bar         -- Statement is ignored.

You can have circular imports in Cyber. In the following example, main.cy and foo.cy import each other without any problems.

-- main.cy
import foo 'foo.cy'

export func printB():
    foo.printC()

foo.printA()

-- foo.cy
import main 'main.cy'

export func printA():
    main.printB()

export func printC():
    print 'done'

Static variable declarations from imports can have circular references. Read more about this in Static Variables.

Modules can also be destructured using the following syntax:

import { cos, pi } 'math'
print cos(pi)

Exporting. #

Use the export prefix in front of static declarations to indicate that it should be exported when the script’s module is loaded.

export func foo():
    print 123

export var bar: 234

Builtin Modules. #

Cyber currently contains the builtin modules:

  • core: Cyber related functions and commonly used utilities.
  • math: Math constants and functions.
  • os: System level functions.
  • test: Utilities for testing.

Core Module. #

The core module contains functions related to Cyber and common utilities. It is automatically imported into each script’s namespace.

Sample usage:

print 'hello'
contents = readFile 'foo.txt'
print contents
FunctionSummary
arrayFill(val any, n number) ListCreates a list with initial capacity of n and values set to val. If the value is an object, it is shallow copied n times.
boolean(val any) booleanConverts a value to either true or false.
cacheUrl(url string) stringReturns the path of a locally cached file of url. If no such file exists locally, it’s fetched from url.
copy(val any) anyCopies a primitive value or creates a shallow copy of an object value.
execCmd(args []string) Map{ out, err, exited }Runs a shell command and returns the stdout/stderr.
exit(status number) noreturnExits the program with a status code.
error(any) errorCreate an error from a tag or tag literal.
evalJS(val string) noneEvals JS from the host environment. This is only available in a web WASM build of Cyber.
fetchUrl(url string) rawstringFetches the contents at url using the HTTP GET request method.
getInput() rawstringReads stdin until a new line is reached. This is intended to read user input from the command line. For bulk reads from stdin, use os.stdin.
int(val any) intConverts a value to an 32-bit integer.
List(val any) ListCasts value to a List. Panics if value is not a List.
Map(val any) MapCasts value to a Map. Panics if value is not a Map.
must(val any) any | noreturnIf val is an error, panic(val) is invoked. Otherwise, val is returned.
number(val any) numberCasts or converts the value to a number. Panics if type conversion fails.
panic(e taglit) noreturnStop execution in the current fiber and starts unwinding the call stack. See Unexpected Errors.
parseCyon(cyon string) anyParses a CYON string into a value.
pointer(val any) pointerConverts a number to a pointer value, or casts to a pointer. This is usually used with FFI.
print(s string) nonePrints a value as a string to stdout. The new line is also printed.
prints(s string) nonePrints a value as a string to stdout.
rawstring(str string) rawstringConverts a string to a rawstring.
readAll() rawstringReads stdin to the EOF as a rawstring.
readFile(path string) rawstringReads the file contents into a rawstring value.
string(val any) stringConverts a value to a string.
taglit(val any) taglitCasts value to a taglit. Panics if value is not a taglit.
toCyon(val any) stringEncodes a value to CYON string.
typeid(val any) numberReturns the type id of the value.
valtag(any) #taglitReturns the value’s type as a tag literal.
writeFile(path string, contents string) noneWrites a string value to a file.

Math Module. #

The math module contains commonly used math constants and functions.

Sample usage:

import m 'math'

r = 10
print(m.pi * r^2)
VariableTypeSummary
enumberEuler’s number and the base of natural logarithms; approximately 2.718.
infnumberInfinity.
log10enumberBase-10 logarithm of E; approximately 0.434.
log2enumberBase-2 logarithm of E; approximately 1.443.
ln10numberNatural logarithm of 10; approximately 2.303.
ln2numberNatural logarithm of 2; approximately 0.693.
nannumberNot a number. Note that nan == nan, however, if a nan came from an arithmetic operation, the comparison is undefined (it may be true or false, so it is not reliable).
neginfnumberNegative infinity.
pinumberRatio of a circle’s circumference to its diameter; approximately 3.14159.
sqrt1_2numberSquare root of ½; approximately 0.707.
sqrt2numberSquare root of 2; approximately 1.414.
FunctionSummary
abs(number) numberReturns the absolute value of x.
acos(number) numberReturns the arccosine of x.
acosh(number) numberReturns the hyperbolic arccosine of x.
asin(number) numberReturns the arcsine of x.
asinh(number) numberReturns the hyperbolic arcsine of a number.
atan(number) numberReturns the arctangent of x.
atan2(number, number) numberReturns the arctangent of the quotient of its arguments.
atanh(number) numberReturns the hyperbolic arctangent of x.
cbrt(number) numberReturns the cube root of x.
ceil(number) numberReturns the smallest integer greater than or equal to x.
clz32(number) numberReturns the number of leading zero bits of the 32-bit integer x.
cos(number) numberReturns the cosine of x.
cosh(number) numberReturns the hyperbolic cosine of x.
exp(number) numberReturns e^x, where x is the argument, and e is Euler’s number (2.718…, the base of the natural logarithm).
expm1(number) numberReturns subtracting 1 from exp(x).
floor(number) numberReturns the largest integer less than or equal to x.
hypot(number, number) numberReturns the square root of the sum of squares of its arguments.
isNaN(number) boolReturns whether x is not a number.
ln(number) numberReturns the natural logarithm (㏒e; also, ㏑) of x.
log(number, number) numberReturns the logarithm of y with base x.
log10(number) numberReturns the base-10 logarithm of x.
log1p(number) numberReturns the natural logarithm (㏒e; also ㏑) of 1 + x for the number x.
log2(number) numberReturns the base-2 logarithm of x.
max(number, number) numberReturns the largest of two numbers.
min(number, number) numberReturns the smallest of two numbers.
mul32(number, number) numberReturns the result of the 32-bit integer multiplication of x and y. Integer overflow is allowed.
pow(number, number) numberReturns base x to the exponent power y (that is, x^y).
random() numberReturns a pseudo-random number between 0 and 1.
round(number) numberReturns the value of the number x rounded to the nearest integer.
sign(number) numberReturns the sign of the x, indicating whether x is positive, negative, or zero.
sin(number) numberReturns the sine of x.
sinh(number) numberReturns the hyperbolic sine of x.
sqrt(number) numberReturns the positive square root of x.
tan(number) numberReturns the tangent of x.
tanh(number) numberReturns the hyperbolic tangent of x.
trunc(number) numberReturns the integer portion of x, removing any fractional digits.

Os Module. #

Cyber’s os module contains system level functions. It’s still undecided as to how much should be included here so it’s incomplete. You can still access os and libc functions yourself using Cyber’s FFI or embedding API.

Sample usage:

import os 'os'

map = os.getEnvAll()
for map each k, v:
    print '{k} -> {v}'
VariableTypeSummary
cpustringThe current cpu arch’s tag name.
endian#little, #bigThe current arch’s endianness.
stderrFileStandard error file descriptor.
stdinFileStandard input file descriptor.
stdoutFileStandard output file descriptor.
systemstringThe current operating system’s tag name.
vecBitSizenumberDefault SIMD vector bit size.
FunctionSummary
access(path any, mode (#read | #write | #readWrite)) true | errorAttempts to access a file at the given path with the #read, #write, or #readWrite mode. Return true or an error.
args() List<rawstring>Returns the command line arguments as a list of rawstrings.
bindLib(path any, decls [](CFunc|CStruct)) Object | MapCalls bindLib(path, decls, {}).
bindLib(path any, decls [](CFunc|CStruct), config: BindLibConfig) Object | MapCreates an FFI binding to a dynamic library and it’s symbols. By default, an anonymous object is returned with the C-functions binded as the object’s methods. If config contains genMap: true, a Map is returned instead with C-functions binded as function values.
copyFile(srcPath any, dstPath any) none | errorCopies a file to a destination path.
createDir(path any) true | errorCreates the directory at path. Returns true if successful.
createFile(path any, truncate boolean) File | errorCreates and opens the file at path. If truncate is true, an existing file will be truncated.
cwd() stringReturns the current working directory.
dirName(path any) string | noneReturns the given path with its last component removed.
exePath() stringReturns the current executable’s path.
free(ptr pointer) noneFrees the memory located at ptr.
getEnv(key any) string | noneReturns an environment value by key.
getEnvAll() MapReturns all environment entries as a Map.
malloc(size number) pointerAllocates size bytes of memory and returns a pointer.
milliTime() numberReturn the calendar timestamp, in milliseconds, relative to UTC 1970-01-01.
openDir(path any) Dir | errorInvokes openDir(path, false).
openDir(path any, iterable boolean) Dir | errorOpens a directory at the given path. iterable indicates that the directory’s entries can be iterated.
openFile(path any, mode (#read | #write | #readWrite)) File | errorOpens a file at the given path with the #read, #write, or #readWrite mode.
realPath(path any) string | errorReturns the absolute path of the given path.
removeDir(path any) true | errorRemoves an empty directory at path. Returns true if successful.
removeFile(path any) true | errorRemoves the file at path. Returns true if successful.
setEnv(key any, value any) noneSets an environment value by key.
sleep(ms number) nonePauses the current thread for given milliseconds.
unsetEnv(key any) noneRemoves an environment value by key.

type File #

MethodSummary
close() noneCloses the file handle. File ops invoked afterwards will return error(#Closed).
read(n number) rawstringReads at most n bytes as a rawstring. n must be at least 1. A result with length 0 indicates the end of file was reached.
readToEnd() rawstringReads to the end of the file and returns the content as a rawstring.
seek(pos number) noneSeeks the read/write position to pos bytes from the start. Negative pos is invalid.
seekFromCur(pos number) noneSeeks the read/write position by pos bytes from the current position.
seekFromEnd(pos number) noneSeeks the read/write position by pos bytes from the end. Positive pos is invalid.
stat() MapReturns info about the file as a Map.
streamLines() Iterable<rawstring>Equivalent to streamLines(4096).
streamLines(bufSize number) Iterable<rawstring>Returns an iterable that streams lines ending in \n, \r, \r\n, or the EOF. The lines returned include the new line character(s). A buffer size of bufSize bytes is allocated for reading. If \r is found at the end of the read buffer, the line is returned instead of waiting to see if the next read has a connecting \n.
write(data (string | rawstring)) numberWrites a string or rawstring at the current file position. The number of bytes written is returned.

type Dir #

MethodSummary
iterator() Iterator<DirEntry> | errorReturns a new iterator over the directory entries. If this directory was not opened with the iterable flag, error(#NotAllowed) is returned instead.
stat() MapReturns info about the file as a Map.
walk() Iterator<DirWalkEntry> | errorReturns a new iterator over the directory recursive entries. If this directory was not opened with the iterable flag, error(#NotAllowed) is returned instead.

map DirEntry #

EntrySummary
'name' -> rawstringThe name of the file or directory.
'type' -> #file | #dir | #unknownThe type of the entry.

map DirWalkEntry #

EntrySummary
'name' -> rawstringThe name of the file or directory.
'path' -> rawstringThe path of the file or directory relative to the walker’s root directory.
'type' -> #file | #dir | #unknownThe type of the entry.

Test Module. #

The test module contains utilities for testing.

Sample usage:

import t 'test'

a = 123 + 321
try t.eq(a, 444)
FunctionSummary
eq(a any, b any) true | errorReturns whether two values are equal. Returns error(#AssertError) if types do not match up.
eqList(a any, b any) true | errorReturns true if two lists have the same size and the elements are equal as if eq was called on those corresponding elements.
eqNear(a any, b any) true | errorReturns two numbers are near each other within epsilon 1e-5.