DEVELOPMENT EDITION · 769442725406
Varc syntax
On this page

Varc units, subprograms, generics and contracts

Imports, units and package extraction

A source file can contain context clauses followed by a library package or subprogram. A conventional package is one .va file named after its unit:

import Ada.Text_IO;
package Counters {
    pub fn next(value: Natural) -> Natural
        requires value < Natural::Last
        ensures result == value + 1
    {
        return value + 1;
    }
}

import P; makes the dependency available. use P; exposes suitable package declarations without repeating P.; use type T; and use all type T; expose the corresponding supported operations. private import P; makes P available to the package's hidden declarations and implementation only. limited import P; is accepted where it forms no cycle and means import P;. See program structure.

A package can also have imports inside it. Extraction determines whether an import is needed by the public specification or only the implementation; a hidden implementation dependency need not become public solely because it occurs in the same file.

pub exposes a declaration to clients. No visibility prefix keeps it hidden. pub(child) places a declaration in the supported child-visible private interface. Nested packages and generic packages use the same item visibility mechanism; a generic's formal list comes first and its visibility after it, generic<type T = private> pub fn ....

The compiler extracts package specification/body units, public declarations and private representation from this source. init { statements } contains package elaboration actions. It accepts statements only; declare package objects outside the init block. Their initialization and the init actions must satisfy elaboration/flow/proof rules.

A standalone main is normally:

import Ada.Text_IO;
fn main() {
    Ada.Text_IO.Put_Line("Hello");
}

The main must have the supported parameterless procedure profile. Project discovery and entry selection follow the Toolchain Manual. A braced package is not itself a function called when imported.

A file may declare functions, types and data enums beside the function named as the file (main in main.va): they are nested in it, before its own declarations, and the file's imports cover them all, as a Vibe module of functions is its main. A declaration uses only those before it.

Function and procedure profiles

fn clamp(value, low, high: Integer) -> Integer;
fn increment(value: inout Natural);
fn find(key: Integer, found: out Boolean, position: out Natural);

fn declares either a function (with -> Result_Type) or a procedure (no result arrow). Names sharing a type can be grouped with commas before :. Parameter groups also use commas. Modes are in, out and inout; omitting one means input.

A parameter can have a default = expression and supported aliased/not null properties. Defaults are part of the interface, and omitted actuals still need valid typed/effect-safe evaluation. An out or inout actual must be writable and marked with & at a call. Returning a value from a no-result procedure is invalid.

var before a parameter makes it the body's own copy, which the body may assign while the caller's value stays as it was: fn halvings(var n: Natural) -> Natural.

A normal body uses braces. A declaration with no implementation ends with ;. An expression function uses = expression;:

fn twice(value: Integer) -> Integer
    requires value in -1000..=1000
    ensures result == value * 2
= value * 2;

Null procedures use = null; and abstract operations = abstract; in legal contexts. Renamings use renames Name;; the name may be an operator, renames operator+ or renames P.operator+, or an enumeration literal for a function of no parameters, and a call through a renaming uses the renaming's own parameter names and defaults. A generic formal function's default may name an operator likewise (fn Join(X, Y: String) -> String = operator++). override fn requires a genuine override; !override fn asserts that the operation is not an override.

An operator declaration uses fn operator+(...) -> T or the relevant supported operator spelling. This names an operation of the nominal types; it does not change the language's precedence table.

Methods and impl blocks

impl Point {
    pub fn x_value(self) -> Integer = self.x;
    pub fn move_x(self: inout, delta: Integer) {
        self.x += delta;
    }
}

This is a declaration fragment assuming Point and appropriate arithmetic contracts. The receiver's type comes from impl Point. self without a mode is input; self: inout permits supported component changes. The block groups primitive operations at the package location; it is not a runtime class object or a place for arbitrary fields.

Method calls use the supported receiver form. Contracts and mutable nonreceiver parameters remain explicit. Methods are not general extensions that can bypass private visibility, ownership or dispatch rules.

Contract clauses

Contracts follow the profile and precede the body/=/terminating semicolon:

fn add(value: inout Natural, amount: Natural)
    requires amount <= Natural::Last - value
    ensures value == old(value) + amount;

requires and ensures are contextual words. result denotes a function's result only in the appropriate function-contract context. old(expression) captures a permitted entry value; it is not an arbitrary snapshot call in ordinary executable code.

cases gives guarded contract cases:

fn absolute(value: Integer) -> Natural
    requires value > Integer::First
    cases {
        value >= 0 => result == value,
        others => result == -value
    };

This is a specification fragment needing an implementation. It carries case coverage and consequence obligations, not imperative fallthrough behavior.

decreases expression on a profile denotes a recursive subprogram variant. The statement form with a semicolon denotes a loop variant; position determines its category.

throws E | F declares allowed propagated exceptions without a stronger consequence. The structured form supplies consequences:

fn withdraw(balance: inout Natural, amount: Natural)
    ensures balance == old(balance) - amount
    throws {
        Insufficient_Funds => balance == old(balance)
    };

The exception must already be declared. Normal return and exceptional propagation have different contracts and state-copyback rules. Only procedures (an fn without a result) declare throws; see the shared exception rules.

Annotation and pragma forms

Annotations follow a declaration head/value in their allowed position:

fn reset()
    @Global(Output => Count)
    @Depends(Count => null)
    @Always_Terminates;

They are not runtime decorators. A single positional annotation argument is its value; multiple/named arguments form the supported aggregate value. Named annotation associations can use => or :. Marker annotations omit parentheses, for example @Ghost.

A class-wide aspect is @Pre::Class(condition) or @Post::Class(condition) in the appropriate operation. Other class-wide aspect kinds are excluded.

The same @Name(arguments); form as a standalone declaration/statement is a pragma. Convenient forms include assert condition;, assume condition;, invariant condition; and decreases measure;. A ghost declaration can use the ghost prefix. The aspect and pragma catalog gives every name and its effect.

Generic units

A generic formal list precedes a package or subprogram:

generic<type Item = private>
fn choose(first: Boolean, left, right: Item) -> Item {
    if first {
        return left;
    }
    return right;
}

This is a library generic unit; a generic can also be declared as an item of a package, its formal list again first and then the item with its visibility:

package Choosers {
    generic<type Item = private>
    pub fn choose(first: Boolean, left, right: Item) -> Item {
        if first {
            return left;
        }
        return right;
    }
}

pub generic<...> fn reads the same. Type parameters after the name say the same more briefly, as Rust writes them: each is a private type, and Ordered also takes its <:

fn choose<T>(first: Boolean, left, right: T) -> T = if first { left } else { right };
fn larger<T: Ordered>(a, b: T) -> T = if a < b { b } else { a };

A call infers the instance from its arguments' types, larger(4, 9), for a procedure too. Formal items are comma-separated inside <...>:

Formal Source pattern
Discrete type type Index = (<>)
Signed/modular/float/fixed type type T = range <>, mod <>, digits <>, delta <>
Private/limited/array/derived/access type Corresponding supported type definition
Input object const N: Positive, optionally = default
Mutable formal object var State: T in the permitted category
Operation fn less(l, r: T) -> Boolean = <>
Package package P = new G<> or explicitly constrained actuals

<> requests a matching default in the applicable formal context. Named operation defaults and supported null procedure defaults are also available. Formal declarations do not acquire all of C++'s template/metaprogramming features.

Explicit instances use:

package Numbers = new Verada.Containers.Formal.Vectors<Integer, 10>;
fn choose_integer -> _ = new choose<Integer>;

Generic actuals can be positional or named using the supported Name: value associations, for example Vectors<Integer, Capacity: 10>. The > closes the actual list, so parenthesize an actual expression whose comparison would otherwise be mistaken for that delimiter.

A procedure instance omits the -> _ marker: fn action = new Generic_Action<Integer>;. The marker identifies the instance category without restating its concrete result type.

A generic package instance can be named implicitly at its use: Verada.Containers.Formal.Vectors<Integer, 10>.Vector. The frontend creates a suitable instance per supported generic/actual combination. Actual inference at generic calls is limited to information available from supported argument types, not an unconstrained whole-program search. Nominal instance identity and cross-module restrictions are in shared generics.

Split bodies, subunits and low-level unit forms

Normal Varc uses one package file, but translation can produce a separate package body P { ... }. Its executable elaboration goes in init { ... }. package P separate; and fn worker(...) separate; are body stubs in the supported parent arrangement. A subunit starts with separate(Parent) followed by its declaration/body. A private child unit uses private package Parent.Child { ... }.

These forms preserve supported unit structure; they are not text inclusion. Do not duplicate a full extracted public definition in two files merely because the low-level forms exist.

Foreign boundaries and state models

C imports/exports use ordinary profiles with @Import, @Export, @Convention(C) and @External_Name("symbol") where supported. @Global/@Depends declare effects; package annotations such as @Abstract_State and @Initializes model hidden state and elaboration.

The C implementation of an imported operation is trusted under its contract. An exported operation's proof does not prove that arbitrary foreign callers respect it. Representation, arrays, strings and callbacks at the ABI boundary have explicit compatibility restrictions.