Skip to main content

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.

info

The guide explains how to use Vapour, with examples, this page aims to be complete and precise.

1. Source files​

  • Vapour files use the .vp extension 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​

LiteralExamplesType
Integer1, 1L, 0x10, 1e3int
Float1.5, 1e-3, 2.5e2num
Complex1i, 2.5icomplex
String"hello", 'hello'char
Booleantrue, falsebool
NullNULLnull
MissingNA, NA_integer_, NA_real_, NA_character_, NA_complex_any vector type
SpecialInf, NaNnum

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 to c(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 mixes int and num, write (1.0, 2.5) instead.
  • A range is written with ..: 1..10 transpiles to 1:10.

2.6 Operators​

KindOperators
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​

TypeR equivalent
intinteger
numnumeric (double)
charcharacter
boollogical
complexcomplex
rawraw
dateDate
posixctPOSIXct
posixltPOSIXlt
nullNULL
anyanything

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.

DeclarationCreatesArguments when constructed
type id: intalias of a type expressionvalue
type l: list { int | char }listunnamed
type o: object { a: int, b: char }named listnamed
type d: dataframe { a: int, b: char }data.framenamed
type s: struct { int, a: char }structureone unnamed, then named
type m: matrix { num }matrixunnamed
type f: factor { char }factorunnamed
type e: environment { a: int }environmentnamed
type ps: []personlist of personunnamed
type cb: func(int, int) intfunction 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:

RuleExample
S and T are the same typechar to char
S is int and T is numlet x: num = 1
T is a union that contains Sint to int | char
T is anyanything to any
T is an alias and S is the aliased type1 to userid
The value is NANA to anything

Otherwise the assignment is an error, in particular:

  • num cannot be assigned to int.
  • An alias cannot be assigned to the aliased type: userid to int.
  • A union cannot be assigned to one of its members: int | char to int.
  • any can only be assigned to any.
  • NULL can only be assigned to a type that includes null.

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.
  • let declares a mutable variable, its value is optional.
  • const declares 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_expr declares variadic arguments.
  • A parameter name must be unique.
  • A function must return a value of its return type, unless its return type is null.
  • 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.

DecoratorApplies toArguments
@genericmethod on any, without bodynone
@defaultmethod on anynone
@class(a, b)typeclass names, overrides the default class
@matrix(...)matrix typenrow, ncol, byrow
@factor(...)factor typelevels, labels, exclude, ordered, nmax
@environment(...)environment typehash, parent, size

Any other argument is an error.

5. Statements​

5.1 Assignment​

StatementMeaningR
x = valueassign to xx = value
x <- valueassign to x in a parent scopex <<- value
x += valueadd to xx = x + value
x -= valuesubtract from xx = 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.
  • if can be used as an expression: let x: int = if(a) { 1 } else { 2 }.
  • The loop variable of a for loop is declared with let and a type, the expression must be iterable: a vector or a list type (list or []), e.g.: a struct cannot be iterated.
  • The type of the loop variable must match the type of the elements.

5.3 Return and defer​

  • return expression returns from the enclosing function.
  • defer (): null => { ... } runs the anonymous function when the enclosing function exits, it transpiles to on.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 func type 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 int and num returns num, otherwise arithmetic operators return the type of their operands.
  • %in% returns bool.
  • 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​

VapourR
let x: int = 1, const x: int = 1x = 1
(1, 2)c(1, 2)
1..101:10
true, falseTRUE, 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): anyf = function(x, ...) { UseMethod("f") }
@default func (x: any) f(...)f.default = function(x, ...) { ... }
x <- 1x <<- 1
x += 1x = x + 1
defer (): null => { ... }on.exit((function() { ... })())
o(a = 1) where type o: objectstructure(list(a = 1), class = c("o", "list"))
s(1, a = 2) where type s: structstructure(1, a = 2, class = "s")
d(a = 1) where type d: dataframestructure(data.frame(a = 1), names = c("a"), class = c("d", "data.frame"))
e(a = 1) where type e: environmentstructure(list2env(list(a = 1), envir = new.env()), class = c("e", "environment"))
type x: intnothing, 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
  • ? help
  • raw literals
  • nested inline types, e.g.: an object declared inside an object

Known issues:

  • naming a type after an existing S3 class, e.g.: person from utils, makes R dispatch that class's methods (e.g.: $) on your objects