29 KiB
Cell Language
Cell is a JavaScript variant used in cell. While very similar to JavaScript, it has several important differences that make it more suitable for actor-based programming.
Variables are delcared with 'var'. Var behaves like let. Constants are declared with 'def'. != and == are strict, there is no !== or ===. There is no undefined, only null. There are no classes, only objects and prototypes. There are no arraybuffers. There are no automatic conversions for types. No proxy. No JS modules. No bigint. No reflect. No weakmap, weakset, weakref. No with. No Number, Date, Array, Math, Function No setters or getters or any other property descriptor things No eval. No new keyword. No instanceof.
The point of cell is to merge the prototype system and actor systems, by giving ergonomic ways to go from prototypical intherited objects to pure data records suitable for sending over the wire.
length(value) Length. Find the length of an array in elements, a blob in bits, or a text in codepoints. For functions, it is the arity (or number of inputs).
If the value is a record containing a length field
If the length field contains a function, then length(my_record) has the same effect as my_record.length().
If the length field contains a number, return the number.
All other values produce null.
statements
throw Throw an error. If an actor has an uncaught error, it crashes.
Native constants and functions
false true null
use(text) Use a module. Returns the module. Modules are a script which return a single value. The value is cached, and the module is only reloaded when the file changes. The value is stone, so it cannot be modified.
The returned value is actually a cell runtime owned object, which may be modified for hot reloading purposes.
stone(value) Petrify the value, turning it into stone. Its contents are preserved, but it can no longer be modified by the assign statement or the blob.write functions. This is usually performed on arrays, records, and blobs. All other types are already stone. Attempting to turn a value that is stone to stone will have no effect.
The stone operation is deep. Any mutable objects in the value will also be turned to stone.
This can not be reversed. Immutable objects can never become mutable. A mutable copy can be made of an immutable object, but the original object remains immutable.
The stone function returns the value.
isa(object, master_object) Return true if master is in the value's prototype chain.
isa(object, function) isa(value, function) Return true if function.proto is in the value's prototype chain.
isa(1, stone) true isa(1, number) true isa("1", stone) true isa("1", text) true isa("1", number) false isa($me, actor) true isa($me, object) false isa($me, stone) true
isa(object, array) Return true if the object has keys for each value in the array.
reverse(array|blob) The reverse function makes a new array or blob with the elements or bits in the opposite order.
It returns a new, reversed array or blob.
fn The function object; not a function.
fn.apply(function, array) Apply. Execute the function and return its return value. Pass the elements of the array as input values. See proxy.
If the first input value is not a function, apply returns its first input value.
If length(array) is greater than length(function), it disrupts.
If the second argument is not an array, it is used as a single input value.
log
log(name, options) Establish a logging channel.
log.channel(*text) Write to a channel. There are a few already defined:
log.console log.error
text
text(array, separator) Convert an array to text. All are concatenated to create a single text, separated by the separator. The default separator is a space.
text(number, radix) Convert a number to text. The radix is 2 through 37.The default radix is 10.
text(text) Return the text.
text(text, from, to) Return the text from the from index to the to index.
text.lower(text) The lower function returns a text in which all uppercase characters are converted to lowercase.
text.normalize(text) Unicode normalize. Return a text whose textual value is the same as text, but whose binary representation is in the specified Unicode normalization form. The two texts will display the same, but might not be equal.
text.extract(text, pattern, from, to) The text is matched to the pattern. If it does not match, the result is null. If the pattern does match, then the result is a record containing the saved fields.
text.replace(text, target, replacement, limit) Return a new text in which the target is replaced by the replacement.
text: the source text.
target: a text or pattern that should be replaced in the source.
replacement: text to replace the matched text, or a function that takes the matched text and the starting position, and returns the replacement text or null if it should be left alone.
limit: The maximum number of replacements. The default is all possible replacements. The limit includes null matches.
text.format(text, collection, transformer) The format function makes a new text with substitutions in an original text. A collection is either an array of texts or a record of texts.
A search is made for {left brace and }right brace in the text. If they are found, the middle text between them is examined. If the collection is an array, the middle text is used as a number, and then the matched {left brace and middle and }right brace are replaced with the text at that subscript in the array. If the collection is a record, and if the middle text is the key of a member of the collection with a text value, then the value of the member is used in the substitution. Unmatched text is not altered.
The text between {left brace and }right brace is broken on the :colon character. The left text will be used as a number or name to select a value from the collection. (The value need not be a text.)
If a transformer input is a function, then it is called with the collection[left text] and right text as inputs. If it returns a text, then the substitution is made.
If a transformer input is a record, then the right text is used to select a function from the transformer. That function is passed the value from the collection. If the return value is a text, that text will substitute. If there is no colon, then the empty text is used to select the function from the transformer. If the transformer does not produce a function, or if the function does not return a text, then no replacement occurs. If transformer[right text](collection[left text]) produces a text, then the substitution is made.
If the substitution is not made, and if collection[left text] is a number, then the right text is used as a format input in calling collection[left text].text(right text). If it returns a text, then the substitution is made.
text.codepoint(text) The codepoint function returns the codepoint number of the first character of the text. If the input value is not a text, or if it is the empty text, then it returns null.
text.search(text, target, from) Search the text for the target. If the target is found, return the character position of the left-most part of the match. If the search fails, return null.
text: the source text.
target: a text or pattern that should be found in the source.
from: The starting position for the search. The default is 0, the beginning of the text. If from is negative, it is added to length(text).
text.trim(text, reject) The trim function removes selected characters from the ends of a text. The default is to remove control characters and spaces.
text.upper(text) The upper function returns a text in which all lowercase characters are converted to uppercase.
logical
logical(value) Convert a value to a logical (boolean). If value is 0, false, "false", or null, return false. If value is 1, true, or "true", return true. Otherwise, return null.
number
number(logical) Result is 1 or 0.
number(number) Return the number.
number(text, radix) Convert a text to a number. The radix is 2 through 37. The default radix is 10.
number(text, format) The number function converts a text into a number.
If it is unable to (possibly because of a formatting error), it returns null. The format character determines how the text is interpreted. If the format is not one of those listed, then null is returned.
format radix separator decimal point "" 10 .period "n" "u" _underbar "d" ,comma "s" space "v" .period ,comma "l" dependent on locale "i" _underbar "b" 2 "o" 8 "h" 16 "t" 32 "j" 0x- base 16 0o- base 8 0b- base 2 otherwise base 10
number.whole(number) Return the whole part of a number. 4.9 => 4 4.2 => 4
number.fraction(number) Return the fractional part of a number
number.floor(number, place) If place is 0 or null, the number is rounded down to the greatest integer that is less than or equal to the number. If place is a small positive integer, then the number is rounded down to that many decimal places. For positive numbers, this is like discarding decimal places.
number.ceiling(number, place) If place is 0 or null, the number is rounded up to the smallest integer that is greater than or equal to the number. If place is a small positive integer, then the number is rounded up to that decimal place.
number.abs(number) Absolute value. Return the positive form of the number. If the input value is not a number, the result is null.
number.round(number, place) If place is 0 or null, the number is rounded to the nearest integer. If place is a small integer, then the number is rounded to that many decimal places.
number.sign(number) The sign function returns -1 if the number is negative, 0 if the number is exactly 0, 1 if the number is positive, and null if it is not a number.
number.trunc(number, place) The number is truncated toward zero. If the number is positive, the result is the same as floor(place). If the number is negative, the result is the same as ceiling(place).
If place is a small integer, then the number is rounded down to that many decimal places. This is like discarding decimal places.
number.min(...vals) Returns the smallest of all vals.
number.max(...vals) Returns the largest of all vals.
number.remainder(dividend, divisor) Remainder. For fit integers, the remainder is dividend - ((dividend // divisor) * divisor).
array
array(number) Create an array of the specified size. All elements are null.
array(number, initial_value) Make an array. All of the elements are initialized to initial_value.
number is a non-negative integer, the intended length of the new array.
If initial_value is a function, then the function is called for each element to produce initialization values. If the function has an arity of 1 or more, it is passed the element number.
array(array) Copy.
array(array, function, reverse, exit) Map. Call the function with each element of the array, collecting the return values in a new array. The function is passed each element and its element number.
function (element, element_nr) If reverse is true, then it starts with the last element and works backwards.
If exit is not null, then when the function returns the exit value, then the array function returns early. The exit value will not be stored into the new array. If the array was processed normally, then the returned array will be shorter than the input array. If the array was processed in reverse, then the returned array will have the same length as the input array, and the first elements will be null. The elements in the new array that were not set due to an early exit will be set to null.
array(array, another_array) Concat. Produce a new array that concatenates the array and another_array.
array(array, from, to) Slice. Make a mutable copy of all or part of an array.
array: the array to copy from: the position at which to start copying. Default: 0, the beginning. If negative, add length(array).
to: the position at which to stop copying. Default: length(array), the end. If negative, add length(array).
If, after adjustment, from and to are not valid integers in the proper range, then it returns null. from must be positive and less than or equal to to. to must be less than or equal to length(array).
array(object) Keys. Make an array containing all of the text keys in the object. The keys are not guaranteed to be in any particular order.
array(text) Split the text into grapheme clusters. A grapheme cluster is a Unicode codepoint and its contributing combining characters, if any.
array(text, separator) Split the text into an array of subtexts. The separator can be a text or pattern.
array(text, length) Dice the text into an array of subtexts of a given length.
array.reduce(array, function, initial, reverse) Reduce. The reduce function takes a function that takes two input values and returns a value.
function (first, second) { return ... } The function is called for each element of the array, passing the result of the previous iteration to the next iteration.
The initial value is optional. If present, the function is called for every element of the array.
If initial is null:
If length(array) is 0, then it returns null. If length(array) is 1, then it returns array[0]. If length(array) is 2, it returns function(array[0], array[1]). If length(array) is 3, it returns function(function(array[0], array[1]), array[2]). And so on. If initial is not null:
If length(array) is 0, then it returns initial. If length(array) is 1, then it returns function(initial, array[0]). If length(array) is 2, it returns function(function(initial, array[0]), array[1]). If length(array) is 3, it returns function(function(function(initial, array[0]), array[1]), array[2]). And so on. If reverse is true, then the work begins at the end of the array and works backward.
array.for(array, function, reverse, exit) For each. Call the function with each element of the array. The function is passed each element and its element number.
(element, element_nr) If reverse is true, then it starts with the last element and works backwards.
If exit is not null, then when the function returns the exit value, then the for function returns early. The exit value is usually true or false, but it may be anything. If exit is null, then every element is processed.
The for function returns null unless it did an early exit, when it returns the exit value.
array.find(array, function, reverse, from) Call the function for each element of the array, passing each element and its element number.
(element, element_nr) If the function returns true, then find returns the element number of the current element.
If the second input value is not a function, then it is compared exactly to the elements.
If the reverse input value is true, then search begins at the end of the array and works backward.
The from input value gives the element number to search first. The default is 0 unless reverse is true, when the default is length(array) - 1.
find returns the element number of the found value. If nothing is found, find returns null.
array.filter(array, function) The filter function calls a function for every element in the array, passing each element and its element number.
(element, element_nr) When the function's return value is true, then the element is copied into a new array. If the function's return value is false, then the element is not copied into the new array. If the return value is not a logical, then the filter returns null.
It returns a new array. The length of the new array is between 0 thru length(array). It returns null if the function input is not a function.
array.sort(array, select) The sort function produces a new array in which the values are sorted. Sort keys must be either all numbers or all texts. Any other type of key or any error in the key calculation will cause the sort to fail, returning null. The sort is ascending. The sort is stable, so the relative order of equal keys is preserved.
The optional select input determines how the sort key for each element is selected.
select type Sort key for array[index] Description null array[index] The sort key is the element itself. This is useful for sorting simple arrays of numbers or texts. text array[index][select] The sort key is the select field of each record element. This is useful for sorting arrays of records. number array[index][select] The sort key is the select element of each array element. This is useful for sorting arrays of arrays. array select[index] select is an array of the same length containing the sort keys. It returns a new, sorted array.
object
object(object) Shallow mutable copy. Text keys
splat(object) Create a new object with the same fields as the object, compressed down its prototype chain, for all keys.
The only types in a splat will be objects, arrays, numbers, boolean, and text.
When sending an object with $send, it is automatically splat'd.
meme(record, record) create a new record with the first as its prototype, and add the second's fields. prototypes cannot be changed.
proto(object) Return the object's prototype.
object(object, another_object) Combine. Make a copy of a object, and then put all the fields of another_object into the copy.
object(object, array_of_keys) Select. Make a new object containing only the fields that are named by the array_of_keys.
object(array_of_keys) Set. Make a object using the array as the source of the keys. Each field value is true.
object(array_of_keys, value) Value Set. Make a object using the array as the source of the keys. Each field value is value.
object(array_of_keys, function) Functional Value Set. Make a object using the array as the source of the keys. The function is called for each key, yielding the field values.
parallelism
Callbacks A callback function is a function that is used to deliver functional results from the future. A callback function has this signature:
function (value, reason) The value is the value of the operation if it was successful. The value is null if it is unsuccessful.
If the value is null, then the optional reason may include an error message or indication of the cause of the unsuccess.
Requestor functions take a callback.
Requestors A requestor function encapsulates a unit of work, communicating the result thru a callback, allowing work to progress over many turns. A requestor function has this signature:
function requestor(callback, value) When the requestor function is finished, it calls the callback function with the result.
The optional value is some value that is used to determine the result.
A common usage is to send a message to some actor. When the reply eventually arrives, extract a result from the reply and pass it to the callback.
A requestor function can optionally return a cancel function.
Cancels A requestor function may optionally return a cancel function. When the cancel function is called, it attempts to stop the work of the requestor. A cancel function try to send a message to some actor informing it that the result is no longer needed. The purpose of cancel is to stop work that is no longer required. It is advisory. It is not an undo. It is not guaranteed, particularly in the case where cancel is called after some actor has completed its work.
Cancel is most effective with the requestor factories that are organizing the work.
A cancel function has this signature:
function cancel(reason, abandon | true) The reason is optional, but if included might be logged or propagated. If abandon is true, then simply stop the requested work. If abandon is false, then if possible, complete the assignment, perhaps by calling the callback with the reason.
parallel(requestor_array, throttle, need) Parallel. The parallel requestor factory returns a resquestor function. When the requestor function is called with a callback function and a value, every requestor in the requestor_array is called with the value, and the results are placed in corresponding elements of the results array. This all happens in parallel. The value produced by the first element of the requestor_array provides the first element of the result. The completed results array is passed to the callback function.
By default, it starts all of the requestors in the requestor_array at once, each in its own turn so that they do not interfere with each other. This can shock some systems by unleashing a lot of demand all at once. To mitigate the shock, the optional throttle argument sets the maximum number of requestors running at a time. As requestors succeed or fail, waiting requestors can be started. The throttle is optional. If provided, the throttle is a number: the maximum number of requestors to have running at any time.
Ordinarily, the number of successes must be the same as the number of requestors in the requestor_array. If you need few successes, specify your need with the need argument. The need could be 1, meaning that 1 or more successes are needed. The need could be 0, meaning that no successes are needed. If the number of successes is greater than or equal to need, then the whole operation succeeds. The need must be between 0 and requestor_array.length.
The requestor function itself returns a cancel function that cancels all of the pending requestors from the requestor_array.
race(requestor_array, throttle, need) Race. The race function is a requestor factory that takes an array of requestor functions and returns a requestor function that starts all of the requestors in the requestor_array at once.
By default, it starts all of the requestors in the requestor_array at once, each in its own turn so that they do not interfere with each other. This can shock some systems by unleashing a lot of demand at once. To mitigate the shock, the optional throttle argument sets the maximum number of requestors running at a time. As requestors succeed or fail, waiting requestors can be started.
By default, a single result is produced. If an array of results is need, specify the needed number of results in the need parameter. When the needed number of successful results is obtained, the operation ends. The results go into a sparce array aligned with the requestor_array, and unfinished requestors are cancelled. The need argument must be between 1 and requestor_array.length.
The returned requestor function returns a cancel function that cancels all of the pending requestors from the requestor_array.
sequence(requestor_array) Sequence. The sequence requestor factory that takes a requestor_array and returns a requestor function that starts all of the requestors in the requestor_array one at a time. The result of each becomes the input to the next. The last result is the result of the sequence.
sequence returns a requestor that returns a cancel function and processes each requestor in requestor_array one at a time. Each of those requestors is passed the result of the previous requestor as its value argument. If all succeed, then the sequence succeeds, giving the result of the last of the requestors. If any fail, then the sequence fails.The sequence succeeds if every requestor in the requestor_array succeeds
fallback(requestor_array) The fallback requestor factory returns a requestor function that tries each of the requestors in the requstor_array until it gets a success. When the requestor is called, it calls the first requestor in requestor_array. If that is eventually successful, its value is passed to the callback. But if that requestor fails, the next requestor is called, and so on. If none of the requestors is successful, then the fallback fails. If any one succeeds, then the fallback succeeds.
The fallback requestor returns a cancel function that can be called when the result is no longer needed.
Standard library
time
use('time')
constants time.second : 1 The number of seconds in a second.
time.minute : 60 The number of seconds in a minute.
time.hour : 3_600 The number of seconds in an hour of 60 minutes.
time.day : 86_400 The number of seconds in a day of 24 hours.
time.week : 604_800 The number of seconds in a week of 7 days.
time.month : 2_629_746 The number of seconds in a Gregorian month of 30.436875 days.
time.year : 31_556_952 The number of seconds in a Gregorian year of 365.2425 days
time has three functions: time.number(), time.record(), time.text().
time.number() returns the time now as a number of seconds since the epoch. time.record() returns the time now as a record, with year, month, day, hour, minute, second, and nanosecond. time.text(format) returns the time now as a text, using the format string. The standard format string is "yyyy-MM-dd HH:mm:ss.SSS".
Pass a time into a function to convert it.
It's easy to say "tomorrow": time.number() + time.day = this time tomorrow. As a string: time.text(time.number() + time.day).
time.number(text, format, zone) time.number(record) returns the time as a number of seconds since the epoch.
time.text(number, format, zone) time.text(record, format, zone) returns the time as a text, using the format string. The standard format string is "yyyy-MM-dd HH:mm:ss.SSS".
time.record(number) time.record(text, format, zone)
math
There are three math variants: use('math/radians'), use('math/degrees'), use('math/cycles'). Each has the same functions, but with different representation of angles.
arc_cosine(number) arc_sine(number) arc_tangent(number, denominator) Compute the arc tangent of a If the optional denominator is supplied, then the value is obtained from number / denominator, using the signs of both to determine the quadrant. The denominator is allowed to be 0. The result is the inverse tangent, in radians, between neg(π) and π.
e(power = 1) ln(number) Natural log
log(number) Base 10 log
log2(number) Base 2 log
power(first, second)
root(radicand, number)
sine(number)
sqrt(number)
tangent(number)
blob
use('blob')
A blob is a binary large object, a linear container of bits. Blobs can be used to encode data, messages, sounds, images, public keys, network addresses, and encrypted payloads.
A blob can be in one of two states, either antestone or stone. In the mutable antestone state, the write functions may be used to append bits to the blob. In the immutable stone state, bits can be harvested from the blob. Bits can be written to blobs as fixed size bit fields, that is a sequence of bits with a specified length, or as a kim.
blob.make() Make a new empty blob.
blob.make(capacity) Make a new empty blob with an initial capacity in bits. When turned to stone, the excess bits are discarded. If the initial capacity is too small, the write functions will extended it. A good initial guess can improve performance.
blob.make(length, logical) Make a new blob containing all zeros (false) or all ones (true).
blob.make(length, random) Make a new blob of a given length whose content is random. The random input is a random generator function that returns fit numbers, like random.random_fit().
blob.make(blob, from, to) Make a copy of all or part of a blob. The default of from is 0. The default of to is the length(blob).
blob.write_bit(blob, logical) Append a bit to the end of the blob. The logical value can be true, false, 1, or 0. Any other value will throw.
blob.write_blob(blob, second_blob) Append second_blob to the end of blob.
blob.write_dec64(blob, number) Append a 64 bit DEC64 encoded number to a stone blob.
blob.write_fit(blob, fit, length) Append a bit field to the blob. If the fit requires more bits than allowed by length, it throws.
blob.write_kim(blob, fit) Append a fit number or a single character as a kim value.
blob.write_pad(blob, block_size) Append a 1 bit to the blob followed by enough 0 bits to round up the blob's length to a multiple of the block_size.
blob.write_text(blob, text) Append a text. This will be encoded as a kim encoded length followed by a sequence of kim encoded UTF-32 characters.
blob.read_blob(blob, from, to) Make a copy of all or part of a blob. The default of from is 0. The default of to is the length(blob).
blob.read_dec64(blob, from) Retrieve a 64 bit DEC64 encoded number from a stone blob.
blob.read_fit(blob, from, length) Retrieve a fit number from a bit field from a stone blob.
blob.read_kim(blob, from) Retrieve a kim encoded fit number from a stone blob.
blob.read_logical(blob, from) Retrieve a bit from the blob. If blob is not a stone blob, or if from is out of range, it returns null.
blob.read_text(blob, from) Retrieve a kim encoded text from a stone blob.
blob.pad?(blob, from, block_size) Return true if the stone blob's length is a multiple of the block_size (in bits), and if the difference between length and from is less than or equal to the block_size, and if the bit at from is 1, and that any remaining bits are 0. See write_pad.
json
use('json')
json.encode(value, space, replacer, whitelist) json.decode(text, reviver)
random
random.random() The random function returns a number between 0 and 1. There is a 50% chance that the result is less than 0.5.
random.random_fit() The random_fit function returns an integer in the range -36028797018963968 thru 36028797018963967 that contains 56 random bits. See fit.
random.random_whole(number) The random_whole function returns a whole number that is greater than or equal to zero and less than the number, which must be less than 36028797018963968.
Actors
A program has may have access to functions which are not standard which have been bestowed on it. These begin with a '$'.
$send(actor, message, callback) $clock(callback) $delay(callback, seconds) $time_limit(requestor, seconds) $contact(callback, record) $couple(actor) $portal(callback, port) $receiver(callback) $start(callback, program) $stop(actor) $unneeded(function, seconds)
$me The actor object of the running program.