Imports
Three keywords, three mechanisms:
use io; # library import - enables `io.printf`, `io.sprintf`, ...
include "helpers.j"; # textual file splice - pastes helpers.j here
import "./config.j"; # module import - loads config.j as its own moduleuse and include operate at the textual level; import is the module system - a real module boundary with run-once initialisation. A module loads and initialises before the code that imports it (see Module imports below).
Library imports
use NAME; enables a built-in library. Every library is namespaced: every name lives behind the library's prefix (io.printf, math.sqrt, convert.toInt). Nothing auto-loads; every program states its imports. The table below lists the most used libraries; libraries/index.md lists them all.
len(EXPR) is a language built-in (not a library) - polymorphic over string / list / map / bytes; no import needed.
| Library | Enable with | Contents | Reference |
|---|---|---|---|
io | use io; | io.printf, io.sprintf, io.readLine, io.eof, and the format-verb mini-language | libraries/io.md |
kv | use kv; | in-process key/value store with per-key TTL (no-server local counterpart to memcache/redis): kv.open / openFile (persisted) -> kv.Store, then set/add/get/has/delete/touch/incr (signed delta)/close. Shared handle (safe for spawn) | libraries/kv.md |
convert | use convert; | convert.toInt, convert.toFloat, convert.toString, convert.toBool, convert.typeOf - explicit casts | libraries/convert.md |
math | use math; | math.abs, math.min, math.max, math.sqrt, math.pow, math.floor, math.ceil, math.round, math.rand, math.randInt, math.randSeed; constants math.PI, math.E | libraries/math.md |
strings | use strings; | strings.upper, lower, contains, startsWith, endsWith, indexOf, trim, trimLeft, trimRight, trimPrefix, trimSuffix, trimSet, trimLeftSet, trimRightSet, replace, replicate, split, chars, join | libraries/strings.md |
binary | use binary; | binary.make, concat, join, indexOf, contains, split, startsWith, endsWith - bulk operations on bytes (the byte-data counterpart to strings/lists) | libraries/binary.md |
json | use json; | RFC 8259 json.encode/encodePretty/decode; structs and map of string to V map to objects, bytes to base64, integral numbers decode to int else float; decode yields generic values (no map-to-struct coercion) | libraries/json.md |
toml | use toml; | RFC-conformant TOML 1.0 toml.encode/encodePretty/decode; same opaque toml.Value + read / walk / write surface as json (JSON Pointer), plus toml.asDatetime (backed by time.Time) for date-times; the config format Jennifer ships, not INI | libraries/toml.md |
lists | use lists; | lists.push, first, last, reverse, sort, contains, indexOf, mismatch, concat, replicate, shuffle, range(start, stop, step), plus map filter reduce find any all sortBy sortWith - non-mutating helpers | libraries/lists.md |
maps | use maps; | maps.keys, values, has, delete, without, merge - non-mutating helpers | libraries/maps.md |
os | use os; | os.getEnv/getEnvBytes/os.setEnv, os.argsBytes, os.run/runBytes/spawn/wait/waitBytes/poll/kill; constants os.PLATFORM, os.ARCH, os.EOL, os.DIRSEP, os.PATHSEP, os.ARGS | libraries/os.md |
path | use path; | path.base, dir, ext, stem, join, clean, isAbs, split - OS-aware path manipulation (the string layer paired with fs), no I/O | libraries/path.md |
meta | use meta; | meta.VERSION, meta.BUILD (interpreter identity), meta.hasCapability, meta.call / defined (call a function by name) | libraries/meta.md |
time | use time; | instants, durations, calendar accessors, fixed-offset zones, strftime format/parse, ISO; structs time.Time, time.Duration, time.Zone; constant time.UTC | libraries/time.md |
hash | use hash; | hash.compute(algo, b) for "md5"/"sha1"/"sha256"; streaming via hash.stream/update/finalize; struct hash.Stream | libraries/hash.md |
archive | use archive; | tar / zip containers over bytes (no fs): archive.pack/unpack with format "tar"/"zip"/"tar.gz"; bundle is a list of archive.Entry {name, data, mode, mtime} | libraries/archive.md |
compress | use compress; | byte-stream compression: pack/unpack for "gzip"/"zlib"/"deflate" (optional "fast"/"default"/"best" level) + streaming (compress.stream/update/finalize); struct compress.Stream | libraries/compress.md |
images | use images; | raster images: decode / encode PNG, JPEG and GIF into an opaque images.Image (pixels stay in Go), crop / resize / fit / rotate / flip, grayscale / threshold / dither, fill / draw, raw RGBA via pixels / fromPixels | libraries/images.md |
crc | use crc; | crc.compute(algo, b) for "crc32"/"crc64" (big-endian bytes); streaming via crc.stream/update/finalize; struct crc.Stream | libraries/crc.md |
decimal | use decimal; | exact base-10 numbers for money and fixed-place values: decimal.from, exact add / sub / mul, div (exact or at a scale), round with named modes (half-even default), compare | libraries/decimal.md |
encoding | use encoding; | isAscii/lenBytes/lenRunes introspection; toText/fromText for "hex"/"base64"/"base64-url"; encode/decode for character codecs ("utf-8", "ascii", "iso-8859-1", "windows-1252", "ebcdic", ...); parseForm/parseCookies/parseMultipart request parsers | libraries/encoding.md |
task | use task; | observe / join task of T handles from spawn { ... }. task.wait, task.poll, task.discard, task.waitAll, task.waitAny, task.cancel, task.waitTimeout | libraries/task.md |
fs | use fs; | filesystem I/O. Whole-file read/write/append (readString/readBytes/writeString/writeBytes/appendString/appendBytes), metadata (exists/isFile/isDir/stat), directory ops (mkdir/mkdirAll/remove/removeAll/rename/list/walk), buffered handles (open/readLine/readChars/readBytes/writeString/writeBytes/eof/close); structs fs.Stat, fs.File | libraries/fs.md |
net | use net; | TCP + UDP sockets and DNS. TCP connect/listen/accept/readBytes/writeBytes/eof, UDP listenUDP/sendTo/recvFrom, DNS lookup/reverseLookup, polymorphic close/address; structs net.Conn, net.Listener, net.UDPSocket, net.Datagram. Default jennifer only; on jennifer-tiny every entry point throws a clear error | libraries/net.md |
httpd | use httpd; | HTTP/1.1 server engine over net/http (TLS, HTTP/2, graceful shutdown). Pull loop httpd.listen/accept/respond; request accessors method/path/query/header/body/remoteAddr; setHeader, serveFile/serveDir, shutdown; structs httpd.Server, httpd.Request. Default jennifer only; on jennifer-tiny every entry point throws a clear error | libraries/httpd.md |
regex | use regex; | regular expressions over string (RE2 syntax). matches/find/findAll/replace/split/escape + regex.Match with positional and named captures. Implicit LRU cache for compiled patterns; rune-index offsets in matches | libraries/regex.md |
testing | use testing; | test-runner primitives. run/results/reset/report + testing.Result. Catches runtime errors, throws, and exit inside test bodies. Three report formats: "text", "tap", "junit". Used by jennifer test | libraries/testing.md |
uuid | use uuid; | RFC 9562 UUIDs. uuid.v4() / uuid.v7() + parse/isValid/version + constant NIL. The version is a function; RNG is the crypto library's crypto-grade source (unguessable, safe as a security token) | libraries/uuid.md |
serial | use serial; | serial-port I/O with termios config. open(path, baud) / openWith(path, Options) -> serial.Port, read/write/flush/close. Linux-only; jennifer-tiny and non-Linux get a stub that throws | libraries/serial.md |
spi | use spi; | SPI devices. open(path) / openWith(path, spi.Options) -> spi.Device, full-duplex transfer(dev, bytes), close. Linux-only; stub elsewhere | libraries/spi.md |
i2c | use i2c; | the I2C bus. open(path, addr) -> i2c.Bus, read/write/readReg/writeReg/close. Linux-only; stub elsewhere | libraries/i2c.md |
gpio | use gpio; | GPIO over /dev/gpiochipN (v2 ioctls). open(path) -> gpio.Chip, setup/read/write/release(chip, pin, ...), close, + IN/OUT. Linux-only; stub elsewhere | libraries/gpio.md |
sql | use sql; | relational client over database/sql: MySQL / MariaDB + PostgreSQL. open/query/exec/next + typed accessors, transactions, prepared statements; placeholder-only binding (injection safety). Default binary only; jennifer-tiny stubs it | libraries/sql.md |
See libraries/index.md for a fuller catalog and the library-organization principles, or libraries/cheatsheet.md for an alphabetical lookup of every builtin function and constant.
A quick sample:
use io;
use convert;
use math;
io.printf("%s\n", convert.typeOf(5 / 2)); # "float" [convert]
io.printf("%d\n", math.floor(math.PI * 2.0)); # 6 [math + io]
io.printf("%s\n", convert.toString(true)); # "true" [convert]Namespaced calls and aliasing
A qualified call is always prefix.name(...); a qualified constant is prefix.NAME. No spaces around the dot. The prefix is the library name by default; an as ALIAS clause renames it at the use site:
use io;
use os;
use math as m;
io.printf("on %s\n", os.PLATFORM); # canonical prefix
io.printf("pi=%f\n", m.PI); # aliased prefixAliasing rules
- Rename, not addition. After
use os as o;onlyo.resolves;os.PLATFORMerrors with a "did you meano?" hint, like Python'simport foo as bar. - Canonical name freed. The aliased canonical name (
osabove) is freed for ordinary identifier use: you could writefunc os() { ... }afteruse os as o;. The style guide recommends against it. - Without aliasing, the prefix is reserved. Bare
use os;reservesosas a namespace prefix for the rest of the program;func os() {}then errors withshadows imported namespace 'os'. - Repeating a
useis a silent no-op, in the REPL and in a batch program. Pick one form per program. - Module
importworks in the REPL.import "./mod.j";at the prompt loads the module and binds its namespace (local.//../paths resolve against the current directory; a bare name walks the system module path), so a latermod.memberresolves across inputs. Re-typing the same import is a no-op. A module is loaded once and cached by path, so editing the file and re-importing in the same session keeps the cached version - restart the REPL to pick up edits.
len is a language built-in
len(EXPR) is not a library function but a reserved keyword and a language primary expression, polymorphic over string / list / map / bytes; no use statement needed:
def n as int init len("hello"); # 5 (rune count)
def m as int init len([1, 2, 3]); # 3 (element count)There is no core library: len is a language built-in, and the build-version constants live in meta (use meta; then meta.VERSION, meta.BUILD).
File splices (include)
include "PATH.j"; textually splices another .j source file at the point of include. The path is a string literal that must end in .j. Relative paths resolve from the directory of the file containing the include; absolute paths and subdirectories work:
include "helpers.j"; # sibling file
include "subdir/utils.j"; # subdirectory
include "../shared/util.j"; # parent dir
include "/abs/path/lib.j"; # absolute pathFile splices may appear anywhere a statement is allowed, including inside a block:
use io;
include "helpers.j"; # spliced here: whatever helpers.j contains lands here
io.printf("%v\n", $helperValue);Circular includes (file A includes file B, B includes A) are an error.
A file that exists only to be included - a part of a larger program or module, calling functions and reading constants its includer defines - is named NAME.inc.j by convention (the shipped barcode_ecc.inc.j, pdf_afm.inc.j). jennifer lint recognises the suffix: linted on its own, such a fragment is not flagged for names it takes from the including file, which linting that file checks instead.
Module imports
import "PATH.j" [as NAME]; loads another .j file as a module with a real boundary. Where an include pastes tokens into the current scope, an import runs the file as its own program: its top level executes once, in its own scope, before the importing file's body runs.
use io;
import "./config.j"; # config.j initialises before this line returns
import "./db.j"; # db.j (which may itself import config.j) initialises next
io.printf("app: running\n");The path decides where the module is found by its leading token:
Local -
import "./util.j";orimport "../shared.j";resolves relative to the importing file's directory.Absolute -
import "/opt/pkg/m.j";(leading/) is an absolute filesystem path.Module -
import "util.j";(no./, no/) is looked up on the module search path: the system module directory first, then each-I DIRpassed on the command line. The importing file's own directory is not consulted for this form. A/anywhere but the front is an ordinary subdirectory (import "sub/util.j";works in every form).Deck -
import "@scope/deck/";loads a vendored deck's entry module,<vendor>/scope/deck/deck.j, andimport "@scope/deck/file.j";another module of that deck. A path may not leave the deck's directory, and./..segments are refused. One vendor directory serves the whole program, and it is found in this order:--vendor DIRon thejennifer runcommand line;- the
JENNIFER_VENDORenvironment variable; - the nearest
vendor/directory at or above the directory of the program being run. Symlinks are resolved first, so a command thatjvc app installlinked ontoPATHfinds thevendor/of the app it belongs to, not one near the link.
The walk starts at the program, not at the importing module and not at the working directory. Without a vendor directory, an
@import is a load error that names all three options. A sibling checkout of the deck is never found:jvc installfillsvendor/.JENNIFER_VENDORwins over the walk for every program it reaches, child processes included, so an app that carries its ownvendor/sees the variable's directory instead. Set it for one command, not for a whole shell.
Guarantees:
- Run-once. A module's top level runs exactly once per program, cached by its resolved absolute path. Importing it again returns the same initialised module without re-running it. Importing the same module again under the same alias is a silent no-op, like a duplicate
use(so two spliced parts - anincluded file, or a module and its_test.joverlay - can each import what they need); binding an alias that is already bound to a different module is an error. - Post-order init. Imports initialise depth-first: a module is fully initialised before any module that imports it. If
mainimportsdbanddbimportsconfig, the order isconfig, thendb, thenmain's body. - Acyclic. An import cycle (
aimportsbimportsa) is a load-time error that names every edge in the loop. - Load errors are not catchable. A parse error or a
throwduring a module's initialisation fails the program at load. Animportis a declaration, not an expression, so it cannot appear inside atry/catch- wrapping one is itself a parse error.
A module publishes with export; unmarked names are private. Put export in front of a top-level def const, def struct, or func to make it reachable through the importer's alias. A name without export stays internal; reaching it from outside is a positioned "not exported from module" error. export is meaningful only in a module: it is a parse error in a jennifer run script.
# config.j
use convert;
export def const MAXCONN as int init 16; # public
def const NAME as string init "jdb"; # private (no export)
export func describe() { # public
return NAME + " x" + convert.toString(MAXCONN);
}Reaching a module's surface:
alias.fn(args)calls an exported function - the arguments are evaluated in your code, but the body runs in the module's own scope (its constants and other functions, plus whatever it imported -useis not transitive, so the module'suse net;does not give younet.*).alias.CONSTreads an exported constant.alias.Structnames an exported struct type, andalias.Struct{...}builds one. A module struct keeps its identity(module, name)across the boundary, so you can hold one (def p as alias.Struct init alias.make();), read its fields, and pass it back (a struct the module throws too, so a caughtalias.HttpErrorgoes back into a function taking it), whilea.Pointandb.Pointfrom two modules stay distinct types. An exported struct or function signature may not expose a private struct (a referential-closure error at theexport).- A module top level is declarations-only:
def const,def struct,func,use,import- no mutabledefand no free-standing statements. Adef constinitializer may still call a privatefunc.
use io;
import "./config.j" as config;
io.printf("%s\n", config.describe()); # calls an exported function
io.printf("%d\n", config.MAXCONN); # reads an exported constantTesting: a co-located MODULE_test.j is a white-box overlay - jennifer test MODULE_test.j splices MODULE.j in first, so its test* functions reach the module's private names by bare identifier. The module must still declare every use / import it needs itself: the test file's own do not count for it, and jennifer test refuses to run a module that leans on them. For black-box tests, import the module and exercise its exported surface. See the runnable examples/modules/ chain.
include vs import
Both read another .j file, but they differ at the boundary:
includedoes a textual splice with no module boundary - the spliced file's top-level names land directly in the enclosing program's scope, and the same file spliced twice contributes its definitions twice. Use it to share snippets within one program.importloads a module - separate scope, run-once, post-order init. Use it to compose independent files.
Mixing the keywords up is a positioned error that names the fix:
include io; -> error: `include` is for files; use `use io;` for
system libraries
use foo.j; -> error: `use` is for system libraries; for files use
`include "foo.j";`
include foo.j; -> error: file splices take a string literal:
`include "foo.j";`
include "foo.go"; -> error: include path "foo.go" must end with `.j`
import foo; -> error: `import` takes a quoted module path
(`import "foo.j";`); for a system library use `use foo;`The included file's contents must be valid where the include appears: a file containing a top-level-only definition cannot be included inside a block.
Requirement header
A file can declare the minimum interpreter version and the host capabilities it needs, so a mismatch is refused with a clear message at read time, before lex or parse, instead of failing deep in a stub or after a breaking change. The requirements are pragma directives in the leading header block:
# pragma-jennifer-version: >=0.25.0
# pragma-jennifer-capability: netversionis a minimum floor (>=major.minor.patch), optionally with an exclusive upper bound:>=0.25.0 <0.26.0. These two forms are the only ones; there is no>,<=,^,~or||, and the bound must be above the floor. A bare0.25.0(no>=) is a malformed directive, and so is a version with a pre-release or build suffix (>=0.25.0-rc1,>=0.25.0+build): both ends are a plainmajor.minor.patch(lint L303 reports it too). Use the bound when a later release is known to break the file, so it fails at load with "requires jennifer=0.25.0 <0.26.0, but this build is 0.26.0" instead of somewhere inside it. A development build of the interpreter (
dev, or any-devversion) counts as newer than every release: it satisfies every floor and fails every upper bound, since it already carries the next release's changes. Only a clean release tag is compared against both ends. A file states one version range - a duplicate is an error.jennifer fmtwrites it as>=X.Y.Zor>=X.Y.Z <A.B.C.capabilitynames a host facility the build must provide:net(TCP / UDP / TLS / DNS and the network-backed libraries),exec(os/execexternal processes) orsql(thesqldatabase drivers). None is present onjennifer-tiny. List several on one line (capability: net, exec) or on separate lines; they accumulate. Query the same set at runtime withmeta.hasCapability/meta.CAPABILITIES.
The header is a comment (a module top level is declarations-only, and the check runs before parsing), tolerant of the shebang, the SPDX block, and the docblock. The header scan reads comments exactly as the lexer does: a leading UTF-8 byte-order mark is skipped (so a BOM-writing editor cannot switch the check off), and block comments nest, so a directive inside a still-open /* /* */ is commentary. It applies uniformly to a program, a module, and each included file: every file self-checks its own header against the running interpreter, so include needs no merging - the effective floor is the highest and the effective capability set the union. A directive that opens # pragma-jennifer-* but does not parse, a bad version grammar, an unknown key, or an unknown capability name is a hard error, so a typo cannot disable the guard; jennifer lint (L303) reports the same problems before you run.