# -*- mode: org -*- Janet Memo Features: - lispy syntax, but with arrays & hash tables (instead of CONS cells) - small (< 1MB) one-file executable (compiled from a single .c + .h pair) - reasonably fast, good for embedding (great FFI) - nice built-in features (e.g. PEG parser) - tooling with jpm (actually a janet script) > (doc) # list of commands > (doc X) # info about X * Syntax - Lisp-like symbols / sexps - case-sensitive - comment starts with # - literals: nil, true, false - keywords start with : - numbers allow radixes (e.g. 16r2f / 0x2f) and separation (1_000_000) - strings ignore newlines (e.g. "some string") - long strings start/end with the same number of backquotes (e.g. ```some ` string ``.```) - long strings are verbatim - mutable versions ("buffers") start with @, so @"string", @`long string` - bracket-tuples evaluate the elements, so [1 a 2] is (1 42 2) when a's value is 42 => so like `(,1 ,a ,2) in CL - mutable versions ("arrays") start with @, so @(:one 2 "three") => there is no real difference between @(...) and @[...] => semantically parentheses () indicate a function call, brackets [] indicate data - "structs" are key-value lists: {:one 1 :two 2 "three" 3} - mutable version ("tables") starts with @, so @{:one 1 :two 2 "three" 3} |--------------------+-----------------------------------------------------------------------| | Notation | Meaning | |--------------------+-----------------------------------------------------------------------| | # | comment | | nil / true / false | literals (self-evaluating symbols) | | :... | keyword | | "..." | string (no newlines, backslash escapes) | | ``...`` | long string (verbatim) | | @"..." / @``...`` | buffer (mutable string) | | (...) | tuple (function call) | | [...] | tuple (list with evaluated elements) | | @(...) @[...] | array (mutable tuple) | | {... ...} | struct (key1 value1 key2 value2 ...) | | @{... ...} | table (mutable struct) | | '(...) | quoted tuple, short for (quote ...) | | ~(... ,x ...) | quasiquote with unquoting, short for (quasiquote ... (unquote x) ...) | | ;... | splicing, short for (splice ...) | | I(... $) | anonymous function, short for (short-fn (... $)) | | | $ / $0: first arg, $N: Nth arg, $&: list of all args | |--------------------+-----------------------------------------------------------------------| (Note: in the last line it should be | instead of I) * Special forms - (def name meta... value): sets name to be value (non-mutable); can destructure arguments - (var name meta... value): same, but mutable with (set name value) - (fn name? args body...): function with optional name, args is [arg1 arg2 ...] - when args ends with &, additional parameters are disregarded - when args is [arg1 arg2 ... & rest], additional parameters are passed in rest - (do body...): sequential execution, results in the last value - (quote ...): returns the quoted expression - (if condition when-true when-false?): false when condition is false or nil - when-false? defaults to nil - (splice x): inserts a list into its parent, e.g. (+ ;(range 10)) - can be used along with unquote, e.g. ~(1 ,;[2 3]) - (while condition body...): until the condition is false or nil - (break value?): break out from a while loop or a function - while loops always return nil - mainly for macro use - (set lvalue rvalue): sets lvalue to a new value given by rvalue - (quasiquote x), (unquote x): as in CL - (upscope & body): like do, but without a new lexical scope * Built-in macros - (let [var1 val1 var2 val2 ...] body...): new scope with a series of defs - (defn name docstring? args body...) - optional arguments come after &opt (and before &) - e.g. [arg1 arg2 &opt opt1 opt2 & rest] - not given optional values default to nil - unless set by (default opt1 val) in the body - keyword arguments come in a struct after &keys - e.g. [arg1 arg2 &keys {:key1 var1 :key2 var2}] - keyword argument can act as character sets (for flags, such as in file/open) - named arguments come after &named, e.g. [arg1 arg2 &named named1 named2] => called as (foo val1 val2 :named2 val3 :named1 val4) - (loop head body...) - head: a sequence of bindings or conditionals [binding :verb object/expression] - verbs include :iterate, :range, :range-to, :down, :down-to, :keys, :pairs, :in - can inclue modifiers: :while, :until, :let, :before, :after, :repeat, :when, :unless - (defmacro name body...): body should return a tuple representing code - not hygienic, use (gensym) to generate new symbols * Data structures - tables and arrays act as functions on their keys/indices - (get data key default-value?) - (in data key default-value?) : throws errors for unknown keys (except for tables/structs) - (put data key value) - (set place value) : like CL's setf, e.g. (set (my-table :a) 47) * Dynamic-scope variables - like CL's special variables and Scheme's make-parameter/parameterize - (setdyn var val): sets the value - (dyn var): queries the current value - (with-dyns bindings body...): execute body with temporary bindings in effect * Modules - (import path): imports symbols as path/XXX - (import path :prefix "pref"): import symbols as pref/XXX (prefix can be "") - (import path :as pref): import symbols as pref/XXX - path can be ./folder/file (looks for ./folder/file.janet [or .so, .jimage, etc.]) * OOP - prototype-based (like Self or JavaScript), so no separate "classes", just objects - object ~ table with a prototype (set by table/setproto) - structs can also be used (created with struct/with-proto) - member function call: (:memfun-key obj args...), where :memfun-key is associated with (fn [self args...] body...) - new objects are created by factory functions (that call table/setproto under the hood) * Other topics - PEG - Multithreading - Networking - FFI - etc. * Core functions (~ 700) ** Global variables |-------------------+--------------------------------------------| | *args* | command line arguments | | *current-file* | name of current file | | *debug* | debug mode enabled? | | *defdyn-prefix* | optional namespace for dynamic bindings | | *doc-color* | colorize doc-format? | | *doc-width* | width of doc-format | | *err* | error stream | | *err-color* | colorize error messages? | | *executable* | argv[0] | | *exit* | exit from current context when set | | *exit-value* | return value of run-context | | *ffi-context* | current native library | | *lint-error* | lint error level | | *lint-levels* | table of level names -> level numbers | | *lint-warn* | lint warning levels | | *macro-form* | inside a macro bound to the source | | *macro-lints* | array of lint messages inside a macro | | *module-cache* | dynamic var overriding module/cache | | *module-loaders* | dynamic var overriding module/loaders | | *module-loading* | dynamic var overriding module/loading | | *module-make-env* | dynamic var overriding make-env | | *module-paths* | dynamic var overriding module/paths | | *out* | output stream | | *peg-grammar* | base grammar when compiling PEGs | | *pretty-format* | pp function format specifier | | *profilepath* | REPL profiling file path | | *redef* | when set allow dynamic top-level rebinding | | *repl-prompt* | custom REPL prompt | | *syspath* | system module load directory | | *task-id* | concurrency control ID | |-------------------+--------------------------------------------| ** Math |----------------------------------+----------------------------------------------------------------------------| | (+ & xs) | sum | | (++ x) | increment | | (+= x & ns) | set to sum | | (inc x) | x + 1 | | (- & xs) | difference | | (-- x) | decrement | | (-= x & ns) | set to difference | | (dec x) | x - 1 | | (* & xs) | product | | (*= x & ns) | set to product | | (/ & xs) | quotient | | (/= x & ns) | set to quotient | | (div & xs) | floored division | | (% & xs) | remainder | | (%= x & ns) | set to remainder | | (mod & xs) | modulo | | (< & xs) | ascending? | | (<= & xs) | non-descending? | | (= & xs) | all equal? | | (not= & xs) | not all equal? | | (> & xs) | descending? | | (>= & xs) | non-ascending? | | (cmp x y) | returns -1, 0 or 1 | | (compare x y) | returns -1, 0 or 1; uses polymorphic compare method | | (compare< & xs) | like <, but uses polymorphic compare method | | (compare<= & xs) | like <=, but uses polymorphic compare method | | (compare= & xs) | like =, but uses polymorphic compare method | | (compare> & xs) | like >, but uses polymorphic compare method | | (compare>= & xs) | like >=, but uses polymorphic compare method | | (even? x) | is x even? | | (odd? x) | is x odd? | | (zero? x) | x = 0 ? | | (one? x) | x = 1 ? | | (bnot x) | bitwise NOT | | (band & xs) | bitwise AND | | (bor & xs) | bitwise OR | | (bxor & xs) | bitwise XOR | | (blshift x & shifts) | bitwise left shift | | (brshift x & shifts) | bitwise right shift | | (brushift x & shifts) | bitwise unsigned right shift | | (min & args) | minimum value | | (min-of args) | minimum value from a sequence | | (max & args) | maximum value | | (max-of args) | maximum value from a sequence | | (extreme order args) | most extreme value in args based on the order function | | (range & args) | array of values (1 arg: 0..x-1, 2-3 args: x..y-1, with step z [default 1]) | | (sum xs) | compute the sum | | (product xs) | compute the product | | (mean xs) | mean value or NaN if xs is empty | | (geomean xs) | geometric mean | | (int/s64 value) | create a boxed signed 64 bit integer from a string or integer | | (int/u64 value) | create a boxed unsigned 64 bit integer from a string or integer | | (int/to-number value) | convert an int/u64 or int/s64 to a number | | (math/abs x) | absolute value | | (math/ceil x) | ceiling (round up) | | (math/floor x) | floor (round down) | | (math/round x) | round to nearest integer | | (math/trunc x) | truncate (round towards 0) | | (math/sqrt x) | square root | | (math/cbrt x) | cube root | | (math/pow a x) | power function | | (math/log x) | natural logarithm | | (math/log10 x) | base-10 logarithm | | (math/log1p x) | same as (inc (math/log x)), but more accurate | | (math/log2 x) | base-2 logarithm | | (math/exp x) | exponential function | | (math/exp2 x) | powers of 2 | | (math/expm1 x) | same as (dec (math/exp x)) | | (math/acos x) | inverse cosine | | (math/acosh x) | inverse hyperbolic cosine | | (math/asin x) | inverse sine | | (math/asinh x) | inverse hyperbolic sine | | (math/atan x) | inverse tangent | | (math/atan2 y x) | inverse tangent of y/x (pi/2 when x = 0, but 0 for 0/0) | | (math/atanh x) | inverse hyperbolic tangent | | (math/cos x) | cosine | | (math/cosh x) | hyperbolic cosine | | (math/sin x) | sine | | (math/sinh x) | hyperbolic sine | | (math/tan x) | tangent | | (math/tanh x) | hyperbolic tangent | | (math/gcd x y) | greatest common divisor | | (math/lcm x y) | least common multiplier | | (math/erf x) | erf function | | (math/erfc x) | complementary erf function | | (math/frexp x) | tuple of mantissa and exponent | | (math/ldexp m e) | create number from mantissa and exponent | | (math/gamma x) | gamma function | | (math/log-gamma x) | log-gamma function | | (math/hypot a b) | same as (sqrt (+ (* a a) (* b b))) | | (pos? x) | x > 0 ? | | (neg? x) | x < 0 ? | | (nat? x) | is x exactly a non-negative int32? | | (nan? x) | is x not-a-number? | | math/nan | not-a-number | | math/e | base of natural logarithm | | math/pi | pi | | math/inf | positive infinity | | math/-inf | negative infinity | | math/int-max | largest integer in a double (2^53) | | math/int-min | smallest integer in a double (-2^53) | | math/int32-max | largest integer in an int32 (2^31-1) | | math/int32-min | smallest integer in an int32 (-2^31) | | (math/next x y) | next representable value after x in direction of y | | (math/random) | random number between 0 and 1 | | (math/seedrandom seed) | set the random seed | | (math/rng &opt seed) | creates a random generator with optional seed | | (math/rng-buffer rng n &opt buf) | get n random bytes | | (math/rng-int rng &opt max) | get a random integer (default max is 2^31-1) | | (math/rng-uniform rng) | get a random value in [0,1) | |----------------------------------+----------------------------------------------------------------------------| ** Logic |----------------+---------------------------------------------------------| | (not x) | logical inverse | | (toggle value) | set to logical inverse, same as (set value (not value)) | | (false? x) | false? | | (true? x) | true? | | (truthy? x) | truthy? (not false or nil) | | (and & forms) | last value when all truthy; otherwise first falsey | | (or & forms) | last value when all falsey; otherwise first truthy | |----------------+---------------------------------------------------------| ** Control flow |--------------------------------------------------+-------------------------------------------------------------------------------------------| | (let bindings & body) | create a scope and bind values to symbols | | (cond & pairs) | if pairs has odd elements, the last is the default (otherwise nil) | | (case dispatch & pairs) | if pairs has odd elements, the last is the default (otherwise nil) | | (match x & cases) | pattern matching | | (with [binding ctor dtor] & body) | evaluate body with first creating the bindnig to value of ctor, and cleaning up with dtor | | (if-not condition then &opt else) | same as (if (not condition) then else) | | (if-let bindings tru &opt fal) | make multiple bindings, if all true then tru, otherwise fal | | (if-with [binding ctor dtor] truthy &opt falsey) | like with, but returns falsey if binding is false/nil | | (when condition & body) | evaluate body when condition is truthy, otherwise nil | | (when-let bindings & body) | same as (if-let bindings (do ;body)) | | (when-with [binding ctor dtor] & body) | like with, but returns nil if binding is false/nil | | (unless condition & body) | same as (when (not condition) ;body) | | (repeat n & body) | evaluate the body n times | | (loop head & body) | general-purpose loop macro with many options | | (for i start stop & body) | C-style for loop; returns nil | | (forv i start stop & body) | like for, but i can be mutated | | (forever & body) | iterate forever (until break) | | (each x ds & body) | loop over each value of ds, return nil | | (eachk x ds & body) | loop over each key of ds, return nil | | (eachp x ds & body) | loop over each key/value pair of ds, return nil | | (generate head & body) | like loop, but creates a fiber yielding the values | | (seq head & body) | like loop, but accumulates into an array | | (catseq head & body) | like seq, but concatenating the results | | (tabseq head key-body & value-body) | like seq, but accumulates into a table | | (-> x & forms) | threading, always as first arg | | (-?> x & forms) | like ->, but short-circuits at nil | | (->> x & forms) | threading, always as last arg | | (-?>> x & forms) | like ->>, but short-circuits at nil | | (as-> x as & forms) | threading, replacing the value of "as" with the previous value | | (as?-> x as & forms) | like as->, but short-circuits at nil | | (defer form & body) | run form unconditionally after body (cleanup) | | (edefer form & body) | run form only if body terminates abnormally | | (compif cnd tru &opt fals) | compile-time if | | (compwhen cnd & body) | compile-time when | | (label name & body) | set up a lexically scoped label-point (for return etc.) | | (prompt tag & body) | set up a dynamic checkpoint (for return etc.) | | (return to &opt value) | return to a prompt point | |--------------------------------------------------+-------------------------------------------------------------------------------------------| ** Evaluation |-------------------------------------+---------------------------------------------------------| | (apply f & args) | apply f to the arguments, splicing the last argument | | (as-macro f & args) | use f as a macro | | (asm assembly) | create function from assembly code | | (comment &) | ignores the body | | (compile ast &opt env source lints) | compiles an abstract syntax tree | | (comptime x) | compile-time evaluation | | (delay & forms) | lazy & memozied evaluation | | (disasm func &opt field) | disassemble a function | | (eval form &opt env) | evaluates a form in an environment (default: current) | | (eval-string str &opt env) | evaluates a string in an environment (default: current) | |-------------------------------------+---------------------------------------------------------| ** Higher-order functions |-------------------------+---------------------------------------------------------------------------| | (comp & functions) | composes functions | | (complement f) | complement function of the predicate f | | (juxt & funs) | create a function returning an array of the result of each function calls | | (juxt* & funs) | function version of juxt | | (identity x) | identity function | | (partial f & more) | partial function application | | (short-fn arg &opt name | create a function with numbered argument ($=$0, $1 ...; $&) | |-------------------------+---------------------------------------------------------------------------| ** Data types Symbols, arrays, tuples, buffers, strings, tables, structs are all associative data structures (!). Arrays and tuples are indexed. |---------------------------------+----------------------------------------------------------------------| | (deep= x y) | deep comparison of arrays/tables/buffers | | (deep-not= x y) | deep comparison of arrays/tables/buffers | | (distinct xs) | deduplicate values in xs, returns an array | | (take n ind) | take the first n elements | | (take-until pred ind) | take elements while pred is falsey | | (take-while pred ind) | take elements while pred is truthy | | (drop n ind) | drop the first n elements | | (drop-until pred ind) | drop elements while pred is falsey | | (drop-while pred ind) | drop elements while pred is truthy | | (slice x &opt start end) | extract a sub-range | | (empty? xs) | is xs empty? | | (length ds) | length of the data structure | | (lengthable? x) | does x have a length? | | (last xs) | last value | | (reverse t) | reverse the order of elements, return a new array/buffer | | (reverse! t) | like reverse, but in-place | | (filter pred ind) | filter based on a predicate | | (map f ind & inds) | map a function over each values and return an array | | (mapcat f ind & inds) | like map, but array/concat the results | | (keep pred ind & inds) | map and keep truthy; same as (filter identity (map pred ind inds)) | | (prewalk f form) | call f on each value in a pre-order traversal (inner nodes as well) | | (postwalk f form) | call f on each value in a post-order traversal (inner nodes as well) | | (reduce f init ind) | left fold | | (reduce2 f ind) | left fold without initial value (nil if ind is empty) | | (accumulate f init ind) | like reduce, but returns all intermediate values | | (accumulate2 f ind) | like reduce2, but returns all intermediate values | | (all pred ind & inds) | all (pred item) truthy? | | (some pred ind & inds) | first truthy (pred item), otherwise nil | | (any? ind) | first non-falsey element, otherwise the last one | | (every? ind) | first falsey element, otherwise the last one | | (count pred ind & inds) | count the truthy (pred item)s | | (find pred ind &opt dflt) | find the first element for which pred is truthy, or dflt | | (find-index pred ind &opt dflt) | like find, but return the index (or dflt) | | (index-of x ind &opt dflt) | find the key of x, or dflt | | (flatten xs) | first depth traversal of a nested array | | (flatten-into into xs) | like flatten, but puts the result into into | | (frequencies ind) | number of occurrences of each value | | (get ds key &opt dflt) | get the value mapped to key, or dflt | | (get-in ds ks &opt dflt) | like get, but in a nested data structure | | (put ds key value) | set the value mapped to key | | (put-in ds ks v) | like put, but in a nested data structure | | (update ds key func & args) | update the value for a key by calling func on the old value | | (update-in ds ks f & args) | like update, but in a nested data structure | | (group-by f ind) | group elements by f and return a table | | (has-key? ds key) | is key present? | | (has-value? ds value) | is value present? | | (in ds key &opt dflt) | get the value mapped to key, or dflt (error if key not present) | | (interleave & cols) | create an array by interleaving the values in the columns | | (interpose sep ind) | insert sep between each pair of elements in ind | | (partition n ind) | partition into tuples of size n | | (partition-by f ind) | partition by splitting when (f x) changes | | (invert ds) | create a new structure where the keys and values are swapped | | (sort ind &opt before?) | sort in-place | | (sort-by f ind) | sort in-place based on (f element) values | | (sorted ind &opt before?) | like sort, but returns a new sorted array | | (sorted-by f ind) | like sort-by, but returns a new sorted array | | (keys x) | get the keys | | (values x) | get the values | | (pairs x) | get the key-value pairs | | (kvs dict) | array of key/value pairs: @[k1 v1 k2 v2 ...] | | (next ds &opt key) | get the next key (after key, or the first if key is nil) | |---------------------------------+----------------------------------------------------------------------| *** Keywords & Symbols |-------------------------------------+--------------------------------------------------| | (gensym) | returns a fresh symbol | | (with-syms syms & body) | run a block of code where syms are fresh symbols | | (keyword & xs) | create a keyword by concatenating the values | | (keyword/slice bytes &opt start end | like string/slice, but returns a keyword | | (symbol & xs) | create a symbol by concatenating the elements | | (symbol/slice bytes &opt start end) | like string/slice, but returns a symbol | |-------------------------------------+--------------------------------------------------| *** Arrays & Tuples |-------------------------------------+----------------------------------------------------------------------| | (array & items) | create an array with elements | | (array/clear arr) | empties the array | | (array/concat arr & parts) | concatenates parts (can also be elements) to arr | | (array/ensure arr capacity growth) | ensures the capacity/growth of arr | | (array/fill arr &opt value) | replaces all elements with value (default nil) | | (array/insert arr at & xs) | inserts values starting at the given index; negative index backwards | | (array/join arr & parts) | concatenates parts to arr | | (array/new capacity) | create an empty array | | (array/new-filled count &opt value) | create a filled array (default value nil) | | (array/peek arr) | last element | | (array/pop arr) | remove & return last element | | (array/push arr & xs) | push all elements at the end | | (array/remove arr at &opt n) | remove n elements starting at the given index (default n = 1) | | (array/slice arrtup &opt start end) | new array representing [start,end), defaults to the whole | | (array/trim arr) | sets capacity to length | | (array/weak capacity) | like array/new, but with support for weak references | | (tuple & items) | create a tuple with elements | | (tuple/brackets & xs) | create a bracketed tuple with elements | | (tuple/join & parts) | create a tuple by joining parts | | (tuple/setmap tup line column) | set the sourcemap metadata of a tuple | | (tuple/slice arrtup &opt start end) | new tuple representing [start,end), defaults to the whole | | (tuple/sourcemap tup) | get the sourcemap metadata of a tuple | | (tuple/type tup) | get the tuple type (:parens or :brackets) | |-------------------------------------+----------------------------------------------------------------------| *** Buffers & Strings |----------------------------------------------------------+---------------------------------------------------------------------------| | (buffer & xs) | create a buffer by concatenating the arguments | | (buffer/bit buffer index) | get the bit at the given index | | (buffer/bit-clear buffer index) | clears the bit at the given index | | (buffer/bit-set buffer index) | sets the bit at the given index | | (buffer/bit-toggle buffer index) | toggles the bit at the given index | | (buffer/blit dest src &opt dest-start src-start src-end) | copies into a buffer | | (buffer/clear buffer) | clears a buffer (but retains its capacity) | | (buffer/fill buffer &opt byte) | fill a buffer | | (buffer/format buffer format & args) | printf-like formatting into a buffer | | (buffer/from-bytes & byte-vals) | buffer from integers | | (buffer/new capacity) | create an empty buffer | | (buffer/new-filled count &opt byte) | create a filled buffer (default value 0) | | (buffer/popn buffer n) | removes the last n value | | (buffer/push buffer & xs) | push bytes and byte sequences at the end | | (buffer/push-at buffer index & xs) | like buffer/push, but starting at a given index | | (buffer/push-byte buffer & xs) | push bytes at the end | | (buffer/push-float32 buffer order data) | push floats at the end | | (buffer/push-float64 buffer order data) | push doubles at the end | | (buffer/push-string buffer & xs) | push byte-sequences at the end | | (buffer/push-uint16 buffer order data) | push uint16 at the end | | (buffer/push-uint32 buffer order data) | push uint32 at the end | | (buffer/push-uint64 buffer order data) | push uint64 at the end | | (buffer/push-word buffer & xs) | push machine words at the end | | (buffer/slice bytes &opt start end) | new buffer representing [start,end), defaults to the whole | | (buffer/trim buffer) | sets capacity to length | | (string & xs) | create a string by concatenating elements | | (string/ascii-lower str) | a new string with lowercase ASCII (non-unicode) | | (string/ascii-upper str) | a new string with uppercase ASCII (non-unicode) | | (string/bytes str) | a tuple of integers representing the string | | (string/check-set set str) | does str only have bytes that are in set? | | (string/find patt str &opt start-index) | index of the first instance of patt in str | | (string/find-all patt str &opt start-index) | indices of all instances of patt in str | | (string/format format & values) | create a formatted string (similarly to snprintf in C) | | (string/from-bytes & byte-vals) | create a string from bytes | | (string/has-prefix? pfx str) | does str start with pfx? | | (string/has-suffix? sfx str) | does str end with sfx? | | (string/join parts &opt sep) | joins an array of string, optionally separated by sep | | (string/repeat bytes n) | create a string containing n copies of bytes | | (string/replace patt subst str) | a new string with the first occurrence of patt in str replaced with subst | | (string/replace-all patt subst str) | a new string with all occurrences of patt in str replaced with subst | | (string/reverse str) | reverse the string | | (string/slice bytes &opt start end) | a substring of bytes between [start,end) | | (string/split delim str &opt start limit) | split a string with delim | | (string/trim str &opt set) | trim leading/trailing whitespaces (or characters in set) | | (string/triml str &opt set) | like string/trim, but only trim leading characters | | (string/trimr str &opt set) | like string/trim, but only trim trailing characters | | (chr c) | 1-char string -> int | |----------------------------------------------------------+---------------------------------------------------------------------------| *** Tables & Structs |-------------------------------------+-------------------------------------------------------------------------| | (from-pairs ps) | create a table from a sequence of pairs | | (getproto x) | get the prototype of a table/struct | | (merge & colls) | merges multiple tables into one, later values overwriting previous ones | | (merge-into tab & colls) | like merge, but into tab | | (struct & kvs) | create a struct from a key-value sequence | | (struct/getproto st) | get the prototype of a struct | | (struct/proto-flatten st) | convert from a struct with prototypes to one without prototypes | | (struct/rawget st key) | gets a value from a struct without looking at the prototype | | (struct/to-table st &opt recursive) | convert to a table | | (struct/with-proto proto & kvs) | create a proto and set the prototype | | (table & kvs) | create a table from a key-value sequence | | (table/clear tab) | remove all pairs from a table | | (table/clone tab) | create a copy of the table | | (table/getproto x) | get the prototype of a table | | (table/new capacity) | create a table | | (table/proto-flatten tab) | convert from a table with prototypes to one without prototypes | | (table/rawget tab key) | gets a value from a table without looking at the prototype | | (table/setproto tab proto) | set the prototype of a table | | (table/to-struct tab &opt proto) | convert to a struct | | (table/weak capacity) | create an empty table with weak references to keys/values | | (table/weak-keys capacity) | create an empty table with weak references to keys (but normal values) | | (table/weak-values capacity) | create an empty table with weak references to values (but normal keys) | | (zipcoll ks vs) | create a table from two arrays/tuples | |-------------------------------------+-------------------------------------------------------------------------| ** Environment & Modules & Bundles |---------------------------------------------------------------------+-----------------------------------------------------------------| | (def- name & more) | private definition | | (var- name & more) | private variable | | (defn name & more) | define a function | | (varfn name & more) | create a function that can be rebound | | (defn- name & more) | define a private function | | (defmacro name & more) | define a macro | | (defmacro- name & more) | define a private macro | | (varglobal name init) | dynamically create a global variable | | (defdyn alias & more) | define an alias for dynamic binding | | (dyn key &opt default) | get a dynamic binding (or nil if not found) | | (setdyn key value) | set a dynamic binding | | (with-dyns bindings & body) | run a block of code with dynamic bindings | | (with-vars vars & body) | run a block of code with vars temporarily bound | | (defglobal name value) | create a global definition | | (default sym val) | default value for an optional argument | | (with-env env & body) | run a block of code with a given environment table | | (env-lookup env) | forward lookup table from an environment | | (all-bindings &opt env local) | all symbols | | (all-dynamics &opt env local) | all dynamic bindings | | (import path & args) | import a module (macro) | | (import* path & args) | import a module (function) | | (require path & args) | require a module with the given name | | (use & modules) | like import, but symbols have no module prefix | | (merge-module target source &opt prefix export only) | merge a module source into the target environment with a prefix | | (module/add-paths ext loader) | add paths to a given loader | | module/cache | a table of loaded modules and their environments | | (module/expand-path path template) | expand a path template | | (module/find path) | match a module path name | | module/loaders | a table of loading method names | | module/loading | a table mapping currently loaded methods to true | | module/paths | a list of paths to look for modules | | (module/value module sym &opt private) | get the value bound to sym in module | | (bundle/add manifest src &opt dest chmod-mode) | add files/directories during a bundle install | | (bundle/add-bin manifest src &opt dest chmod-mode) | add scripts during a bundle install | | (bundle/add-directory manifest dest &opt chmod-mode) | add directory during a bundle install | | (bundle/add-file manifest src &opt dest chmod-mode) | add files during a bundle install | | (bundle/install path &keys config) | install a bundle from the filesystem | | (bundle/installed? bundle-name) | is the bundle installed? | | (bundle/list) | list of installed bundles | | (bundle/manifest bundle-name) | manifest of an installed bundle | | (bundle/prune) | remove orphaned bundles | | (bundle/reinstall bundle-name &keys new-config) | reinstall a bundle from local source | | (bundle/replace bundle-name path &keys new-config) | like bundle/reinstall, but from any directory | | (bundle/topolist) | topological order of bundles | | (bundle/uninstall bundle-name) | uninstall a bundle | | (bundle/update-all &key configs) | reinstall all bundles | | (bundle/whois path) | which bundle installed a given path? | | (cli-main args) | call the command-line interface | | (make-env &opt parent) | create a new environment | | (curenv &opt n) | current environment table | | (dofile path &named exit env source expander evaluator read parser) | evaluate a file/stream | | (make-image env) | create an image from an environment | | (load-image image) | returns an environment; inverse of make-image | | load-image-dict | table for unmarshaling images | | make-image-dict | table for marshaling images | | (marshal x &opt reverse-lookup buffer no-cycles) | marshal a value into a buffer | | (unmarshal buffer &opt lookup) | unmarshal a value from a buffer | | root-env | the root environment used to create environments | | (run-context opts) | run a context, opt being a table of options | |---------------------------------------------------------------------+-----------------------------------------------------------------| ** Type check |-----------------| | (type x) | | (abstract? x) | | (array? x) | | (boolean? x) | | (buffer? x) | | (bytes? x) | | (cfunction? x) | | (dictionary? x) | | (fiber? x) | | (function? x) | | (indexed? x) | | (int? x) | | (keyword? x) | | (nil? x) | | (number? x) | | (string? x) | | (struct? x) | | (symbol? x) | | (table? x) | | (tuple? x) | |-----------------| ** I/O & Documentation |---------------------------------------------+------------------------------------------------------------| | (describe x) | human-readable output | | (doc &opt sym) | shows documentation (macro) | | (doc* &opt sym) | shows documentation (function) | | (doc-format str &opt width indent colorize) | reformat a docstring | | (doc-of x) | shows documentation (searches by value) | | (pp x) | pretty-print to stdout | | (prin & xs) | print values to the console | | (prinf fmt & xs) | print formatted data to the console, as with string/format | | (print & xs) | like prin, but with a newline | | (printf fmt & xs) | like prinf, but with a newline | | (eprin & xs) | like prin, but to the error stream | | (eprinf fmt & xs) | like prinf, but to the error stream | | (eprint & xs) | like print, but to the error stream | | (eprintf fmt & xs) | like printf, but to the error stream | | (xprin to & xs) | prin to a file explicitly (no dynamic bindings) | | (xprinf to fmt & xs) | print formatted data to a file explicitly | | (xprint to & xs) | like xprin, but with a newline | | (xprintf to fmt & xs) | like xprinf, but with a newline | | (flush) | flush the current output stream | | (eflush) | flush the current error stream | | (getline &opt prompt buf env) | read a line | | (slurp path) | read data from a file | | (spit path contents &opt mode) | write data to a file | | stderr | the standard error file | | stdin | the standard input file | | stdout | the standard output file | | (file/close f) | close a file | | (file/flush f) | flush the buffer of a file | | (file/lines file) | iterator over the lines of a file | | (file/open path &opt mode buffer-size) | open a file in different modes | | (file/read f what &opt buf) | read from the file (what = :all, :line, n [lines]) | | (file/seek f &opt whence n) | jump to a relative location in a file | | (file/tell f) | current position in a file | | (file/temp) | open a temporary file | | (file/write f bytes) | write to file | | (filewatch/add watcher path &opt flags) | add a path to a watcher | | (filewatch/listen watcher) | listen for changes in a watcher | | (filewatch/new channel &opt default-flags) | create a new file watcher | | (filewatch/remove watcher path) | remove a path from a watcher | | (filewatch/unlisten watcher) | stop listening for changes in a watcher | | (int/to-bytes value &opt endianness buffer) | write an integer to a buffer | |---------------------------------------------+------------------------------------------------------------| ** Foreign Function Interface |-------------------------------------------------------------------+------------------------------------------| | (ffi/align type) | align of a type in bytes | | (ffi/call pointer signature & args) | call a row pointer | | (ffi/calling-conventions) | array of supported calling conventions | | (ffi/close native) | free a native object | | (ffi/context &opt native-path &named map-symbols lazy | set path to native dynamic library | | (ffi/defbind name ret-type & body) | generate bindings to native functions | | (ffi/defbind-alias name alias ret-type & body) | like ffi/defbind, but allows aliases | | (ffi/free pointer) | free memory allocated with ffi/malloc | | (ffi/jitfn bytes) | create a type to be called by ffi/call | | (ffi/lookup native symbol-name) | lookup symbol from native object | | (ffi/malloc size) | allocate memory | | (ffi/native &opt path) | loads a shared object | | (ffi/pointer-buffer pointer capacity &opt count offset) | create buffer from pointer | | (ffi/pointer-cfunction pointer &opt name source-file source-line) | create C function from raw pointer | | (ffi/read ffi-type bytes &opt offset) | parse a native struct | | (ffi/signature calling-convention ret-type & arg-types) | create a function signature object | | (ffi/size type) | size of an ffi type in bytes | | (ffi/struct & types) | create a struct type to pass in ffi | | (ffi/trampoline cc) | get native pointer for callback | | (ffi/write ffi-type data &opt buffer index) | append a native type to a buffer | | (native path &opt env) | load a native module from the given path | |-------------------------------------------------------------------+------------------------------------------| ** Multitasking & Fibers |----------------------------------------------+------------------------------------------------------------------| | (cancel fiber err) | resume a fiber and raise an error | | (coro & body) | makes a fiber that may yield multiple values | | (ev/acquire-lock lock) | acquire a (read) lock | | (ev/acquire-rwlock rwlock) | acquire a read/write lock | | (ev/acquire-wlock wlock) | acquire a write lock | | (ev/all-tasks) | a list of all active fibers | | (ev/call f & args) | call a function asynchronously | | (ev/cancel fiber err) | cancel a suspended fiber; return the canceled fiber | | (ev/capacity channel) | number of items a channel stores before blocking writers | | (ev/chan &opt capacity) | create a channel | | (ev/chan-close chan) | close a channel | | (ev/read stream n &opt buffer timeout) | read at most n bytes asynchronously (n can be :all) | | (ev/chunk stream n &opt buffer timeout) | like ev/read, but waits if there are not enough bytes | | (ev/close stream) | closes a stream [same as (:close stream)] | | (ev/count channel) | number of items waiting in a channel | | (ev/deadline sec &opt tocancel tocheck) | after sec seconds try to cancel tocancel if tocheck is resumable | | (ev/full channel) | is the channel full? | | (ev/gather & bodies) | run fiber in parallel, return result in array | | (ev/give channel value) | write value to channel | | (ev/take channel) | read from channel | | (ev/give-supervisor tag & payload) | send message to supervisor channel | | (ev/lock) | create a lock | | (ev/rwlock) | create a read/write lock | | (ev/release-lock lock) | release a lock | | (ev/release-rlock rwlock) | release a read lock on a read/write lock | | (ev/release-wlock rwlock) | release a write lock on a read/write lock | | (ev/select & clauses) | block until the first of several channel operations occur | | (ev/rselect & clauses) | like ev/select, but randomized for fairness | | (ev/sleep sec) | sleep for sec seconds | | (ev/go fiber-or-fun &opt value supervisor) | put a fiber on the event loop to be resumed | | (ev/spawn & body) | run code in a new fiber, same as (ev/go (fn [] ;body)) | | (ev/do-thread & body) | run code in a new thread | | (ev/spawn-thread & body) | like ev/do-thread, but returns immediately | | (ev/thread main &opt value flags supervisor) | run main in a new thread & suspend the current thread | | (ev/with-deadline sec & body) | start body in a new fiber, but kill it after sec seconds | | (ev/thread-chan &opt limit) | create a threaded channel | | (ev/to-file) | create a copy of the stream | | (ev/with-lock lock & body) | run body after acquiring the lock; then release the lock | | (ev/with-rlock lock & body) | same as eval/with-lock, but with read access to an rwlock | | (ev/with-wlock lock & body) | same as eval/with-lock, but with write access to an rwlock | | (ev/write stream data &opt timeout) | write data to stream | | (fiber-fn flags & body) | create a fiber, same as (fiber/new (fn [] ;body) flags) | | (fiber/can-resume? fiber) | can the fiber be resumed? | | (fiber/current) | current fiber | | (fiber/getenv fiber) | environment of a fiber | | (fiber/last-value fiber) | last value returned/signaled by a fiber | | (fiber/maxstack fib) | maximum stack size allowed for a fiber | | (fiber/new func &opt sigmask env) | create fiber with function and signal mask | | (fiber/root) | current root fiber | | (fiber/setenv fiber table) | set the environment table of a fiber | | (fiber/setmaxstack fib maxstack) | set maximum stack size for a fiber | | (fiber/status fib) | status of a fiber | | (resume fiber &opt x) | resume a fiber and optionally pass a value | | (yield &opt x) | yield a value to the parent fiber (execution pauses) | |----------------------------------------------+------------------------------------------------------------------| ** Parsing |----------------------------------------------------+-----------------------------------------------------------------------| | default-peg-grammar | default grammar for PEGs | | (parse str) | parse a string and return the first value | | (parse-all str) | parse a string and return all values | | (parser/byte parser b) | input a single byte into the parser stream | | (parser/clone p) | create a deep clone of the parser p | | (parser/consume parser bytes &opt index) | input bytes into the parser and parse them | | (parser/eof parser) | indicate the end of file, parser becomes :dead | | (parser/error parser) | returns the error message (or nil if it is not in an error state) | | (parser/flush parser) | clear the parser state and queue | | (parser/has-more parser) | check if there are more values in the parser queue | | (parser/insert parser value) | insert a value in the parser | | (parser/new) | create a new parser | | (parser/produce parser &opt wrap) | dequeue the next value in the parser queue | | (parser/state parser &opt key) | get the internal state of the parser | | (parser/status parser) | get the current status of the parser (:pending, :error, :root, :dead) | | (parser/where parser &opt line col) | get the current line number and column of the parser | | (peg/compile peg) | compile a PEG source | | (peg/find peg text &opt start & args) | find the first match index (nil if not found) | | (peg/find-all peg text &opt start & args) | find all match indices | | (peg/match peg text &opt start & args) | match a peg to string and return the captured values | | (peg/replace peg subst text &opt start & args) | replace the first match of peg with subst, return a new buffer | | (peg/replace-all peg subst text &opt start & args) | replace all matches of peg with subst, return a new buffer | | (scan-number str &opt base) | parse a number | |----------------------------------------------------+-----------------------------------------------------------------------| ** Networking |-----------------------------------------------------+----------------------------------------------------| | (net/accept stream &opt timeout) | get the next connection on a server stream | | (net/accept-loop stream handler) | server stream continuously accepting connections | | (net/address host port &opt type multi) | look up connection information | | (net/address-unpack address) | return a host/port pair | | (net/chunk stream nbytes &opt buf timeout) | like net/read, but wait for all bytes to arrive | | (net/close stream) | alias for ev/close | | (net/connect host port &opt type bindhost bindport) | open a connection | | (net/flush stream) | flush a network stream | | (net/listen host port &opt type no-reuse) | create a server | | (net/localname stream) | local address/port pair | | (net/peername stream) | remote address/port pair | | (net/read stream nbytes &opt buf timeout) | read at most n bytes from a network stream | | (net/recv-from stream nbytes buf &opt timeout) | receive data from a stream and puts in a buffer | | (net/send-to stream dest data &opt timeout | write a datagram to a server stream | | (net/server host port &opt handler type no-reuse) | start a server with net/listen and net/accept-loop | | (net/setsockopt stream option value) | set socket options | | (net/shutdown stream &opt mode) | stop communication on a stream | | (net/write stream data &opt timeout) | write data to a stream | |-----------------------------------------------------+----------------------------------------------------| ** Operating System |---------------------------------------------------------+----------------------------------------------------------| | (os/arch) | OS type | | (os/cd path) | change current directory | | (os/chmod path mode) | change file permissions | | (os/clock &opt source format) | current time | | (os/compiler) | compiler used to compile the interpreter | | (os/cpu-count &opt dflt) | number of CPUs available | | (os/cryptorand n &opt buf) | get (or append to buf) n random bytes | | (os/cwd) | current working directory | | (os/date &opt time local) | current (or given) time as a date struct | | (os/dir dir &opt array) | iterate over files/subdirs | | (os/environ) | OS environment table | | (os/execute args &opt flags env) | execute a program and return the exit code | | (os/exit &opt x force) | exit from janet with exit code x | | (os/getenv variable &opt dflt) | get OS environment variable | | (os/isatty &opt file) | is file (default: standard output) a terminal? | | (os/link oldpath newpath &opt symlink) | create a link | | (os/lstat path &opt tab/key) | like os/stat, but does not follow symlinks | | (os/mkdir path) | create a directory | | (os/mktime date-struct &opt local) | number of seconds since epoch from a date struct | | (os/open path &opt flags mode) | stream from a file | | (os/perm-int bytes) | parse a 9-character permission string to an int | | (os/perm-string int) | convert a permission code to a string | | (os/pipe &opt flags) | create a tuple of readable and writable streams | | (os/posix-exec args &opt flags env) | like os/exit, but replace the current process | | (os/posix-fork) | create a new process by a fork system call | | (os/proc-close proc) | close pipes created by the subprocess | | (os/proc-kill proc &opt wait signal) | kill a subprocess | | (os/proc-wait proc) | suspend until the subprocess completes | | (os/readlink path) | read a symbolic link | | (os/realpath path) | absolute path as a string | | (os/rename oldname newname) | rename a file | | (os/rm path) | delete a file | | (os/rmdir path) | delete an empty directory | | (os/setenv variable value) | set OS environment variable | | (os/setlocale &opt locale category) | set the system locale | | (os/shell str) | pass a command to the system shell | | (os/sigaction which &opt handler interrupt-interpreter) | add a signal handler | | (os/sleep n) | sleep for n seconds | | (os/spawn args &opt flags env) | execute a program and return a process | | (os/stat path &opt tab/key) | get information on a file/directory | | (os/strftime fmt &opt time local) | format the given time (default: current time) | | (os/symlink oldpath newpath) | create a symlink, same as (os/link oldpath newpath true) | | (os/time) | current time as seconds since the epoch | | (os/touch path &opt actime modtime) | update the access/modification time of a file | | (os/umask mask) | set a new umask | | (os/which) | get the current OS | |---------------------------------------------------------+----------------------------------------------------------| ** Error handling & Debugging |----------------------------------------------+-------------------------------------------------| | (assert x &opt err) | throw an error if x is not truthy | | (assertf x fmt & args) | assert + string/format | | (error e) | throws an error | | (errorf fmt & args) | error + string/format | | (bad-compile msg macrof where &opt line col) | handler for compile error | | (bad-parse p where) | handler for parse error | | (debug &opt x) | throws a debug signal | | (signal what x) | raise a signal with payload x | | (debug/arg-stack fiber) | gets all values in a fiber's argument stack | | (debug/break source line col) | set a breakpoint at a source point | | (debug/fbreak fun &opt pc) | set a breakpoint in a function | | (debug/lineage fib) | gets the array of child fibers | | (debug/stack fib) | gets the stack as an array of tables | | (debug/stacktrace fiber &opt err prefix) | prints a stacktrace | | (debug/step fiber &opt x) | steps a fiber | | (debug/unbreak source line column) | removes a breakpoint at a source point | | (debug/unfbreak fun &opt pc) | removes a breakpoint in a function | | (debugger fiber &opt level) | run a REPL-based debugger | | debugger-env | table of dot-prefixed functions for debugging | | (debugger-on-status env &opt level is-repl) | creates a function to be called on errors | | (flycheck path &keys kwargs) | checks a file without running it | | (maclintf level fmt & args) | linter warning (inside a macro) | | (propagate x fiber) | propagate a signal from a fiber to the current | | (protect & body) | evaluate expressions while capturing any errors | | (trace func) | enable tracing of a function | | (untrace func) | disable tracing of a function | | (tracev x) | print to stderr the form and its value | | (try body catch) | try executing body and catch errors | | (warn-compile msg level where &opt line col) | default handler for compile warning | |----------------------------------------------+-------------------------------------------------| ** Miscellaneous |---------------------------------------------+------------------------------------------------------------------------| | (freeze x) | make x immutable and create a deep copy | | (thaw ds) | make ds mutable and create a deep copy | | (gccollect) | garbage collection (not to be used manually) | | (gcinterval) | get number of bytes to allocate before garbage collection | | (gcsetinterval interval) | set number of bytes to allocate before garbage collection | | (hash value) | get the hash of any value | | (dempotent? x) | does x evaluate to itself? | | janet/build | janet build identifier | | janet/config-bits | janet compatibility flag | | janet/version | janet version | | (keep-syntax before after) | creates a tuple with the type of before and the elements of after | | (keep-syntax! before after) | like keep-syntax, but after is coerced to a tuple (if it was an array) | | (macex x &opt on-binding) | expand macros completely, with an optional callback on bindings | | (macex1 x &opt on-binding) | like macex, but expand only one level | | (memcmp a b &opt len offset-a offset-b) | compare two byte sequences | | (quit &opt value) | tries to exit from the current REPL | | (repl &opt chunks onsignal env parser read) | run a repl | | (sandbox & forbidden-capabilities) | disable feature sets | | (walk f form) | iterate over an AST and apply f to the values | |---------------------------------------------+------------------------------------------------------------------------|