DEVELOPMENT EDITION · 769442725406
Vibe syntax
On this page

Vibe declarations and statements

Vibe's statements are Python's simple statements on logical lines and compound statements with colon suites. The shared statement reference describes initialization, assignment, control transfer and proof obligations independent of presentation.

Assignment and local declarations

Inside a function, a first assignment to a name declares it. An annotation can supply the type; subsequent assignments must retain that type:

total: int = 0
total = total + amount
total += 1

This body fragment requires an amount whose range makes the arithmetic safe. A loop parameter is read-only. Assignment to a record component or collection element is checked against that component's type and the operation's precondition.

The augmented assignments are +=, -=, *=, /=, //=, %=, **=, &=, |= and ^=. Each is a typed update with its operator's meaning, so /= needs a float target (/ gives a float) and //= is the integer form. A chained assignment, a = b = v, evaluates v once and assigns the targets from left to right, as Python does; each target holds its own copy of the value, as every Vibe assignment does.

A name declared in a branch/loop does not acquire Python's general function-wide local scope. Declare it before that construct when it must survive afterward. Flow analysis rejects a read that is not preceded by initialization on every relevant path. A typed declaration without a value can reserve a local when supported initialization proves later. Whether a local is a constant or a variable is inferred from its later uses.

Tuple assignment and unpacking

The equal-length tuple form evaluates right-side values before performing target writes:

a, b = b, a

Use already declared a and b for the swap pattern. Unpacking a returned/stored tuple into names is supported and can introduce fresh names:

pair: tuple[int, int] = swap_pair(2, 8)
a, b = pair
a, b = b, a

This excerpt comes from the reference project. The tuple expression is evaluated once, then its components are assigned in order. The tuple reference gives the tuple types, of two to four components.

One starred target takes the rest of a named list, string or array, as a slice:

head, *rest = values
first, *_ = values
*init, last = values

The items before the starred target are taken from the start and those after it from the end; the sequence must have at least that many items, which is proved. A starred target is taken only among an assignment's targets.

If statements and conditional values

if condition:, any number of elif branches, and an optional else select statement suites. A condition may bind a name with the walrus, if (n := count(xs)) > 0:, which is bound before the test (and before each later elif that is reached); a walrus where Python might not evaluate it, after and or or or in a conditional's branch, is B0401. Conditions must be Boolean; integer/container/string truthiness is not inferred. Use len(xs) > 0 or an appropriate predicate instead of if xs. a if condition else b is the expression form when one value is required.

answer: int = 0
if first:
    answer = low
elif second:
    answer = high
else:
    answer = fallback

This fragment assumes Boolean first/second and suitably typed values. The declaration before the branches makes the intended scope and assignment explicit.

Loops

while condition: tests a Boolean condition before every iteration. while True: is a forever loop until a permitted exit. A for loop uses one name over a supported iterable, or the tuple targets specifically recognized for zip/enumerate:

for index in range(len(values)):
    inspect(values[index])

for left, right in zip(a, b):
    compare(left, right)

These are loop fragments; the named values and operations must exist. range(n) and range(low, high) are half-open. range(start, stop, step) takes Python's values, from start while below stop (above it for a negative step); its start and step are fixed when the loop begins, a step of 0 is B0401, and the loop ends because it counts its steps. A comprehension takes one too, [x for x in range(0, 10, 2)], and so does a generator, sum(x for x in range(0, n, 3)), whose step is then a number written in it. reversed(range(...)) and reversed(a) of an array walk backwards.

while (line := next_line()) != "": binds the name at the start of each iteration, then tests it. A list comprehension's filter may bind a name too, big: list[int] = [w for i in range(n) if (w := values[i] * 2) > 5]. See iteration for exact domains, lockstep stopping, generated checks, and matrix traversal.

break exits the innermost loop. continue skips the rest of the body, wherever it is in it: in an if, a try (running any finally on the way) or a match.

A loop's else runs when the loop ends without break: when a while condition is false, or a for loop's source is used up.

for x in xs:
    if x == wanted:
        break
else:
    print("not found")

Put invariant(...), decreases(...), and increases(...) loop annotations at the start of the body before ordinary work. The prover checks the invariant and needs enough facts to retain properties of changed variables. A function's while loop also needs supported termination evidence.

A counting loop needs none: a for over a list, a str or range whose body only increases a local int by literals (n += 1, n += 100 under an if, any amounts) states for you that the int is between its value before the loop and that plus, for each step so far, the most one path through the body adds. So n += 1 for each matching character proves without an invariant, where the steps of a for ch in s loop are not otherwise a name the program could write about. Over a list or a str, such a loop goes by position, the element taken from it, so its body changes neither the element's name nor the list.

A for over the rows of a list of lists whose body grows its row by appends states the same of the rows: those already visited have grown by what one step appends, the others are as they were, so grid[i][j] after the loop proves without an invariant (lists of lists).

Match statements

A match statement has one of two forms:

Family Pattern forms Meaning
Discrete selector Literal or dotted value (Colour.RED), A | B, a capture name, _ Case alternatives over a discrete type; coverage checked
Class or union selector Number(value=n), positional field names, a literal value for a field (Point(x=0, y=y)), _ Type-membership tests, field values compared, and constant local field bindings

A class pattern's selector is a simple name, and its patterns name classes of a union or hierarchy, or the one dataclass the selector is of. A field's pattern is a name, which binds the field's value, or a literal or dotted value, which the field must equal. In the discrete form, a bare name is a capture, as in Python: it matches anything and binds the subject (case k if k < 0:); a value to compare with is a literal or a dotted name, as Colour.RED is. Use _ for the default alternative. A case may take a guard, case p if c:: the case is taken when its pattern matches and the guard holds, and otherwise the cases after it are tried, as in Python. A class pattern's guard reads the fields it binds, case Circle(r=r) if r > 10:.

match token:
    case Number(value=n):
        return int(n)
    case Mark(value=n):
        return int(n)
    case _:
        return 0

This function-body excerpt is from the reference project's declared Token union. Bound field names are local constants, not writable aliases into the matched object. Unions are described under classes.

Returns, calls, and no-op statements

return expression supplies the declared result; return is used for a no-result operation. All control paths must satisfy the result/termination rules. A scalar result is a value; a collection result is built in place, as described under collections.

A call to a function returning None is a statement. Any other expression by itself does nothing and is rejected (the REPL, unlike a file, prints it). pass does nothing. A string by itself is documentation and is not evaluated.

assert condition is a condition to prove there, and so is assert condition, message. The message is no part of what is proved; it is computed only when the assertion fails (in a build that keeps assertions, --no-prove or --advisory), and the failure's report ends with it. It is any value str() takes; computing it must not fail where the assertion is false. assume(condition) is a trusted assertion, with a warning; it does not prove the condition. requires, ensures and raises are contracts at the start of a function body only.

Exceptions and resource release

raise E, raise E(), raise E("message"), bare reraising inside a handler, and try/except have the rules in contracts and exceptions. A try statement may also have Python's else, run when its body ends without an exception (outside the handlers), and finally, run however the statement is left: normally, by an exception (which then goes on), or by return, break or continue (the value a return gives is the one it had before finally ran). A finally itself does not return, break or continue (B0401): that would drop the exception it may be running for.

try:
    total = parse(text)
except Malformed:
    total = 0
else:
    print("parsed")
finally:
    print("done")

Context managers and with

A dataclass with __enter__(self) and __exit__(self, exc_type, exc, tb) is a context manager, and with runs it as Python does: with m as x: calls m.__enter__(), binds x to its result, runs the body, and calls m.__exit__(...) however the body ends. At its end, and when it leaves by return, break or continue, the three arguments are None (and what __exit__ returns is not used); when it raises an exception, they are its name, its message and None, and the exception goes on unless __exit__ returns True, which suppresses it (the statement after the with runs next). An exception that __enter__ raises goes on without __exit__. with a as x, b as y: is with a as x: around with b as y:, and as x may be left out.

@dataclass
class Session:
    name: str
    open: bool = False

    def __enter__(self) -> Session:
        self.open = True
        return self

    def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: object) -> bool:
        self.open = False
        return exc_type is not None and str(exc) == "retry"


def work(s: Session) -> None:
    with s as session:
        print(session.name, session.open)

Vibe types __exit__'s parameters as it can: whatever their annotations (Python's are type[BaseException] | None, BaseException | None and TracebackType | None), each is a str | None. The first is the exception's name as Ada.Exceptions.Exception_Name gives it (MAIN.REJECTED, not Python's class), the second its message (what str(exc) gives in Python too), the third is always None; all three are None when the body ended without an exception. Its result is a bool, and one that returns None (or nothing) never suppresses. __enter__ and __exit__ may change their object and print, as procedures do. __enter__ returns self, or says what it returns (-> Handle). When it returns self, the name is the manager, as Python's is the same object: what the body does to x the manager has when __exit__ runs, and what __exit__ does x has after the statement. A manager written as a name (with session:) is that object, not a copy.

A class with only one of the two methods, __enter__ with parameters after self, or __exit__ without exactly three, is B0401, and so is a target that is not a name; a with statement's object of a class with neither is B2001. A failed run-time check is not an exception (see contracts and exceptions), so it stops the program without running __exit__, as it stops a finally.

Owned objects and containers need no context manager: they are released when they end, by the language's ownership rules.

del owner frees an owned object (one whose type admits None) and leaves the owner null; it is Vibe's only use of del. Deleting an Owned[T] that is never null, or a list's or a dict's element (del d[k]), is B0401; x: T = xs.pop(i) takes a list's element out. See sharing and ownership.

Source evidence: statement parser, with statements, local/view/control-flow lowering, and shared statement checks.