Repository navigation
i. Overview
Convention is Hello, Black Mage!
print("Hello, Black Mage!")That's it. That's a complete Vivi program, you don't need a main() loop. The script doesn't even need to be called main.vivi, running vivi . from the project root will tell Vivi to find the first available script in the directory. Vivi does search for and use a main.vivi and a main() entrypoint if they're available, but it doesn't need it.
The reason print() works is because it's included in a _base.vivi library that's auto loaded on every program.
Note
Important: Vivi is not a no ; language. Semicolons optional and useful in single line statements.
Type annotation is entirely optional, meaning you can just declare a variable and Vivi will determine what type it is automagically through its inferrence system.
foo := "bar" // bar is inferred as a stringIf you prefer explicitness, or if Vivi is reading something wrong, you can introduce type annotation into your program.
i32 foo := 1 // i32 is a 32-bit integerYou can do a bare declaration like so, leaving the value null:
i32 fooThere's a few options for type coersion/casting, and some escape hatches for operations in string literals as well.
foo :: "string"
bar :: 10
i32(bar) // Typecast to an i32
string(bar) // Typecast to a string
foobar :: foo ~ bar // ~ is the concatenation operator
// Output: string10
// String interpolation, +-*/% is always math, ~ is always concatenation
print("{bar + bar}, {foo~bar}")
// Output: 20, string10
x := 10
y := "11"
z := x + y
// Output is 21, y was coerced into an intUse = to reassign a value. Variables must first be declared before reassignment.
i32 foo // or i32 foo := 0 to give it a default value
foo = 5Typically in languages that use this syntax (Jai, Odin, Zig), :: is immutable comptime declaration, and when used top level is order independent. Since Vivi doesn't really have a traditional "comptime", :: is proctime sugar for immutable declaration, whereas := is sugar for mutables. You can think of them as the exact same thing though, since they functionally operate the same.
Types:
rune // Same as a char
string // Native string type
bool // 0/1, true/false
i8, i16, i32, i64 // Signed integer, no "long" type yet
u8, u16, u32, u64 // Unsigned integer
f32, f64 // Doubles, true floats are hard to implementYou can alias a type easily by assigning a variable to that type. int and float are default aliases.
int := i32
float := f32in, not, and, or are also implemented, with not/and/or being alternatives to !=, &&, ||. in is a keyword used to see if a value is in an array/struct. Python's not in is on the todo list.
On top of that, there's also the typical =, ==, !, +, -, *, /, %, +=, -=, *=, /=, %=, ++, --, x?y:z (ternary), .. (slice), | (union), >, >=, <, <= as well as some bitwise operators &, | (fallback operator, and doubles as bitwise or on context), ^, <<, >>, ~, ~= etc.
~ Is used for concatenation,, and you can additionally use ~= to avoid the verboseness of something like
string a := "Thing1"
string b := "Thing2"
a = a ~ b // Thing1Thing2
// Use ~= instead
a ~= b // Same result, Thing1Thing2Vivi has 4 different comment styles, use whichever one you want.
#
;;
//
/* ... */Arrays work like Lua tables, the one thing I actually do like about lua. They're 0 indexed and can nest.
t := [] // Empty array instantiation
t := ["apple", "banana", "orange"] // Populate an array
t[0] // Returns apple
t := ["key": [1, 2, 3], 4, 5] // Populate a nested array
t[0] // 4
t[1] // 5
t["key"] // [1,2,3]
t["key", 0] // Chains into the first index of "key" (1), works for nests
t[0, 1] or t[x, y] // Call by index or with another var for index/value
t["key"].add(0, val) // Insert val at specified index
t["key"].take(0) // Removes the specified entry
t["key"].push(val) // Pushes val at the end of "key":[1,2,3] to become [1,2,3,val]
t["key"].pop() // Removes last entry
t["key"].sort() // Sorts sequentially
t.empty() // Dumps everything from t, resizes to 0
i32[10] t // Sized array decl
i32[10] t := 0 // Scalar initializer fills every slot with a copy of it
i32[10] t := [1,2,3] // Array initializer also fills every slot (whole array, deep-copied per slot) — not spread across indicesi32 *p := &x // Pointer decl, init from an existing value's address
Vec2 *vp // Bare pointer decl, pointee type checked on later assignment
&x &arr[0] &v.field // address-of a variable, array element, or struct field
p* // Dereference read
p* = 6 p* += 4 // Dereference write, mutates in place, all compound ops
p = &z // Rebinds p itself, different statement entirely from p* = 6
vp.x vp.x = 42 // Auto-deref on field access through a pointer-typed variable
p == q // Pointer identity, true when both address the same slot
q := p // Copying a pointer copies the address -- both reach the same slotTo work through a pointer, keep the pointer and deref at the point of use. Dereferencing into a binding gives you a duplicate, because := copies arrays/structs like any other assignment:
ap2 := ap // auto deref at point of use
_set(ap2*, 0, 9)
copy := ap* // writes into a duplicate, original untouched
_set(copy, 0, 9)Scalars are unaffected. y := p* on an i32 copies the int, which is what you want.
Enums are auto enumerated structs in the back end, but they function like regular enums. If no values are supplied to any member, or all values are signed/unsigned ints, Vivi infers it as an enum without needing the keyword.
Color :: { // Auto-increment from 0 or explicit values
Red,
Green,
Blue
}
Color.Red // 0
Color.Green // 1
Color.Blue // 2If needed, you can force a type for all members of an enum by supplying a type first. Again, enum is optional and Vivi will infer if you declare an enum like an enum.
u32 thing := {
m,
n,
o
}Implicit selectors are enum literals. Proctime sorts and evaluates enums so that you can access their members without their name. They also resolve early in proctime, so they're order independent. They don't have to be capitalized, but it's an easy way to keep track of them.
early :: .HARRY
enum Names :: {
TOM,
DICK,
HARRY
}
a :: .DICK
b := .TOMIf you try to access a selector that exists in multiple enums, runtime will crash cus it can't resolve two names. eg:
[ERROR] Enum Error in main.vivi
1 | enum Names { Tom, Dick }
2 | enum Cats { Tom, Felix }
3 | x := .Tom
| ˆ '.Tom' matches more than one enum.A Vivi original
u32 {
a := 1
b := 2
c := 3
}Like enums, the struct keyword is optional. Vivi will infer it as a struct if you use it like one.
struct Vec2 := { // Typedef type constructor
i32 x: 0, // Type declaration is optional, interpreter will infer
i32 y: 0
}
v := Vec2(10, 20)
v.x = 10
v.y = 20
// Struct/array assignment is copy on assign by default
a := Vec2(1, 2)
b := a
b.x = 99
print(a.x) // 1
print(b.x) // 99, copies from source but mutablestuff := {
a: "blep",
fn: () {
print(self.a)
}
}
stuff.fn() // returns "blep"if () {...}
if () {
...
} else if () {
...
} else () {
...
}if x print("y")Returns a value without a return keyword
msg := if hp > 50 { "good" }
else if hp > 20 { "bad" }
else { "almost dead" }while true {...}
i := 1
while i < 100 {
i++
}for 0..10 {...} // .. Slices, 0 to 10
for 0..var {...}
for i := 0; i < 10; i++ {...} // C Style
for i, name in array {...}
for v in array {} // values only, no index
for i in 0..n {} // named var bound to each int in the range
for key, value in struct {
print("{key} = {value}")
}Copped from Jai, they use it/it_value, Vivi uses i/ix for simplicity. There is no depth checking, so nested for loops don't check i/ix.
i is the index the for loop reads from the provided list. ix is the index's value. ix semantics are write through, meaning a change to ix reflects on the value that's intended to be edited in the actual thing you're looping over.
for Names {
println(i) // Prints the index
println(ix) // Prints the value
}for i := 0; i <= 10; i++ {
if i == 5 continue
for j := 0; j <= 10; j++ {
if j == 5 break
}
}local // eg: local i32 x := 0 <-- bound in {} scopes, discarded when exited
static // eg: static i32 x := 0 <-- declare once, ignore redeclarations, typical static behaviorswitch x {
default:
"1":
...
2:
...
}
// Slices in switch statements cus idk why no lang has thought of that
switch x {
0..3:
...
4:
...
}
// Fallthroughs
switch x {
1:
print("blep")
fallthrough // contniues to 2
2:
print("fell through")
}
switch x in arr {
1:
2:
}Vivi also has experimental support for Jai style if cases. These are NOT up to Jai spec, if you port code from Vivi to Jai, expect to refactor some if cases. I don't even know what Jai is calling these, I assume switch or if case.
if x == {
1: ...
2: ...
default: ...
}
// Jai switches even work for something weird like this
if Point(1, 2) == {
Point:
println("type match Point")
default:
println("not a point")
}
// They also work for `in` cases
if n in [1, 2, 3] == {
2:
println("switch in: member 2")
default:
println("nope")
}A proper assert() function is going to be added eventually. For now, Vivi has type matching and panic() if you need it.
x := "blep"
if (x == string) {
print("x is a string")
}
switch x {
i32: // Int
f32: // Float
string: // String
default: // Unchecked type
}try {
// do something
} catch (err) {
print(err) // Prints error and proceeds normally, doesn't crash unless panic() in catch
}Last in, first out, go style. Future updates will allow for a deferred block statement.
defer fn()Note
Defer currently doesn't capture its environment, so there's a lot of issues with top level defers and defers in imports right now.
name :: () {...}name := () {...}Simply called like so, will autofire.
(){}name :: (a := "test", b := 1) {...}name :: (f32 x, rune y) {...}You can mix type annotations with default arguments
name :: (f32 x := 1.0, rune y := "a") {...}Functions are annotated for their return type and are optional. Use void for no return type. If a return type is declared, that type is enforced in the actual function return. You can also define a custom return type, like a Vec2.
bool name :: () {
return true
}Use [] to create an array of return types. This is experimental and will be expanded in the future.
// Currently limited to 2 for testing
[i32, i32] name :: () {
return 1, 2
}
// Fallback
[i32 | string] name :: () {
return "hi" // If not given an i32, it accepts a string
}[i32, i32] divmod :: (a, b) {
return a / b, a % b
}
x, y := divmod(7, 2) // x = 3, y = 1
Point := { x: 10, y: 20 }
px, py := Point // px = 10, py = 20Functions embedded into other functions are private by default, but lazily and can be accessed externally. This is experimental and may be deprecated in future versions.
pub :: () {
priv := (){} // priv is private to that call frame, not visible by bare name outside it
}
pub().priv() // chained call reaches the private fn from that specific invocation
h := pub(); // same access through a stored reference, not copy
h.priv()Closures made inside a loop capture that iteration's value, and use Go's fix. This one isn't fully tested so I'm not comfortable saying this works perfectly yet.
fns := []
for i := 0; i < 3; i++ {
fns.push(() { return i })
}
print(fns[0]()) // 0
print(fns[1]()) // 1vivi . --int="2"
void main :: (argc, argv) {...}
// Variable "int" with a value of 2 accessible in argvUse ... to signal variadics to Vivi. argc and argv are implicit in variadics.
void f :: (...) {
print("arg count: " ~ argc)
for 0..argc {
print("arg value: " ~ argv[i])
}
}Variadics can be annotated to make all values in that variadic the specified type.
void f :: (i32 ...) {...}To pass args around, use the args keyword, which is interchangeable with argc and argv.
variadic :: (...) {
passthrough(args)
}
passthrough :: (...) {
println(argc) // or args[0]
for i := 0; i < argc; i++ {
println(argv[i]) // or args[1][i]
}
}You can define a method as a chained accessor using the #method directive.
Methods use an implicit self to mutate the variable the method is acting on, and can be promoted to and demoted from a method on reassignment. self does NOT mean these are objects, it's just self referential shorthand.
Parentheses are also optional if the method doesn't take any arguments.
eg: var.double() can be used as var.double if #method double takes no arguments.
#method double :: () {
return self *= 2
}
#method add :: (n) {
a := self
return a += n
}
a := 5
a.double // a is now 10, parens optional if no argument is needed
a.add(3) // a is now 13
a := 1
a.double // acceptable, returns 2
b := 5.double // acceptable, returns 10
test :: () {
return 5
}
test().double // Should parse as (test()).double and return as 10
test.double // Runtime error, function values have no methods
// This SHOULD work, but struct return types aren't tested
struct test :: () {
return struct {
i32 x: 0,
i32 y: 0
}
}
test().x.double // Parse error because x would be a private variable
a := test() // Do it like this
a.x.doubleExamples
arr := [(){...}, (){...}] // array of handlers / dispatch tables
actions[Op.Update]() // enum index into dispatch table
{log: (msg){...}, warn: (msg){...}} // struct method fields / mixin building
each(arr, (x) { print(x) }) // passed as argument to higher-order functions
map(arr, (n) { return n * 2 }) // map/filter/reduce via fn args
log := if debug { (m){print(m)} } else { (m){} } // if-as-expression yields fn values
tasks := [(){return compute()}]; tasks[0]() // lazy/deferred computationNote
:: hoisting is currently broken on imports, but they should still import and execute linearly and work more or less as expected. If you encounter undefined errors, this is why.
Vivi differentiates standard library imports with project level imports if it detects (*/)*.vivi in the string. Vivi's standard library is included from /lib/core.
Import the standard library with as Uppercase.
The current sstandard library includes:
Io, Sys, Math, Time and Strings. _base.vivi is autoloaded into every program, no need to import it.
#import "Io"
#import "libs/test.vivi"All libraries are imported flat with global scope unless the "as" keyword is used
#import "Strings" as sNo function overloading, but you can shadow library functions locally, or you can just hack it/patch it/delete it/replace it. I literally don't care how you use it, the core libs aren't sacred.
#import "Math" as math
// eg: math.pow()
math.pow = () {
// whatever
}Phrases are used for grammar extension.
#phrase [ret] name :: (sig) { body }
#phrase i32 inc :: (i32 x) { return x + 1 }
#phrase unless :: (cond, block body) { if !cond { return body } }
unless COND {...}A missing body is a parse error and produces no declaration.
Phrases must be top level, defined as const, and are hoisted through proctime.
#!/usr/bin/env vivi
vivi <...> -lex Outputs the lexical analysis.
vivi <...> -ast Outputs the AST tree.
vivi -v To print out the Vivi's version.