Guide
A tour of the language as it runs today. Every example is a complete program: paste it into the Run page to try it. The reference lists every decision behind these rules.
Getting started
With nothing installed, the Run page compiles and runs a program in your browser. To use it from a terminal, install Tomato from the Download page (a package on a Mac; on Linux or from source, ./install-native.sh with clang installed), then save this as hello.tom:
@main
def main():
print("hello", 6 * 7)
and run it with tomato run hello.tom (it prints hello 42); tomato build hello.tom -o hello writes a native program instead. The commands are listed at the end of this guide.
Programs
A program starts at a function marked @main. A program has no top-level code: statements go inside a function (only the repl accepts bare statements). Functions also take other entry names, such as @prime; tomato run FILE prime 17 runs it with the input 17, read as the most restrictive type its parameter allows.
def greet(name: str, times: int = 2) -> str:
out = ""
for i in range(times):
out = out + "hi " + name + "; "
return out
@main
def main():
print(greet("tom"), 10 / 4, 7 % 3)
Types
inthas no size limit: it grows as needed (for example2 ** 200).int[length=8]anduint[length=8]have a fixed width, stop on overflow, and need an explicit conversion fromint:uint[length=8](x).floathas a 53-bit significand and an exponent of any size, so no float operation overflows or underflows (float(10 ** 400)is1e+400); it is a plain double whenever the value fits one, and there is only this one float type./between whole numbers gives a float (10 / 4is2.5). Float literals (1.5,2e3),//(rounds down) and**work as in the reference.rationalis exact and comes from the library:from rational import rational, thenrational(1, 3). Alsobool,str,list[T],dict[str, V],set[T], andT | Nonefor an optional value of any of those types, such asint | None.- A local variable or parameter of type
T | Noneis a plainTwhere a test shows it is notNone: afterif s is None: return(orraise,break,continue, orassert s is not None), in the body ofif s is not None:and ofwhile node is not None:, and on the right ofs is not None and ..., sos + '!'andx + 1need no check. Assigning a value that is notNonenarrows it from there (if s is None: s = 'default'leavessastr, and so does anif/elsethat assigns it in every branch); assigningNoneor an optional ends it, and a field such asself.nameis never narrowed. x is Ttests the type of a value andx is not Tits opposite:x is int,shape is Circle,x is None,x is list[int]. It tells which member a union such asint | strholds, and insideif x is int:, in itselseand laterelifs, and after anifwhose other branchesreturn,raise,breakorcontinue(if x is not int: returnleaves anint), the variable has the narrowed type. AT | Nonethatis Tis notNonethere either. A class or interface is tested by the object's own class: withpet: Animalholding aDog,pet is Animalandpet is Dogare true andpet is Catis false, and insideif pet is Dog:the variable is aDog, sopet.tricksworks. Between two objects, lists, dicts or sets,a is basks whether they are the same one, not equal ones (==compares what they hold); numbers, text and tuples are values, andison them is an error that says to use==.inis only membership (if a in items:);x in int, the old spelling of the type test, still works in 1.0.x with a warning.- Names follow Python's rule: the innermost one wins. A function, class or constant of your module (or one you import) named like a built-in, such as
def len(x: int) -> int, is used instead of the built-in in that module. A parameter or variable of a function hides a built-in, function or class of its name everywhere in that function, in calls too:def f(len: int): return len + 1works,max = 5makesmaxthe number, a variable that holds a function (fn(int) -> int) is called as that function, and calling a variable that is not a function is an error. The compiler warns (shadow) about each such variable. The names of the types (int,uint,float,bool,str,File,list,dict,set,tuple) cannot be defined or used as a variable name, because they always mean the type. f-strings,assert, unpacking,forloops and comprehensions keep working whatever your names are. - Types are checked at compile time. A constant out of range for a fixed-width type, like
uint[length=8] = 300, is a compile error.
Lists, dicts, tuples and text
@main
def main():
xs = [5, 3, 8]
xs.append(1)
print(xs.pop(), xs.pop(0), xs) # 1 5 [3, 8]
xs.insert(1, 9) # [3, 9, 8]
xs.extend([4, 4])
xs.sort() # also xs.sort(key=n -> -n) and xs.sort(cmp=(a, b) -> b - a)
xs.reverse()
print(xs, xs[-1], xs[1:3], xs + [0], [0] * 2, 8 in xs, xs == [9, 8, 4, 4, 3])
try:
xs.pop(10)
catch IndexError as e:
print(e.message) # index out of range
ages = {'ann': 31, 'bob': 7} # a dict[str, int]: the type comes from the first value
ages['cy'] = 40
ages.remove('bob')
print(ages, len(ages), 'ann' in ages, ages.get('zed', 0), ages.keys(), ages.values())
for name, age in ages.items(): # a for loop can take each pair apart
print(name, age + 1)
nicknames = {'ann': 'annie'}
print(nicknames.get('bob') is None, nicknames.get('ann')) # get(key) gives None when it is missing
pair = ('ann', 31) # a tuple[str, int]: a fixed length, each item with its own type
who, n = pair
print(pair, pair[1] + 1, who, n)
for label, count in [('a', 1), ('b', 2)]:
print(label, count)
s = ' Hello, World '
print(s.strip(), s.strip(' H'), s.find('o'), s.rfind('o'), s.count('l'), s.find('o', 8))
print('héllo'[1], len('héllo'), 'a-b-c'.split('-'), '+'.join(['x', 'y']), 'é'.isalpha())
Lists. xs.append(x), xs.pop() (the last item) or xs.pop(i), xs.insert(i, x) (i from 0 to len(xs), negative counts from the end, anything else is an error: no clamping), xs.extend(ys) (a list of the same type), xs.sort() and xs.reverse() change the list in place and give nothing back. sort takes key= or cmp= as sorted does. Lists compare with == and != item by item (items of a class need an @eq method). pop on an empty list and an index out of range raise an IndexError. A list of bool or of fixed-width integers is stored one to four bytes per item, which changes nothing you write.
Dicts. Keys can be any hashable value: int, bool, float, text, tuples of those, fixed-width integers, T | None, unions and interface values of those, and objects of a class with a method marked @hash (@hash def h(self) -> int: return hash(self.x) * 31 + hash(self.y); objects are equal by their @eq, or only to themselves when the class has none, and equal keys must have equal hashes). A list, set or dict cannot be a key (use a tuple), and a class with @eq but no @hash cannot either; hash(x) gives the hash of any key. A literal with no declared type takes its key and value types from its first pair, as a list literal does (an empty {} needs a declared type: d: dict[str, int] = {}). d[key] raises a KeyError for a missing key; d.get(key, default) never does, and d.get(key) gives None when the key is missing, for a value that can be None (text, list, dict, set or object; for other values the compiler asks for a default). d.remove(key), d.keys(), d.values() and d.items() (a list of tuple[K, V] pairs, for any value type) are the rest. Sets have add and remove.
Tuples. (1, 2) is a tuple[int]: immutable, any length, one item type. Different item types make a fixed-length tuple with a type per item, tuple[str, int] (('ann', 31); indexes are written as numbers: pair[1]). a, b = pair takes one apart, a function can return a, b, and for a, b in pairs: and for k, v in d.items(): take each pair apart in the loop. A mixed tuple type can be written in annotations (x: tuple[str, int]) but not inside an expression, and it prints like Python shows it, also inside a union (('a', 1)).
Text. Indexing, slicing and len count characters, not bytes ('héllo'[1] is é). Methods: find, rfind and count (with an optional start and end), startswith, endswith, replace, split, join, upper and lower (Unicode, one letter at a time), strip, lstrip and rstrip (white space, or the characters you give), isdigit and isalpha (Unicode) and isspace. Build text with f-strings: f'{name} has {count} items'.
@main
def main():
data = b'GET / HTTP/1.0\r\n' # bytes: immutable binary data
print(data[:3], len(data), data[0], data.split(b' ')[1], b'\r\n' in data) # b'GET' 16 71 b'/' True
raw = 'héllo'.encode() # text to its UTF-8 bytes
print(raw, raw.hex(), raw.decode(), bytes([104, 105]), list(b'hi'))
# b'h\xc3\xa9llo' 68c3a96c6c6f héllo b'hi' [104, 105]
print(bytes.fromhex('ff00'), b'\xff\xfe'.decode(errors='replace')) # b'\xff\x00' and two U+FFFD
Bytes. bytes is binary data: an immutable run of bytes, written b'...' or b"..." with the escapes of text and \xHH (only ASCII characters may be written as themselves). len(b), b[i] (an int from 0 to 255), slices (more bytes), +, *, == and < (byte by byte), x in b (a byte value or a run of bytes), for x in b (the ints), and bytes can be dict keys and set elements. print shows them as Python does, b'GET'. Make them with bytes(n) (zeros), bytes([1, 2, 255]) (each item from 0 to 255), bytes.fromhex('ff 00') or s.encode(), and turn them back with list(b), b.hex() or b.decode() (UTF-8 by default, 'ascii' too; bad bytes are a ValueError, or U+FFFD with errors='replace'). Methods: find, rfind, count, startswith, endswith, split(sep), join, replace, strip, lstrip and rstrip. Bytes and text are different types (b'a' == 'a' is an error). The libraries take and give bytes: os.read_bytes and os.write_bytes, sockets, hashlib, hmac, base64, struct, MessagePack and requests. There is no mutable bytearray yet: build a list[int] and call bytes(items) once.
Angles and math
from math import deg, rad, turn, sin, cos, atan2, sqrt, hypot, log_base, pi
@main
def main():
a = deg(90) # also rad(1.5), turn(0.25), grad(100)
print(a, rad(1.5), turn(0.25)) # 90 deg 1.5 rad 0.25 turn
print(sin(deg(30)), cos(a)) # 0.49999999999999994 0.0
print(atan2(1, 1)) # 0.7853981633974483 rad
print(atan2(1, 1).deg()) # 45.0 (.deg() .rad() .turn() .grad() give floats)
print(deg(90) + turn(0.25), deg(370).normalized()) # 180 deg 10 deg
print(sqrt(2), hypot(3, 4), log_base(100, 10), pi)
- An
Angleknows its unit, sosin(1.0)with a bare float is a compile error; writesin(deg(1))orsin(rad(1.0)).sin,cosandtantake an Angle;asin,acos,atanandatan2(y, x)return one (in radians). - Angles add, subtract, negate (
-deg(30)), scale by a number on either side (deg(30) * 3,3 * deg(30)) and compare whatever their unit (deg(180) == turn(0.5)); the result keeps the unit on the left. A list of angles works withsum,min,maxandsorted. Any class can do the same with methods marked@negand@rmul, and@addand@ltfor those four. - Also
sqrt,cbrt,hypot,exp,log,log2,log10,sinh,cosh,tanhand their inverses, and the constantspi,tauande(constdeclares a constant in your own program too:const rate = 0.5). A value with no answer, likesqrt(-1)ortan(deg(90)), is an error.
Ranges and iteration
@main
def main():
r = range(5, 50, 5)
print(r) # range(5, 50, 5)
print(range(100)) # range(0, 100, 1)
print(len(r), r[1], r[-1], r[2:5], 25 in r)
print(sum(r), list(range(3)), reversed(range(4)))
for i in range(3):
print(i)
range(stop), range(start, stop) and range(start, stop, step) make a range value that keeps only its start, stop and step, so range(1000000000) takes no more memory than range(3). It prints all three numbers, whatever you wrote, and works as a sequence: for, len(), indexing (negative too), slicing (gives another range), in, ==, reversed(), sorted(), sum(), min(), max(), and list(r) for a real list.
A method marked @iter makes its class something a for loop can walk, and a function with yield is a generator you can loop over directly. range itself is a class written this way, in Tomato, in the standard library.
def fib(limit: int) -> int:
a = 0
b = 1
while a < limit:
yield a
c = a + b
a = b
b = c
class Countdown:
start: int
@init
def make(self, start: int):
self.start = start
@iter
def numbers(self) -> int:
n = self.start
while n > 0:
yield n
n = n - 1
@len
def size(self) -> int:
return self.start
@main
def main():
for x in fib(30):
print(x)
for n in Countdown(3):
print(n)
print(len(Countdown(7)), sum(Countdown(4)), list(Countdown(3)))
A generator says what it yields with -> Type and runs inside the for that uses it, one value at a time, with nothing built up in memory (break and continue work as usual). It can only be used as what a for loops over, not stored or passed around. The markers @len, @get (x[i]), @slice (x[a:b:c]), @contains (v in x) and @reversed make the matching built-ins work on your class, and sum, min, max, sorted and list() accept anything with an @iter method. from itertools import progress_bar: for x in progress_bar(items): draws a bar as it goes, for a list, range, text, dict or object of any item type (see Generics below). Text loops too: for ch in "abc".
Input
@main
async def main():
name = await input("Name? ") # one line of text, without the line end
n = int(await input("How many? ")) # int() and float() read text; bad text raises RuntimeError
print("hi", name, n * 2)
try:
while True:
print("line:", await input())
catch EOFError: # no more input
print("done")
input is async (see below), so it is always awaited. tomato run FILE reads standard input, so printf 'Ann\n3\n' | tomato run ask.tom works; input raises EOFError when the input runs out. Inputs for the @main function itself still come from the command line: tomato run FILE main 12. In the repl, a line that asks for input asks once; the answer is remembered and replayed when the session re-runs. On the Run page a field appears after the output when the program asks, and Enter runs it again with that answer added.
Async and tasks
async def count(n: int) -> int yields str: # returns int, yields str statuses
i = 0
while i < n:
yield "step " + str(i) # a status for whoever watches
i = i + 1
return n * 10
async def double(x: int) -> int:
return x * 2
@main
async def main():
print(await double(4)) # runs double and waits for it: 8
t = start count(3) # starts it; a task object, running at the same time
other = start double(10)
async for s in t: # each status as it arrives
print(s)
print(await t, await other) # 30 20
class Feed:
name: str = ''
async def fetch(self, n: int) -> int: # an async method: await obj.fetch(1), or start obj.fetch(1)
await sleep(0.1) # wait 0.1 seconds; other tasks run meanwhile
return n
@iter
async def items(self) yields int: # async for x in feed: reads the statuses
yield 1
yield 2
async def worker() -> int:
try:
await sleep(10)
catch CancelledError: # t.cancel() raises this inside the task at its next wait
print('stopping')
return 0
@main
async def main():
t = start worker()
await sleep(0.1)
print(t.done()) # False: still waiting
t.cancel()
print(await t, t.done()) # stopping, then 0 True
async def makes a function that can wait; calling it makes a task, and await runs it and gives the result (or raises the error it raised), so a missing await is a compile error that says what to write. start f(x) gives the task as a value (task[int], or task[int, str] when it yields statuses) that you can keep in a list and await later. Tasks run on one thread and take turns whenever one waits (for another task, for input) or yields, so they never interrupt each other. The program ends when main is done and nothing is left to run. An await can be inside an expression (int(await input())), in a while or elif condition (run again each time), and in the right side of and/or (run only when needed); the exception is the two values of a if c else b.
Methods can be async too (the task keeps self alive; overrides must be async as well), and an @iter method can be async so async for x in obj: works. await sleep(seconds) waits: time is a logical clock that moves only when every task is waiting, so output order is the same everywhere; natively the program really waits, in the browser the clock jumps. t.cancel() makes the task raise CancelledError (a RuntimeError) at its next wait, so its finally blocks run; t.done() says whether it has finished. If a task fails and nobody awaits it, its error is raised in the task that started it at that task's next await, where try/catch can catch it; if that task is already finished the error is printed to standard error and the program exits with code 1.
Classes and interfaces
interface Shape:
def area(self) -> int
class Rect implements Shape:
w: int
h: int
@init
def make(self, w: int, h: int):
self.w = w
self.h = h
def area(self) -> int:
return self.w * self.h
@main
def main():
shapes: list[Shape] = [Rect(2, 3), Rect(4, 5)]
total = 0
for s in shapes:
total = total + s.area()
print(total)
Single inheritance with override, private and const fields, and interfaces with dynamic dispatch. Memory is reference counted and the runtime frees cycles.
Generics
class Box[T]:
item: T
@init
def make(self, item: T):
self.item = item
def get(self) -> T:
return self.item
def first[T](items: list[T]) -> T:
return items[0]
@main
def main():
print(Box(3).get(), Box('hi').get()) # a Box[int], then a Box[str]
print(first(['a', 'b']), first([1.5]))
b: Box[str] = Box('typed')
nobody: list[Box[int]] = [] # write the type out when no argument has it
A class or function can take type parameters in brackets after its name (class Pair[A, B], up to two). Each call works out the types from its arguments, and the compiler makes one copy of the declaration per set of types, so nothing is slower at run time. An Iterable[T] parameter takes T from the items of a list, tuple, set, dict, text, range or object with @iter. That is how progress_bar and the itertools helpers (permutations, combinations, product, chain, pairwise, batched, repeat) work with any item type: for name in progress_bar(['a', 'b']): gives text, progress_bar(range(10)) gives ints. Generic interfaces, generic methods and bounds on T are not built yet.
Reading and writing TOML
toml is a library written in Tomato (TOML v1.0.0): from toml import loads, load, dump, dumps. loads(text) and load(path) give a Value, the same class json reads into (from value import Value; dump(doc, path) writes one to a file): a table is a Dict, an array a List, and the scalars an Int, Float, Str or Bool. doc['key'] reads a table and .as_str(), .as_int(), .as_float(), .as_bool() read a value (a different kind raises a ValueTypeError that says what was found). An array's elements are .as_list() or [i], 'key' in doc and len(doc) work, and .kind() tells the type (dict, list, str, int, float, bool, datetime, local-datetime, local-date, local-time). The four date and time types are a Moment (.as_moment()), and TOML's inf and nan are a Float whose special says which. To change a document, change the dict or list it holds (doc.as_dict()['key'] = Str('x')). dumps(doc) writes the document back: plain values first, then [tables], then [[arrays of tables]]; a null, bin, ext or timestamp (kinds TOML has no way to write) raises a ValueError. Because both libraries use the one class, a document read from TOML can be written as JSON (json.dumps(toml.loads(text))) and the other way round, as far as the kinds go.
from toml import loads, dumps, integer, TOMLDecodeError
@main
def main():
try:
doc = loads('name = "demo"\n[server]\nport = 8080\n[[user]]\nid = 1\n[[user]]\nid = 2\n')
print(doc['name'].as_str(), doc['server']['port'].as_int(), len(doc['user']))
doc['server'].put('port', integer(9090))
print(dumps(doc))
loads('a = 1\na = 2')
catch TOMLDecodeError as e:
print(e.message, e.line, e.column)
An error in the text raises TOMLDecodeError (a ValueError) with line, column and pos. Integers must fit in 64 bits as TOML says. inf and nan cannot be Tomato floats, so such a value has kind float and special set to inf, -inf or nan. See examples/config.tom and decision D62a.
HTTP requests
import requests
async def main_demo():
r = await requests.get('https://example.com', timeout=10.0)
print(r.status, r.ok, r.headers['content-type'])
print(r.text)
r2 = await requests.post('https://example.com/api', form={'name': 'Ann'}, headers={'X-Key': 'abc'})
try:
r2.raise_for_status()
catch requests.HTTPError as e:
print(e.status)
catch requests.TimeoutError as e:
print('slow')
catch IOError as e: # any other failure: not reached, name not found, too many redirects
print(e.message)
import requests makes the library's names available as requests.get and so on (from requests import get works too). Every call is async and awaited, like input(), and requests started with start really run at the same time. get, post, put, patch, delete, head and request(method, url) take the keyword arguments params (a dict added to the query), data (a body of text, sent as UTF-8, or of bytes), form (a dict sent as an HTML form), json (a Json value or JSON text), headers, timeout (a float in seconds), follow_redirects and max_redirects. A Response has status, ok, url (after redirects), text, content (the body as bytes), headers (lower-case names), json() (the body parsed with json.loads) and raise_for_status(). A 404 or 500 does not raise by itself. Failures raise requests.ConnectionError (name not found, refused, TLS failure), requests.TimeoutError, requests.InvalidURL or requests.TooManyRedirects. All are IOErrors: requests.ConnectionError is a ConnectionError and requests.TimeoutError a TimeoutError (so catch TimeoutError also handles asyncio's timeout), the others are requests.RequestErrors. It needs the system libcurl (on macOS it is there; on Linux install the libcurl package) and works with tomato run, not in the browser playground, where a request raises ConnectionError. r.json() will come with the JSON library. See examples/http_get.tom.
Caches and the clock
from cache import Cache, CacheMiss
@main
def main():
c = Cache[str, int](2) # the last type is the result, the types before it are the key: text keys, int results; at most 2 entries
c.set('a', 1)
c.set('b', 2)
print(c.get('a', 0)) # 1, and 'a' is now the most recently used
c.set('c', 3) # full: 'b', used longest ago, is dropped
print(c.keys(), 'b' in c) # ['c', 'a'] False
print(c.get('b', -1)) # -1: missing keys give the default
try:
print(c['b']) # c[key] raises CacheMiss instead
catch CacheMiss as e:
print(e.message)
print(c.hits, c.misses, c.hit_rate())
t = Cache[str, str](100, 60.0) # every entry expires after 60 seconds
t.set('token', 'abc', ttl=5.0) # this one after 5
g = Cache[int, int, str, float](1000) # a key of three parts (int, int, str) and a float result
g.set(1, 2, 'x', 0.5) # the key parts, then the result
print(g.get(1, 2, 'x', 0.0), g[1, 2, 'x'], (1, 2, 'x') in g) # 0.5 0.5 True
print(g.keys()) # [(1, 2, 'x')]
from cache import Cache is a least-recently-used cache written in Tomato. Cache[K1, K2, ..., R] lists the types of the key parts (one to four) and then the type of the result, the way a function lists its parameters and its return type: Cache[int, int, str, float] remembers a float for each (int, int, str). get(k1, k2, ..., default), peek, set(k1, k2, ..., value, ttl) and delete take the key parts one by one; c[k1, k2] and (k1, k2) in c take them in the brackets or as a tuple; keys() gives tuples when the key has several parts. A key part can be an int, float, bool or str (an object only when its class has @str). get, c[key] and set count as a use; in, peek and keys() do not. Every operation takes constant time (a dict plus a doubly linked list). Capacity 0 stores nothing. delete(key), clear() and len(c) work as expected, and hits, misses, evictions, expirations and hit_rate() count what happened. An expired entry is dropped when it is next looked at. Time comes from the built-in clock(), the seconds on a monotonic clock as a float (take two readings and subtract); a test gives the cache its own Clock subclass, Cache[str, int](100, 60.0, fake), whose now() it controls. Object creation takes no keyword arguments, so ttl and the clock are positional there. The cache has no locking because tasks only switch at await. memoize(f, capacity) remembers a function's results, for a function of one to four parameters: m = memoize(slow, 100), then m.call(7, 2) runs slow(7, 2) once and later calls with 7, 2 return the remembered result (m.results is the cache, a Cache[int, int, int] here, with its hits and misses; there are no closures, so you call through m.call). A disk-backed cache and a request cache for HTTP are not built yet. d.remove(key) deletes an entry from any dict.
Time
from time import time, monotonic, gmtime, strftime, isoformat, format_duration, Stopwatch
@main
def main():
start = monotonic() # a clock that never goes back: only differences mean anything
print(isoformat(1710000000)) # 2024-03-09T16:00:00Z
t = gmtime(1710000000)
print(t.year, t.month, t.day, t.weekday, t.yearday) # 2024 3 9 5 69 (weekday 0 is Monday)
print(strftime('%a %b %e %H:%M:%S %Y', t)) # Sat Mar 9 16:00:00 2024
print(format_duration(7384.0)) # 2h 03m 04s
w = Stopwatch()
print(time() > 0.0, w.elapsed() < 5.0) # time() is seconds since 1970-01-01 00:00:00 UTC
print(format_duration(monotonic() - start))
from time import ... is modelled on Python's time, written in Tomato. time() and time_ns() are the wall clock (a float of seconds, an exact int of nanoseconds, since 1970-01-01 UTC; they can jump when the system clock is set); monotonic() and monotonic_ns() are the clock to time things with, the same clock as the built-in clock(). gmtime(seconds) breaks a moment into a Time (year, month, day, hour, minute, second, weekday with Monday as 0, yearday with January 1st as 1); timegm(year, month, day, hour, minute, second) and mktime(t) go the other way. strftime(fmt, t) takes a Time or the seconds, and knows %Y %y %m %d %e %H %I %M %S %p %j %a %A %b %B %w %u %Z %z %F %T %R %D %c %x %X %n %t %%; asctime(t), ctime(seconds) and isoformat(seconds) are ready-made formats, and format_duration(seconds) writes a length of time for people (250ms, 12.5s, 2m 05s). Everything is UTC, because the language has no time zones (so there is no localtime, and %Z is UTC); dates use the proleptic Gregorian calendar, and gmtime raises a ValueError for a moment more than about 292 billion years from 1970. There is no time.sleep and no strptime: waiting is the built-in await sleep(seconds), which lets other tasks run.
JSON and MessagePack
from json import loads, dumps, JSONDecodeError
from value import Dict, Int, Str
@main
def main():
doc = loads('{"name": "tomato", "tags": ["red", "round"], "n": 3, "pi": 3.14}')
print(doc['name'].as_str(), doc['tags'][1].as_str(), doc['n'].as_int()) # tomato round 3
print(len(doc), 'n' in doc, doc['pi'].kind()) # 4 True float
extra = doc.get('missing') # None when the key is absent
print(extra is None) # True
out = Dict({'ok': Int(1), 'who': Str('Ada')})
print(dumps(out)) # {"ok":1,"who":"Ada"}
print(dumps(out, indent=2, sort_keys=True))
try:
loads('[1, 2,]')
catch JSONDecodeError as e:
print(e.message, e.line, e.column) # Expecting value: line 1 column 7 (char 6) 1 7
from json import loads, dumps. loads(text) returns a Value (from value import Value, the one class json and toml share): a Null, Bool, Int, Float, Str, List or Dict. Because Tomato is typed, you say what you expect when you read a value: j['a'] and j[0] go into objects and lists, as_int(), as_float() (an int is accepted), as_str(), as_bool(), as_list() and as_dict() take the value out, and kind() ('null', 'bool', 'int', 'float', 'str', 'list', 'dict') says what it is; x is Str tests it as for any class. Reading it as the wrong kind, a missing key or an index out of range raises ValueTypeError. len(j), 'a' in j and j.get('a') (None when missing) work on objects, and == compares two values by kind and content. Build values with the constructors (Int(3), List([...]), Dict({...})); print(j) writes compact JSON-style text.
A number with no fraction or exponent is an exact int of any size; any other number is a float (1e999 is an error, not infinity). Objects keep the order of the document and a repeated key keeps its last value. The parser follows RFC 8259 strictly: no trailing commas, comments, leading zeros, NaN, single quotes, raw control characters in strings, lone surrogate escapes or invalid UTF-8, and no more than 512 levels of nesting. A mistake raises JSONDecodeError, whose message reads Expecting ',' delimiter: line 3 column 5 (char 42) and which carries reason, line, column and pos. dumps(value, indent=0, sort_keys=False, ensure_ascii=False) is compact unless indent is a positive number of spaces; floats come out the way Python prints them (1500.0), and non-ASCII text is written as UTF-8 unless ensure_ascii=True. A parser written in Tomato itself would be slow because indexing text is a linear scan, so the checking and number reading are in the C runtime: an 8 MB document loads in about 0.15 s.
from json import loads_msgpack, dumps_msgpack
from value import Bin, Timestamp, Dict
@main
def main():
packed = dumps_msgpack(Dict({'id': Bin(b'\x01\x02\xff'), 'at': Timestamp(1700000000)}))
print(packed[0:6]) # b'\x82\xa2id\xc4\x03'
back = loads_msgpack(packed)
print(back['id'].as_bytes(), back['at'].seconds())
The same module reads and writes MessagePack, from and to bytes (loads_msgpack(data), dumps_msgpack(value)). A MessagePack bin becomes a Bin (as_bytes()), other extension values an Ext (ext_type(), as_bytes()) and timestamps (extension -1, all three sizes) a Timestamp (seconds(), nanos()); all of them are Values from the value module. Map keys must be text. Ints are written in their shortest form (up to 64 bits, signed or unsigned), floats as float64. Bad data raises MsgpackError with the byte offset; dumps of a bin, ext, timestamp or TOML date is a JSONEncodeError because JSON text has no such values.
To keep MessagePack in a file, dump_msgpack(value, path) writes dumps_msgpack(value) to the file, replacing it, and load_msgpack(path) reads the whole file and decodes it (json.load and json.dump do the same for JSON text). A path that cannot be opened raises IOError with the same message as open(), such as could not open '/tmp/x.msgpack': No such file or directory; a file that opens but cannot be read or written (a directory, a full disk) raises IOError naming the file too. Bad bytes in the file raise MsgpackError, and a value MessagePack cannot hold is refused before the file is touched.
Files
@main
def main():
out = open('notes.txt', 'w') # 'r' (the default) reads, 'w' replaces the file, 'a' appends
out.write('hello\nworld\n')
out.close()
text = open('notes.txt').read() # the whole file as text (UTF-8)
print(len(text.split('\n')), text.strip())
try:
open('no/such/folder/x.txt')
catch IOError as e:
print(e.message) # could not open 'no/such/folder/x.txt': No such file or directory
open(path) or open(path, mode) gives a File with read(), write(text) and close(); the program closes the file itself, though a file that nothing refers to any more is closed too. A second close() does nothing, f.closed() says whether the file is closed, and reading or writing a closed file raises ValueError. A file that cannot be opened raises IOError naming the path and the reason. toml, json and MessagePack have their own load and dump functions for whole files.
Errors
@main
def main():
try:
xs = [1, 2, 3]
print(xs[5])
catch RuntimeError as e:
print("caught", e.message)
n: uint[length=8] = 250
print(n + 5) # 255
print(n + 10) # stops: integer overflow
Runtime failures raise a catchable error, and every class is a RuntimeError, so catch RuntimeError takes any of them: IndexError (a bad index, pop() from an empty list), KeyError (a missing key), ValueError (int('abc'), a step of 0, sqrt(-1)), ZeroDivisionError, OverflowError (integer overflow, a float too large for a library function), IOError (a file that cannot be opened; TimeoutError and ConnectionError are IOErrors too, and the timeouts and connection failures of asyncio, requests and socket are their subclasses, so catch TimeoutError handles them all), EOFError and CancelledError. The errors of json, toml and re are ValueErrors. A bare raise inside a catch raises the caught error again, with its original line and call trace: catch IOError as e: print('could not load'); raise (anywhere else it is a compile error). Catch the narrowest class you can handle; e.message says what happened and e.id is the error's id (such as E04, see error messages). Write your own with class MyError(RuntimeError) (a class with no fields of its own inherits its parent's @init, so class MyError(RuntimeError): pass already takes a message and an optional id), then raise MyError('boom') and catch MyError as e. print(e) and str(e) give the message alone, as in Python (e.message); an uncaught error is reported with its class name in front. A class that declares fields needs an @init of its own that calls RuntimeError.make(self, message). An error nobody catches stops the program with exit status 1. Type errors are found at compile time and are never catchable.
Reading errors and warnings
An error that stops a program shows what is wrong, where (--> program.tom:6:11), the line with a ^ under the problem and, often, a help: line. A runtime error then lists the calls it passed through, innermost first (at half (line 6)). A warning has the same shape but never stops the program: it points at a variable nothing reads, an unused import, code after a return, a variable that might have no value, a name that hides a built-in, or a list changed inside the loop that is going through it. Silence one on its line with a comment such as # allow: unused. In a terminal the command line colors errors red and warnings yellow (--color=auto|always|never, NO_COLOR); the playground colors them too. The words are the same either way; see error messages.
Modules and LLVM
from util import f imports a module's exported names; import util lets you write util.f instead. import util as u binds only u (u.f, and util is not a name in that file), and from util import f as g, h binds g and h. A file of your project with the name of a standard module (json.tom) is used instead of the library's, with a warning; std/reserved.txt lists the names the library keeps for modules it may add (http, log, queue, ...), which a seed cannot use. !name(a: T) -> R declares a function from LLVM IR you supply with --llvm, and !name(x) calls it. Any symbol that exists when the program is linked can be declared (libc's !abs, your own C or IR); a float is passed as a C double. Only the runtime's own tomato_* functions are reserved: !tomato_... outside the standard library is a compile error.
Commands
tomato init [NAME] [--seed] | start a project in this folder: tomato.toml, src/main.tom, tests/ with an example test, and a .gitignore with builds/ (--seed: a seed, a package); it never overwrites a file |
tomato run [FILE] [ENTRY [INPUTS…]] [--mode MODE] [--llvm F.ll] | compile, link and run; with no word it runs the project's src/main.tom; a first word that ends in .tom or has a / is the FILE, any other word is an ENTRY of it, and everything after the entry is input, read as it is (options go before it; -- ends them); MODE is debug (the default: readable errors, leak report) or release (short error codes, linked with -O2) (reads standard input for await input()) |
tomato build [FILE] [-o OUT] [--entry NAME] [--mode MODE] [--llvm F.ll] | write a native program, by default builds/NAME from src/main.tom (--mode release for the optimised build). The program takes [ENTRY [INPUTS…]]: no word runs main, an entry name runs that entry. An entry parameter typed File is opened for reading from its word (- is standard input) before the entry runs. With --entry NAME the program has that one entry and takes just its inputs |
tomato compile [FILE] [--entry NAME] [--mode MODE] | print the LLVM IR |
tomato explain CODE [FILE] | decode an error id such as E04, or the id and line of the error a program built with --mode release prints (E01:4 for error[E01]: division by zero (line 4)), into the error's class and message; with a FILE it also shows the source line |
tomato config [FILE] | show the settings in effect and where each comes from: [limits] in the tomato.toml found in the program's folder (or the current folder) or a parent, and in ~/.tomato/config.toml (see D77g in the decisions); the user file may also give [build] mode, the lowest default of --mode (D99a) |
tomato seed install [--locked] [--offline] [--yes], tomato seed add --path DIR | --git URL | gh:USER/REPO --rev COMMIT [--test] [--yes] [--offline], tomato seed remove NAME, tomato seed vendor [--offline], tomato seed check, tomato seed hash [FOLDER] | seeds (packages) from a folder or a git repository: install locks the { path = "../folder" } and { git = "URL", rev = "COMMIT" } seeds of tomato.toml into tomato.lock (a git seed is fetched into ~/.tomato/seeds; a program can then import their modules), add lists a seed in [seeds] (--test: [test-seeds]), shows the !name(...) foreign symbols it declares and asks to accept them, remove drops one, vendor copies the locked seeds into vendor/, check checks the seed in this folder and hash prints a folder's content hash. There is no registry yet. tomato.toml also gives --mode and -o their defaults ([build]) and sets the oldest compiler a project needs (tomato = "1.0"); see docs/manifest.md |
tomato repl [FILE…] | interactive prompt that edits whole blocks: Up and Down recall an earlier piece (a block as its real lines), the arrow keys move within it and between its lines, Enter runs a complete piece (an open bracket or a block goes on to the next line, a block ends at an empty line), Tab completes a name (keywords, built-ins, the names of your session, standard modules after import, :commands) or indents, Ctrl-C cancels, Ctrl-D leaves; the code is colored as you type it on a terminal with colors (--color=auto|always|never, NO_COLOR); the history is kept in ~/.tomato/repl_history_v2; += works; needs only the compiler and clang; each line joins the session, which is compiled and run, and only new output is shown; a def, class, interface or annotated variable (x: int = 2) with the name of an earlier one replaces it for the whole session, so earlier lines and the objects they made use the new one (and the new one is refused, keeping the old, when an earlier line no longer works with it, say after a change of type); :load FILE, :program, :save FILE, :compile, :reset, :help and :quit. Because the whole session re-runs on each line, a side effect outside the program (writing a file) repeats, and a function or class you define cannot read your variables (pass them as arguments) |
tomato update | install the newest release |
tomato version | print the version |
tomato help | list the commands. Every command also takes --color=auto|always|never and --no-warnings, and after -- every word is an input to the program |
Not yet
Some decided features are not built yet, such as & intersection types, */** spreading at call sites and @init flow analysis. The specification has a status table that marks what is built and what is not.