Types
These are Jade's value types.
| Type | Description |
|---|---|
int | Signed integer, 64 bits wide; also spelled long |
float | 64-bit floating point (f64); also spelled double |
byte, short, ushort, int32, uint32, ulong | Integers of a fixed width, signed or not; see Sized numbers |
float32 | 32-bit floating point |
bool | Boolean true or false |
char | A single Unicode scalar; what indexing or iterating a string yields |
str | UTF-8 string with indexing, iteration, and concatenation |
bytes | A counted sequence of raw octets; binary data that is not text |
array | Mutable array with index access; may hold values of different types |
dict | String-keyed mutable hash map |
stream | A buffered sequence produced by a yielding function, or by a pipe over one |
struct | User-defined record type with named fields |
fn | First-class function value |
prompt | Text to send to a model; ?p dereferences one |
grammar | A sampling constraint built by Grammar.new(pattern) |
nil | Absence of value |
An async fn and the future its call produces are covered in Async.
Int is 64 bits
An int is a signed 64-bit integer, from -9223372036854775808 to 9223372036854775807. Jade 1.x spent one bit of the machine word tagging what kind of value it held, which left 63 bits; Jade 2.0 knows every value's type when it compiles, so the whole word holds the number.
A literal outside that range is refused when the file is read. The lowest value is a special case. Jade treats - as a separate negation, so it checks the digits before applying the sign, and allows the one magnitude, 9223372036854775808, only when a - comes before it.
An int literal can also be written in hex: 0x or 0X, then the digits 0-9 and a-f in either case. It is an int like any other, with the same range.
print(0x11) // 17
print(0xff + 1) // 256
print(0x7fffffffffffffff) // 9223372036854775807
Arithmetic that would leave the range raises an error instead of wrapping around:
let big = 3037000500
try {
print(big * big)
} catch e {
print("overflow caught")
}
Sized numbers
Beside int and float, Jade has number types of a fixed width, for C libraries, file formats and kernels that use them.
| Type | Width | Range |
|---|---|---|
byte | 8 bits, unsigned | 0 to 255 |
short | 16 bits | -32768 to 32767 |
ushort | 16 bits, unsigned | 0 to 65535 |
int32 | 32 bits | -2147483648 to 2147483647 |
uint32 | 32 bits, unsigned | 0 to 4294967295 |
int, also long | 64 bits | the int's range |
ulong | 64 bits, unsigned | 0 to 18446744073709551615 |
float32 | 32-bit float | single precision |
float, also double | 64-bit float | double precision |
long and double are other names for int and float, not new types.
Arithmetic follows the rules of assembly code:
- Both sides of an operator have one type, and so does the result. A
shortplus anintis refused by the build, with the fix in the message:toInt(s) + n, ors + toShort(n). - A literal takes the type it meets. With
ba byte,b + 1adds the byte 1, and@byte let b = 300is refused, since 300 does not fit. A variable never changes type:@uint32 let y = nwithnan int needstoUint32(n). - Overflow raises. A byte holding 250 plus 10 raises
byte overflow, and so does a byte holding 3 minus 5. Division by zero raises. - Unsigned types divide, compare and shift right as unsigned.
- Converting raises when the value does not fit.
toByte(300)raises300 does not fit a byte, which holds 0 to 255;toByte(n & 0xff)keeps the low bits. Converting to a wider type never fails.
@byte
let b = 200
print(b + 55) // 255
print(toInt(b) + 1000) // 1200
@float32
let f = 1.1
print(f * 3) // 3.3000002, in single precision
int and float keep one exception: they still mix, so 1 + 0.5 is 1.5. The sized types do not.
Type Coercion Rules
Jade converts between types on its own only in a few arithmetic and comparison cases:
| Rule | Example | Result |
|---|---|---|
Arithmetic: int op float → float | 1 + 0.5 | 1.5 (float) |
Ordering: int < float allowed | 1 < 2.5 | true |
| Strict equality: no cross-type coercion | 1 == 1.0 | type error |
Bool ordering: false = 0, true = 1 | false < true | true |
| String ordering, by character | "abc" < "abd" | true |
| Bitwise: integer operands only | 1.0 & 2 | type error |
| Logical: bool operands only | 1 && true | type error |
char and str compare and concatenate | "hi"[0] == "h" | true |
Arithmetic promotion converts an int to a float when the other operand is a float. Equality never promotes, so comparing 1 to 1.0 is always an error.
Every row marked "type error" is caught by jade check before the program runs, not while it runs.
Type functions and converters
Each built-in type has two functions. The type function, named for the type, checks that a value already has that type and returns it unchanged. The converter makes a value of the type from another one.
| Type | Type function | Converter |
|---|---|---|
int | int(x) | toInt(x) |
float | float(x) | toFloat(x) |
str | str(x) | toString(x) |
bool | bool(x) | toBool(x) |
char | char(x) | toChar(x) |
dict | none | toDict(text), which reads JSON text |
print(int(5)) // 5
print(float(5)) // 5.0: an int is also a float
print(toInt("42")) // 42
print(toString(7)) // 7
let n = int("42") // refused by the build: int() needs an int, got str; convert one with toInt()
A type function's check happens when the program is built, since every value's type is known then.
toString writes any value as print shows it, so a dict comes out as JSON text, and toDict reads JSON text back into a dict. The pair is the whole of Jade's JSON support; see Reading and writing JSON.
A type name as a decorator on a let is the same call. @int let n = v means let n = int(v), so it checks the type, and a converter decorates the same way:
@float
let ratio = 1 // 1.0
@toInt
let n = "42" // 42
The one exception: char and str
A char compares equal to the one-character string that spells it. It also orders against strings and concatenates with them in either direction. That is a deliberate hole in the strict-equality rule above, and the reason is worth knowing so you do not read the rest of the rule as merely a suggestion.
Indexing a string used to return a one-character str. As of v1.2.1 it returns a char. Without this exception, every if s[0] == "a" already written would have become a TypeError overnight. The exception keeps that code working.
let s = "café"
print(s[0] == "c") // true
print(s[0] + "at") // cat
for c in s { print(c) } // four lines: "é" is one character, not two
Char
A char is a single Unicode scalar, not a byte. It is an immediate value, meaning it fits inside the tagged value word alongside int, bool, and nil. Scanning a string therefore allocates nothing. The old one-character-string behavior allocated once per character.
There is no char literal. A char comes from indexing a string, iterating one, toChar("x"), toChar(<number>), or toChar(?p).
toInt(c) gives a character's Unicode scalar. toChar(n) builds a character from a number, and refuses anything that is not a valid scalar rather than substituting a replacement character.
The pair exists for reading fixed-size C fields across the FFI. A char[32] arrives as thirty-two characters with its NUL padding intact. Nothing trims the padding, because trimming would mean guessing where the text stops. Instead, a program finds the end itself by testing toInt(c) == 0.
let c = toChar("x")
let first = "hello"[0]
len of a char is 1. That matches the answer it gave back when indexing produced a one-character string.
A char taken from a tainted string stays tainted. So a loop that rebuilds a string one character at a time cannot quietly strip the taint and slip the result past sh.exec.
Bytes
A bytes value is a counted sequence of raw octets. It is deliberately not a string, and the reason matters. A Jade string is UTF-8 and NUL-terminated. So a blob containing a zero byte would be cut short at that byte, and a blob that is not valid UTF-8 would be corrupted by anything treating it as text. fs.read decodes UTF-8, which is why it cannot read a PNG at all.
Conversion is explicit in both directions, never implicit:
use std::fs
let raw = "hi".encode() // str -> bytes, UTF-8
print(raw) // b"hi"
print(len(raw)) // 2
print(raw[0]) // 104. An octet is an int, not a char.
print(raw.decode()) // bytes -> str, raises on invalid UTF-8
fs.write_bytes("out.bin", raw)
let back = fs.read_bytes("out.bin")
Indexing gives an int from 0 to 255 rather than a char. A byte is not a Unicode scalar. Making b[0] behave like s[0] would hide the fact that the two give different answers on any non-ASCII input.
A blob has three methods: len(), decode(), and slice(start, end). slice clamps its bounds rather than raising, so you can take the tail of a buffer without checking its length first.
let raw = "hello".encode()
print(raw.len()) // 5
print(raw.slice(0, 2)) // b"he"
print(raw.slice(3, 99)) // b"lo". The end clamps to the length.
Writing an octet is spelled b[i] = v, the same way an array works, and the value is an int from 0 to 255. A blob is reference-semantic: two names for one buffer see the same write. Building a blob from nothing is what std::bytes is for.
use std::bytes
let buf = bytes.zeros(3)
buf[0] = 255
print(buf) // b"\xff\x00\x00"
bytes is deliberately not a second string type, so there is no way to compare two blobs directly. Using == on them is an error. Decode both first, or compare a slice.
print(b) shows an escaped b"…" form rather than dumping raw octets to your terminal, because a blob can contain control characters or an escape sequence. Use decode() when the bytes really are text.
Bytes carry a trust marker the same way strings do. So sh.exec refuses fs.read_bytes(p).decode() for the same reason it refuses fs.read(p).
Stream
A function whose body contains a yield returns a stream rather than a single value. Called, the body runs all the way through, filling a buffer, and the caller receives that buffer. Piped, doubles(4) |> print, each value goes to the stage at the moment it is yielded instead; see Operators.
fn doubles(n) {
let i = 0
while (i < n) {
yield i * 2
i = i + 1
}
}
let s = doubles(4)
print(len(s)) // 4
print(s[0]) // 0
for x in s { print(x) }
for x in s { print(x) } // the same values again
A stream is a buffer, not a one-shot channel. It keeps everything it produced, so reading it twice gives the same values twice. There is no "already consumed" state to keep track of. len and indexing work for the same reason.
A prompt's reply arrives in pieces too. ?p waits for the whole reply and gives a str, while ?p |> write shows each piece as the model writes it, and ?p |> f gives back a stream of what f returned.
A bare return stops a generator early. Writing return x is a compile error, because a function that yields already produces a stream. Returning a value as well would ask it to be two things at once.
Yields of different types widen into a mixed stream rather than failing. A mixed array literal follows the same rule.
Prompt
A prompt holds text meant for a model. It is a value like any other, so you can pass it to a function, store it in a struct field, or hand it to another file. Nothing is sent until you dereference it with ?.
prompt p = "Name one prime number under 10."
print(?p)
?p on its own gives the whole reply as a str. A converter around it limits what the model may generate and converts the result, so toInt(?p) gives you an int. A pipe after it, ?p |> write, runs once per piece of the reply as the model writes it. See Prompts and Inference for the whole story, and Operators for how pipes work.
Nil
nil is Jade's single "absence of value" type. Three things evaluate to it: a function that reaches the end of its body without returning, a bare return, and most built-ins that mutate something, such as arr.push(x) and fs.write(...).
Three spellings
nil, None, and null are three spellings of the same value. They all evaluate to the one nil and compare equal to each other. You can use any of them anywhere a literal is expected, including default parameter values and type annotations.
let a = nil
let b = None
let c = null
print(a == b) // true
print(b == c) // true
fn greet(name = null) { // default parameter
return name
}
print(greet()) // nil
The three spellings are aliases, not distinct types. There is no separate null type. A JSON null is not nil: toDict reads it as the text "null" in a dict of strings, and refuses it in any other dict.
Dict
A dict is a mutable hash map with string keys. Values can be any Jade type. You write a dict with curly braces and read it with square brackets.
Creating a dict
let d = {"name": "jade", "version": 1}
let empty = {}
A key can be any expression that produces a string. Jade evaluates it when it builds the literal, so a variable in key position contributes its value, not its name:
let key = "hello"
let greet = {key: "world"}
print(greet["hello"]) // world
Writing {name: 1} where name is not a variable gives an undefined-variable error, not a key spelled "name". Quote a literal key.
Reading and writing values
print(d["name"]) // jade
d["version"] = 2 // update existing key
d["stable"] = true // add new key
Length and lookup
print(len(d)) // number of key-value pairs
print(d.keys()) // ["name", "version"]
print(d.values()) // ["jade", 1]
print(d.has("name")) // true
print(d.get("name")) // jade
print(d.get("nope")) // nil. A missing key is not an error here.
print("name" in d) // true
in and not in test keys, never values.
A dict cannot be iterated directly. Loop over d.keys() instead:
for k in d.keys() {
print(k)
}
Printing a dict
A dict prints as JSON. Its keys are sorted, and a string inside it, a key or a value, is quoted and escaped the way JSON writes it. The same goes for a string inside an array. A string on its own prints bare:
print({"ana": 3, "bo": 5}) // {"ana": 3, "bo": 5}
print({"say": "she said \"hi\""}) // {"say": "she said \"hi\""}
print(["a", "b"]) // ["a", "b"]
print("hi") // hi
print, toString and f-strings all show a value the same way.
Reading and writing JSON
toDict(text) reads JSON text holding an object into a dict, nested levels included, and toString(d) writes a dict as JSON text. Reading a file is fs.read; nothing else about JSON lives in a package.
let city = toDict(fs.read("city.json")) // {"name": "Paris", "population": 2100000}
print(city["name"]) // Paris
let pop = toInt(city["population"]) // 2100000
toInt(city["name"]) // raises: cannot convert "Paris" to an int
A dict holds one type of value, and the program decides which. The type comes from how the program uses the dict, as every other type in Jade does, and it is str when nothing says otherwise:
| The program uses the values as | The dict is | What toDict does with the text |
|---|---|---|
ints, as in scores["ana"] + 1 | a dict of ints | raises on a value that is not an int |
| floats | a dict of floats | takes ints and floats |
| bools | a dict of bools | raises on a value that is not true or false |
dicts, as in d["a"]["x"] | a dict of dicts | each nested level follows the same rule |
arrays, as in d["tags"][0] | a dict of arrays | each element follows the same rule |
| strings, or nothing in particular | a dict of strings | every value fits |
So mixed values never fail on their own. A dict of strings takes every value: a JSON string unescaped, and anything else as the exact text the file wrote, so a number, true or null is its spelling and a nested object or array is its JSON text, which toDict reads again: toDict(city["location"])["lat"]. A value fails only when the program converts it to something it does not fit. A converter such as toInt(city["population"]) takes a str as well as a number, so it does not make the dict a dict of ints; the conversion happens at the call.
toDict raises, with the line and column, on text that is not JSON, on text whose top level is not an object, and on a value that does not fit the dict's type. null fits only a dict of strings, where a program checks for "null". A key written twice keeps its last value. Keys and values keep the trust of the text they came from, so a dict read from a command's output cannot reach sh.run (see Standard Library).
try {
let scores = toDict('{"ana": 3, "bo": "five"}')
print(scores["ana"] + 1)
} catch e {
print(e.message)
// toDict: expected an int, found a string at line 1 column 18; to read mixed
// values, use the dict as strings and convert each with toInt()
}
A dict of strings writes every value quoted, so a number read into one is written back as "2100000". toDict and toString work on dicts, never on classes; a class that should be written out builds a dict.
Value semantics
Assigning a dict to a new variable copies it. Mutations to the copy do not affect the original:
let d2 = d
d2["name"] = "copy"
print(d["name"]) // jade (unchanged)
print(d2["name"]) // copy
Arrays behave the opposite way. Assigning an array shares the same storage, so writing through the second name is visible through the first. Structs behave like arrays. The three containers genuinely differ here, so do not carry a habit from one to another.
| assigning it | passing it to a function that writes to it | |
|---|---|---|
dict | copies | the caller does not see the write |
array | shares | the caller sees the write |
struct | shares | the caller sees the write |
Passing a dict to a function
This is the same rule again, and it is the one that costs people an afternoon. A parameter is an assignment, so a function receives its own copy of a dict. A write to that copy is invisible to the caller. The identical code on an array or a struct does reach the caller:
fn set_it(d) { d["x"] = 99 }
fn push_it(a) { a.push(99) }
let d = {"x": 1}
set_it(d)
print(d["x"]) // 1. Unchanged: the function wrote to its own copy.
let a = [1]
push_it(a)
print(a.len()) // 2. Changed.
Nothing warns you, and the call reports success. So the search for the bug usually starts wherever the stale value is read, rather than at the write that never landed.
Use a struct when a function needs to change something the caller can see. That is the shape the language is built for. Declare the fields, and the change travels back.
struct Cursor { x, y }
fn advance(c, dy) { c.y = c.y + dy }
let cur = Cursor { x: 0, y: 0 }
advance(cur, 10)
print(cur.y) // 10
Nested dicts
Reading a dict out of a dict is also an assignment, so it copies. Writing to what you read back does not reach the outer dict:
let outer = {"inner": {"x": 42}}
let inner = outer["inner"]
print(inner["x"]) // 42
inner["x"] = 1
print(outer["inner"]["x"]) // 42. The outer dict still holds its own copy.
Dict keys are always strings. Accessing a key that does not exist produces a runtime error.