Skip to content
Jennifer Programming Language

Imports

Three keywords, three mechanisms:

jennifer
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 module

use 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.

LibraryEnable withContentsReference
iouse io;io.printf, io.sprintf, io.readLine, io.eof, and the format-verb mini-languagelibraries/io.md
kvuse 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
convertuse convert;convert.toInt, convert.toFloat, convert.toString, convert.toBool, convert.typeOf - explicit castslibraries/convert.md
mathuse 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.Elibraries/math.md
stringsuse strings;strings.upper, lower, contains, startsWith, endsWith, indexOf, trim, trimLeft, trimRight, trimPrefix, trimSuffix, trimSet, trimLeftSet, trimRightSet, replace, replicate, split, chars, joinlibraries/strings.md
binaryuse binary;binary.make, concat, join, indexOf, contains, split, startsWith, endsWith - bulk operations on bytes (the byte-data counterpart to strings/lists)libraries/binary.md
jsonuse 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
tomluse 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 INIlibraries/toml.md
listsuse 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 helperslibraries/lists.md
mapsuse maps;maps.keys, values, has, delete, without, merge - non-mutating helperslibraries/maps.md
osuse 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.ARGSlibraries/os.md
pathuse path;path.base, dir, ext, stem, join, clean, isAbs, split - OS-aware path manipulation (the string layer paired with fs), no I/Olibraries/path.md
metause meta;meta.VERSION, meta.BUILD (interpreter identity), meta.hasCapability, meta.call / defined (call a function by name)libraries/meta.md
timeuse time;instants, durations, calendar accessors, fixed-offset zones, strftime format/parse, ISO; structs time.Time, time.Duration, time.Zone; constant time.UTClibraries/time.md
hashuse hash;hash.compute(algo, b) for "md5"/"sha1"/"sha256"; streaming via hash.stream/update/finalize; struct hash.Streamlibraries/hash.md
archiveuse 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
compressuse compress;byte-stream compression: pack/unpack for "gzip"/"zlib"/"deflate" (optional "fast"/"default"/"best" level) + streaming (compress.stream/update/finalize); struct compress.Streamlibraries/compress.md
imagesuse 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 / fromPixelslibraries/images.md
crcuse crc;crc.compute(algo, b) for "crc32"/"crc64" (big-endian bytes); streaming via crc.stream/update/finalize; struct crc.Streamlibraries/crc.md
decimaluse 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), comparelibraries/decimal.md
encodinguse 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 parserslibraries/encoding.md
taskuse task;observe / join task of T handles from spawn { ... }. task.wait, task.poll, task.discard, task.waitAll, task.waitAny, task.cancel, task.waitTimeoutlibraries/task.md
fsuse 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.Filelibraries/fs.md
netuse 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 errorlibraries/net.md
httpduse 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 errorlibraries/httpd.md
regexuse 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 matcheslibraries/regex.md
testinguse 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 testlibraries/testing.md
uuiduse 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
serialuse 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 throwslibraries/serial.md
spiuse spi;SPI devices. open(path) / openWith(path, spi.Options) -> spi.Device, full-duplex transfer(dev, bytes), close. Linux-only; stub elsewherelibraries/spi.md
i2cuse i2c;the I2C bus. open(path, addr) -> i2c.Bus, read/write/readReg/writeReg/close. Linux-only; stub elsewherelibraries/i2c.md
gpiouse gpio;GPIO over /dev/gpiochipN (v2 ioctls). open(path) -> gpio.Chip, setup/read/write/release(chip, pin, ...), close, + IN/OUT. Linux-only; stub elsewherelibraries/gpio.md
sqluse 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 itlibraries/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:

jennifer
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:

jennifer
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 prefix

Aliasing rules

  • Rename, not addition. After use os as o; only o. resolves; os.PLATFORM errors with a "did you mean o?" hint, like Python's import foo as bar.
  • Canonical name freed. The aliased canonical name (os above) is freed for ordinary identifier use: you could write func os() { ... } after use os as o;. The style guide recommends against it.
  • Without aliasing, the prefix is reserved. Bare use os; reserves os as a namespace prefix for the rest of the program; func os() {} then errors with shadows imported namespace 'os'.
  • Repeating a use is a silent no-op, in the REPL and in a batch program. Pick one form per program.
  • Module import works 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 later mod.member resolves 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:

jennifer
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:

jennifer
include "helpers.j";          # sibling file
include "subdir/utils.j";     # subdirectory
include "../shared/util.j";   # parent dir
include "/abs/path/lib.j";    # absolute path

File splices may appear anywhere a statement is allowed, including inside a block:

jennifer
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.

jennifer
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"; or import "../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 DIR passed 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, and import "@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:

    1. --vendor DIR on the jennifer run command line;
    2. the JENNIFER_VENDOR environment variable;
    3. the nearest vendor/ directory at or above the directory of the program being run. Symlinks are resolved first, so a command that jvc app install linked onto PATH finds the vendor/ 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 install fills vendor/.

    JENNIFER_VENDOR wins over the walk for every program it reaches, child processes included, so an app that carries its own vendor/ 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 - an included file, or a module and its _test.j overlay - 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 main imports db and db imports config, the order is config, then db, then main's body.
  • Acyclic. An import cycle (a imports b imports a) is a load-time error that names every edge in the loop.
  • Load errors are not catchable. A parse error or a throw during a module's initialisation fails the program at load. An import is a declaration, not an expression, so it cannot appear inside a try/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.

jennifer
# 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 - use is not transitive, so the module's use net; does not give you net.*).
  • alias.CONST reads an exported constant.
  • alias.Struct names an exported struct type, and alias.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 caught alias.HttpError goes back into a function taking it), while a.Point and b.Point from two modules stay distinct types. An exported struct or function signature may not expose a private struct (a referential-closure error at the export).
  • A module top level is declarations-only: def const, def struct, func, use, import - no mutable def and no free-standing statements. A def const initializer may still call a private func.
jennifer
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 constant

Testing: 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:

  • include does 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.
  • import loads 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:

text
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:

jennifer
# pragma-jennifer-version: >=0.25.0
# pragma-jennifer-capability: net
  • version is 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 bare 0.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 plain major.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 -dev version) 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 fmt writes it as >=X.Y.Z or >=X.Y.Z <A.B.C.

  • capability names a host facility the build must provide: net (TCP / UDP / TLS / DNS and the network-backed libraries), exec (os/exec external processes) or sql (the sql database drivers). None is present on jennifer-tiny. List several on one line (capability: net, exec) or on separate lines; they accumulate. Query the same set at runtime with meta.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.