Grav v1.14.0

Syntax and keywords

The lexical rules of Grav: how source text is split into comments, names, keywords and literals.

Source files

  • Source files are UTF-8 text with the extension .grav.
  • A file is a list of top-level declarations: functions, classes, structs, enums, interfaces, traits, type aliases, global let/const, namespaces, imports, uses, tests, #defines and inline C blocks. Their order does not matter.
  • A program starts at fn main(), which takes no parameters and returns nothing.

Comments

// to the end of the line
/* anything, across lines */

A // comment directly above a declaration (or at the end of its line) is its doc comment: editors show it on hover.

Statements and line breaks

A statement ends at the end of its line, at a ;, or at a closing }. Use ; to put several statements on one line. A line break does not end a statement when the line ends with a binary operator, a ,, or an opening bracket, so long expressions can be split after an operator.

A statement that starts with * or & (a pointer dereference or address) could be read as continuing the previous line, so end the previous statement with ; in that case:

bump(&c);
*p = 1

Names

Identifiers start with a letter or _ and continue with letters, digits and _. They are case-sensitive. Conventions: UpperCamelCase for types, lowerCamelCase for functions, methods, variables and fields, UPPER_CASE for constants.

Names starting with __ are reserved for the compiler and standard library.

A member may be named by a keyword: after . (or ?., ->), after fn in a class, interface or struct, and as a field's name after a modifier, the position already says it is a name. Locals, parameters, loop and catch variables may also be named type, typedef, trait, match, export or uses (no expression starts with them, and match ( still starts a match); other keywords, and free functions, cannot be names.

grav
import "std"

class Rule {
    public type: string = "regex"
    static fn in(values: Array<string>) -> string { return "in:" + Str.join(values, ",") }
    fn match(s: string) -> bool { return s == self.type }
}

fn main() {
    let r = new Rule()
    print(Rule.in(["a", "b"]))
    print(r.match("regex"))
    print(r.type)
}
Output
in:a,b
true
regex

Keywords

These words are reserved and cannot be used as names:

KeywordMeaningSee
let, constdeclare a variable / a constantValues
fndeclare a function, method, lambda or function typeFunctions
returnleave a function, optionally with a value
if, elseconditionalControl flow
while, doloops
for, inC-style, range and for-each loops
break, continueleave / skip ahead in a loop
switch, match, case, defaultmulti-way branch and pattern matching
class, struct, enum, interface, traittype declarationsClasses
type, typedeftype aliasAliases
abstracta class that cannot be created / a method without a bodyInheritance
extends, implements, usesparent classes, interfaces, composition
constructora class's initialiser
newcreate an object
self, thisthe current object
superthe parent class's constructor or methods
statica member of the class rather than of each object
readonlya field set only in constructors
public, private, protectedaccess control
namespacegroup declarations under a nameModules
exportmark a declaration as public (documentation only)
try, catch, finally, throwexceptionsErrors
async, awaitbackground tasksConcurrency
as, isconversion and type test
sizeofsize of a type in bytesC interop
true, false, nullliterals
int, float, bool, string, voidbuilt-in typesTypes

Contextual keywords

These are special only in certain positions and remain usable as names elsewhere:

WordSpecial where
import, fromat the top level: import "path", import { A } from "path"
useat the top of a namespace or file
testtest "name" { ... } at the top level
deferat the start of a statement
stepin a range: for (i in 0..10 step 2)
finalbefore class or fn
destructorin a class body
operatorin fn operator+(...)
weakbefore a field
autoas a type argument, or let x: auto
anyas a type

The built-in type names long, int8 … int64, uint, unsigned, ulong, uint8 … uint64, byte, double, float32, float64 and binary are also valid identifiers outside type positions.

Literals

KindExamplesType
integer42, -7, 1_000_000, 0xFF, 0b1010int, or long if it does not fit
float3.14, 0.5, 1.5e3, 2.0float
booleantrue, falsebool
nullnullreferences and T?
string"text", "tab\t", "sum=${a + b}", "${x:.2f}"string
raw stringr"C:\dir", r"\d+"string
multi-line string""" ... """ (shared indentation removed)string
raw multi-line stringr""" ... """string
character'a', '\n', '\u{1F600}'int (the code point)
fixed array[1, 2, 3], [[1, 2], [3, 4]]int[3], int[2][2]
collection[1, 2, 3] where a collection is expectedthat collection
map{"a": 1, "b": 2}HashMap<string, int>
structPoint { x: 1, y: 2 }Point
tuple(1, "one")(int, string), the std Pair
lambdafn(x) => x * 2, fn(a: int) -> int { return a }a function type

A leading 0 makes an integer octal, as in C (017 is 15).

Escape sequences

In strings and character literals:

EscapeMeaning
\n \t \rline feed, tab, carriage return
\\ \" \'backslash, double quote, single quote
\$a literal $ (prevents interpolation)
\0 \a \b \f \vcontrol characters
\eescape (27), for terminal colours
\xHHone byte
\u{H...}a Unicode code point, encoded as UTF-8

Raw strings have no escapes.

Interpolation and format specs

${expression} inside a (non-raw) string inserts the expression's text. ${expression:spec} formats it, where spec is [align][+][0][width][.precision][type]:

PartValues
align< left, > right, ^ centre
+always show the sign
0pad numbers with zeros
widthminimum width
precisiondecimals (f, e, %), or the maximum length of text
typed f e % x X o b s

Preprocessor

#define NAME text and #define NAME(a, b) text define macros, which are substituted before parsing. See C interop.

Inline C

%{ ... %} embeds C code: at the top level as declarations, as an expression with as T, or as a statement ending in ;. See C interop.

Edit this page on GitHub