Language specification
This is the specification of the Vapour language as implemented on the development branch, see the changelog for changes since the last release. It describes what the language accepts, how it is checked, and what it transpiles to.
Limitations of the current implementation are listed at the end.
The guide explains how to use Vapour, with examples, this page aims to be complete and precise.
1. Source files
- Vapour files use the
.vpextension and are UTF-8 encoded. - When transpiling a directory, files are read recursively in alphabetical order of their path and treated as a single program, a name must be declared in a file that comes before the files that use it.
- Statements are separated by a new line or a semicolon (
;).
2. Lexical elements
2.1 Comments
A comment starts with # and runs to the end of the line.
Roxygen2 comments (#') are comments, they are copied as-is to the R output.
2.2 Identifiers
Identifiers follow R's rules: letters, digits, . and _, not starting
with a digit, e.g.: x, my_var, my.var.
Backtick-quoted identifiers (`my var`) are not supported.
2.3 Keywords
let const type func return defer
if else for in while repeat break next
true false
2.4 Literals
| Literal | Examples | Type |
|---|---|---|
| Integer | 1, 1L, 0x10, 1e3 | int |
| Float | 1.5, 1e-3, 2.5e2 | num |
| Complex | 1i, 2.5i | complex |
| String | "hello", 'hello' | char |
| Boolean | true, false | bool |
| Null | NULL | null |
| Missing | NA, NA_integer_, NA_real_, NA_character_, NA_complex_ | any vector type |
| Special | Inf, NaN | num |
Strings may span multiple lines and use R's escape sequences, e.g.: \", \n.
Whole numbers are int, e.g.: 1 and 1e3, even though R stores them as doubles,
numbers with a decimal point or a negative exponent are num.
There is no literal for raw, use as.raw().
2.5 Vectors and ranges
- A vector is written with parentheses:
(1, 2, 3)transpiles toc(1, 2, 3). ()is an empty vector,c().- All elements of a vector must have the same type,
(1, 2.5)is an error as it mixesintandnum, write(1.0, 2.5)instead. - A range is written with
..:1..10transpiles to1:10.
2.6 Operators
| Kind | Operators |
|---|---|
| Arithmetic | + - * / ^ %% |
| Comparison | == != < > <= >= |
| Logical | && || ! |
| Custom infix | %name%, e.g.: %in% |
| Assignment | = <- += -= |
| Access | $ [ [[ :: ::: |
| Pipe | |> |
| Range | .. |
: is not an operator, it introduces types.
? is not supported.
3. Types
3.1 Base types
| Type | R equivalent |
|---|---|
int | integer |
num | numeric (double) |
char | character |
bool | logical |
complex | complex |
raw | raw |
date | Date |
posixct | POSIXct |
posixlt | POSIXlt |
null | NULL |
any | anything |
R has no scalars: every base type denotes a vector.
3.2 Type expressions
A type expression is used after a colon (:) wherever a type is expected.
type_expr = type { "|" type }
type = name # base or declared type, e.g.: int, user
| package "::" name # type from an installed package
int | char is a union: a value of either type.
3.3 Type declarations
Types are declared with type, a name, a colon, and a definition.
A type name must be unique and cannot be the name of a function.
A type declared inside a function is only visible in that function.
| Declaration | Creates | Arguments when constructed |
|---|---|---|
type id: int | alias of a type expression | value |
type l: list { int | char } | list | unnamed |
type o: object { a: int, b: char } | named list | named |
type d: dataframe { a: int, b: char } | data.frame | named |
type s: struct { int, a: char } | structure | one unnamed, then named |
type m: matrix { num } | matrix | unnamed |
type f: factor { char } | factor | unnamed |
type e: environment { a: int } | environment | named |
type ps: []person | list of person | unnamed |
type cb: func(int, int) int | function signature | (none) |
The object types (list, object, dataframe, struct, matrix,
factor, environment) can only be used to declare types,
let x: list is invalid.
matrix and factor accept a single type.
Declaring a type also declares a constructor function of the same name,
e.g.: person(name = "John").
3.4 Assignability
A value of type S can be assigned to a variable, argument,
or return of type T when:
| Rule | Example |
|---|---|
S and T are the same type | char to char |
S is int and T is num | let x: num = 1 |
T is a union that contains S | int to int | char |
T is any | anything to any |
T is an alias and S is the aliased type | 1 to userid |
The value is NA | NA to anything |
Otherwise the assignment is an error, in particular:
numcannot be assigned toint.- An alias cannot be assigned to the aliased type:
useridtoint. - A union cannot be assigned to one of its members:
int | chartoint. anycan only be assigned toany.NULLcan only be assigned to a type that includesnull.
Values returned by R functions (anything not declared in Vapour) are not checked and can be assigned to any type. This is by design, inferring types for R functions is on the roadmap.
3.5 Attributes
The attributes of object, dataframe, struct, and environment types
are accessed with $. Accessing or assigning an attribute that is not declared
is an error, as is assigning a value of the wrong type.
$ cannot be used on vector types.
Nested attributes, e.g.: a$b$c = 1, are checked through each declared type.
4. Declarations
4.1 Variables
let name: type_expr [= expression]
const name: type_expr = expression
- Every variable is declared with a type.
letdeclares a mutable variable, its value is optional.constdeclares a constant, it must have a value and a single type (not a union). Only the binding is constant, the attributes of a constant object can be changed.- A variable cannot be declared twice in the same scope.
4.2 Functions
func name(parameters): type_expr {
statements
}
- Parameters are
name: type_expr, optionally followed by= default. ...: type_exprdeclares variadic arguments.- A parameter name must be unique.
- A function must
returna value of its return type, unless its return type isnull. - A function cannot share its name with a type, another function, or a function from base R.
- Functions can be declared inside functions.
4.3 Methods
func (receiver: type) name(parameters): type_expr {
statements
}
A method is a function dispatched on the class of its first argument,
the receiver. It transpiles to an S3 method, name.type.
A generic is declared with @generic and no body,
a default method with @default, both on a receiver of type any.
@generic
func (x: any) area(...: any): any
@default
func (x: any) area(...: any): null {
stop("not implemented")
}
A method on any is only allowed with @generic or @default.
A method can only be defined once per type.
Declaring the generic is optional, e.g.: to add a method to print.
4.4 Anonymous functions
(parameters): type_expr => {
statements
}
Anonymous functions follow the same rules as functions, the braces are required.
4.5 Decorators
A decorator precedes a declaration, on the line before it.
| Decorator | Applies to | Arguments |
|---|---|---|
@generic | method on any, without body | none |
@default | method on any | none |
@class(a, b) | type | class names, overrides the default class |
@matrix(...) | matrix type | nrow, ncol, byrow |
@factor(...) | factor type | levels, labels, exclude, ordered, nmax |
@environment(...) | environment type | hash, parent, size |
Any other argument is an error.
5. Statements
5.1 Assignment
| Statement | Meaning | R |
|---|---|---|
x = value | assign to x | x = value |
x <- value | assign to x in a parent scope | x <<- value |
x += value | add to x | x = x + value |
x -= value | subtract from x | x = x - value |
- The variable must have been declared.
- Constants cannot be assigned.
- With
<-the variable must exist in a parent scope.
5.2 Control flow
if (condition) { ... } else if (condition) { ... } else { ... }
for (let name: type in expression) { ... }
while (condition) { ... }
repeat { ... }
break exits a loop, next skips to the next iteration.
Both must be used within a loop (for, while, or repeat),
a function body starts outside of any loop.
- Braces are required.
ifcan be used as an expression:let x: int = if(a) { 1 } else { 2 }.- The loop variable of a
forloop is declared withletand a type, the expression must be iterable: a vector or a list type (listor[]), e.g.: astructcannot be iterated. - The type of the loop variable must match the type of the elements.
5.3 Return and defer
return expressionreturns from the enclosing function.defer (): null => { ... }runs the anonymous function when the enclosing function exits, it transpiles toon.exit.
6. Expressions
6.1 Calls
Calls to functions declared in Vapour are checked:
- each argument must be assignable to its parameter,
- a named argument must match a parameter,
- there cannot be more arguments than parameters (unless
...is used), - a callback passed to a
functype must match its signature: number and types of arguments, and return type.
Calls to R functions are not checked, apart from the namespace:
for pkg::fn Vapour hints if the package is not installed or does not export fn.
6.2 Operator types
- Comparison and logical operators return
bool. - Comparing values of different types is reported (
INFO), e.g.:"a" > 1. - Arithmetic between
intandnumreturnsnum, otherwise arithmetic operators return the type of their operands. %in%returnsbool.- Other custom infix operators (e.g.:
%>%) are R functions, like calls to R functions their result is not checked.
7. Scope
- Scope is lexical, every function body creates a new scope.
- A variable declared inside a function is not visible outside of it.
- A variable may be redeclared in an inner scope (shadowing).
- Types follow the same scoping rules as variables.
- Referencing a variable that does not exist is a warning, not an error, as it may be defined in R at run time.
- Within a function, a parameter without a default value that is used
without checking
missing()is a warning.
8. Diagnostics
Checks are reported with a severity, only errors prevent transpilation, see diagnostics for the list.
9. Transpilation
| Vapour | R |
|---|---|
let x: int = 1, const x: int = 1 | x = 1 |
(1, 2) | c(1, 2) |
1..10 | 1:10 |
true, false | TRUE, FALSE |
func f(x: int): int { return x } | f = function(x) { return(x) } |
(x: int): int => { return x } | function(x) { return(x) } |
func (x: t) f(): int { ... } | f.t = function(x) { ... } |
@generic func (x: any) f(...: any): any | f = function(x, ...) { UseMethod("f") } |
@default func (x: any) f(...) | f.default = function(x, ...) { ... } |
x <- 1 | x <<- 1 |
x += 1 | x = x + 1 |
defer (): null => { ... } | on.exit((function() { ... })()) |
o(a = 1) where type o: object | structure(list(a = 1), class = c("o", "list")) |
s(1, a = 2) where type s: struct | structure(1, a = 2, class = "s") |
d(a = 1) where type d: dataframe | structure(data.frame(a = 1), names = c("a"), class = c("d", "data.frame")) |
e(a = 1) where type e: environment | structure(list2env(list(a = 1), envir = new.env()), class = c("e", "environment")) |
type x: int | nothing, types exist only in Vapour |
Constants are not locked in R, they are only checked by Vapour.
When transpiling a package (-outdir=R), the declared types are written
to inst/types.vp so that other packages can use them (see packages).
10. Known limitations
Not yet supported:
- backtick-quoted identifiers
?helprawliterals- nested inline types, e.g.: an
objectdeclared inside anobject
Known issues:
- naming a type after an existing S3 class, e.g.:
personfromutils, makes R dispatch that class's methods (e.g.:$) on your objects