Tetral Language Specification

Technical Specification for the Tetral Language

Table Of Contents

1.Status2.Introduction2.1.Core Principles3.Scope4.Terms, Concepts and Definitions5.Conformance6.Environments6.1.Translation Environment6.2.Standalone Environment6.3.Embedded Environment7.Data Types7.1.The Boolean Type7.2.The Void Type7.3.Integral Types7.4.Floating Point Types7.5.Array Types7.6.The String Type7.7.Struct Types7.8.Enum Types7.9.Variant Types7.10.Interface Types7.11.Class Types7.12.Function Types7.13.Nullables7.14.Type Compatibility And Assignability7.15.Type Conversions7.15.1.Implicit Conversions7.15.2.Explicit Conversions7.16.Type Parameters7.16.1.Identity and Assignability7.16.2.Constraints7.16.3.Use of Type Parameters7.16.4.Inference7.17.Hashing8.Limits9.Language9.1.Identifier Semantics9.2.Overflow/Underflow Semantics9.3.Runtime Errors9.4.Object Lifetimes9.5.Source Text9.6.Syntax Notation9.7.Lexical Elements9.7.1.Keywords9.7.2.Identifiers9.7.3.Constants9.7.3.1.Integer Constants9.7.3.2.Floating Point Constants9.7.3.3.Character Constants9.7.3.4.Predefined Constants9.7.4.Operators9.7.5.Semicolons9.7.6.Comments9.8.Expressions9.8.1.Primary Expressions9.8.1.1.New Expression9.8.1.2.‘Super’ Expression9.8.1.3.‘This’ Expression9.8.1.4.Cast Expression9.8.1.5.Object Literals9.8.1.6.Array Literals9.8.1.7.String Literals9.8.2.Trail Expressions9.8.3.Index Access Expression9.8.4.Property Access Expression9.8.5.Function Call Expression9.8.6.Coalescence Expression9.8.7.Unary Expressions9.8.7.1.Unary Increment Expressions9.8.7.2.Unary Decrement Expressions9.8.7.3.Unary Arithmetic Expressions9.8.7.4.Unary Bitwise Negation Expressions9.8.7.5.Unary Logical Negation Expressions9.8.8.Power (POW) Expression9.8.9.Multiplicative Expressions9.8.10.Additive Expressions9.8.11.Shift Expressions9.8.12.Relational Expressions9.8.13.Equality Expressions9.8.14.XOR Expressions9.8.15.Bitwise AND Expressions9.8.16.Bitwise OR Expressions9.8.17.Logical AND Expressions9.8.18.Logical OR Expressions9.8.19.Conditional Expression9.8.20.Assignment Expression9.8.21.Top Level Expression9.8.22.Loop Condition Expression9.9.Type Expressions9.9.1.Type Name Expressions9.9.2.Type Parameter Instantiation Expressions9.9.3.Nullable Type Expressions9.9.4.Array Type Expressions9.10.Declarations9.10.1.Declaration Modifiers9.10.2.Type Parameter Lists9.10.3.Module Declarations9.10.4.Import Declarations9.10.5.Function Declarations9.10.6.Extension Function Declarations9.10.7.Variable Declarations9.10.8.Struct Declarations9.10.9.Enum Declarations9.10.10.Variant Declarations9.10.11.Interface Declarations9.10.12.Class Declarations9.10.12.1.Class Fields9.10.12.2.Class Constructors9.10.12.3.Class Methods9.10.12.4.Class Access Modifiers9.11.Statements9.11.1.Block Statements9.11.2.Loop Flow Control Statements9.11.3.If Statements9.11.4.Labeled Statements9.11.5.Switch Statements9.11.5.1.Switch Expression9.11.6.For Loop Statements9.11.7.For-Each Loop Statement9.11.8.Do While Loop Statements9.11.9.Regular While Loop Statements9.11.10.Return Statements9.11.11.Yield Statements9.11.12.Assert Statements9.12.Translation Unit10.Intermediate Representation (Bytecode Format)10.1.File Header10.1.1.The STRTABLE Entry10.1.2.The STRDATA Entry10.1.3.The TYPETABLE Entry10.1.4.The FUNCTABLE Entry10.1.5.The INSTRBLOCK Entry10.1.6.The RDATA Entry10.1.7.The MDATA Entry10.1.8.The ADATA Entry10.2.String Pool Table10.3.String Pool Data10.4.Type Table10.4.1.Array Values Inside Entries10.4.2.Arrays, Nullable Definitions and Reference Definitions10.4.3.Function Signatures10.4.4.Structs10.4.5.Enums10.4.6.Interfaces10.4.7.Classes10.4.8.Parameter List Instantiation10.4.9.Imported Type10.5.Function Table10.6.Instructions Block10.7.Data Block10.8.Import List10.9.Export Table11.Bytecode Instructions11.1.General Purpose Instructions11.2.Stack Memory Instructions11.3.Global Memory Instructions11.4.Closure Instructions11.5.Heap Memory Instructions11.6.Function Call Instructions11.7.Foreign Symbol Instructions11.8.Conversion Instructions11.9.Unary Instructions11.10.Binary Instructions11.10.1.Integer-only Binary Instructions11.10.2.Boolean-only Binary Instructions11.10.3.Arithmetic Binary Instructions11.10.4.Comparison Instructions11.10.5.String/Array Instructions12.The Standard Library12.1.The std Module12.1.1.The Result Variant12.1.2.The List Class12.1.3.The Map Class12.1.4.The Set Class12.1.5.Reading Terminal Input, readln12.1.6.Printing to Standard Out, println12.1.7.Reading Environment Variables, getenv12.1.8.Writing Environment Variables, setenv12.1.9.Numeric Parsing Functions12.1.10.Enum parsing, parseEnum12.2.The std::strings Module12.2.1.Creating String Objects From UTF Data12.2.2.String Trimming Functions12.3.The std::math Module12.4.The std::io Module12.4.1.File encoding enumeration12.5.The std::filepaths Module12.5.1.Accessing the current working directory, cwd12.5.2.Accessing the current program directory, pwd12.5.3.Reading a Path’s File Extension12.5.4.Reading a Path’s Base Name12.5.5.Reading a Path’s Directory Name12.5.6.Normalizing paths12.5.7.Path joining12.5.8.Relativizing Paths12.5.9.Absolute Paths12.5.10.Real Paths12.6.The std::reflection Module12.6.1.Data Type Kind, DataTypeKind12.6.2.Tetral Data Type Object, DataType12.6.3.Accessing Type Data, getTetralDataType12.7.The std::json Module12.7.1.Serialization Errors, JsonError12.7.2.Serializing values, stringify12.7.3.Deserializing values, parseJson

1.Status🔗

This document is a work-in-progress and is subject to change and its current state does not represent a final document.

2.Introduction🔗

Tetral, derived the Greek prefix tetra- for “four,” is a scripting language intended to be executed by an interpreter, or virtual machine, and to provide a platform-agnostic execution system. This document will serve as the specification for this language and outline key aspects of its grammar, type system and code execution.

2.1.Core Principles🔗

Tetral is designed with the following 4 core principles in mind.

Statically Typed
Types must be specified and known at compile-time to allow for execution environments to optimize as much as possible and to provide easy readability for programmers.
Platform-Agnostic
As long as an interpreter exists, it shouldn’t matter how the IR was compiled, it should be possible to execute it.
Explicit Null Control
Values should never be allowed to be null, unless explicitly stated to be otherwise.
Memory Safety
Users of the language should not have to worry about freeing or allocating memory manually, and should not worry about the objects they’re using becoming de-allocated as they’re using them.

3.Scope🔗

This document defines the Tetral scripting language (Also referred to as TetralScript, or TetralLang.)

4.Terms, Concepts and Definitions🔗

Source File
A text file containing Tetral source code.
Bytecode / Intermediate Representation (IR)
The compiled representation of Tetral source code. The terms “bytecode,” “IR,” and “intermediate representation” are used interchangeably throughout this document.
Program
A valid Tetral source file or Tetral bytecode file that can be executed by a Tetral execution environment.
Access
To read or modify the value of an object.
Bit
A single binary digit, having a value of either 0 or 1.
Byte
A sequence of 8 bits. The byte is the smallest addressable unit of memory.
Alignment
The requirement that a value of a given type be stored at a memory address that is a multiple of that type’s alignment value.
Padding
Unused space inserted in memory to ensure that a value is stored at a correctly aligned address.
Native
Describes a feature, function, variable, or library implemented in a lower-level language, such as C or C++, rather than in Tetral.
Symbol
An entity that can be referred to by a name. Symbols include, but are not limited to:
  • Functions
  • Structs
  • Enums
  • Classes
  • Local variables
  • Global variables
  • Imported symbols
Namespace
A named scope that groups related symbols. Namespace names are written as a sequence of identifiers delimited by ::.
Simple Name
The name of a symbol as written in a source file, without a namespace prefix.
Fully Qualified Name
The name of a symbol prefixed by its namespace.
Binary Name
The name of a symbol in compiled Tetral IR.
Module
A collection of functions, types, and variables declared within a specific namespace.
Implicit Import
A module that is imported without being explicitly imported by the user. Implicit imports vary by execution environment.
Code unit
An encoded unit of data corresponding to a Unicode encoding.
Code point
A Unicode code point. For more info on codepoints, please see the Unicode Standard.
Character
Unless stated otherwise, this term refers to a code point.

5.Conformance🔗

The key words “shall” and “shall not” indicate requirements. The word “should” indicates a recommendation. The word “may” indicates permission. Text marked as an example or a note is informative and does not state a requirement.

A conforming execution environment shall accept any valid bytecode file and execute it with the behavior this document specifies. It shall reject any invalid bytecode file and report that it is invalid.

A conforming translator shall accept any valid source file and produce bytecode whose execution has the behavior this document specifies for that source file. It shall reject any invalid source file and report the reason. A translator and an execution environment may be part of the same program.

A conforming implementation shall provide the facilities required by the environments it claims to support. (See the next section.)

Behavior that this document does not fully define is implementation-defined. An implementation shall document its choice for each implementation-defined behavior. This document defines no undefined behavior: no valid program shall cause an implementation to access memory outside the objects the program may legitimately reach.

An implementation may impose limits on programs, but shall support at least the minimum values given in the Limits section, and shall report an error if a program exceeds a limit it imposes.

An implementation may provide extensions, as long as they do not change the behavior of any valid program.

6.Environments🔗

The Tetral language may be executed in one or multiple of several contexts, or execution environments.

Depending on the context of the execution/compilation of a Tetral program, the environments used may differ. For example, an embedded program loading a Tetral source file may first use the Compilation Environment and then the Embedded Environment to execute the code, or only the Embedded Environment if loading a bytecode file.

6.1.Translation Environment🔗

The translation environment shall translate Tetral source files into Tetral Bytecode files.

Translation environments only operate on Tetral source files.

6.2.Standalone Environment🔗

A standalone environment is one where a Tetral file is executed as a fully standalone program with a single defined entry point.

A standalone program’s entry point must be defined as a function with the name main and have one of the following signatures:

The standalone environment must also provide full support for the standard library and the importing of external symbols.

Standalone environments must also implicitly import the std and std::strings standard library modules.

6.3.Embedded Environment🔗

An embedded environment is one in which Tetral programs are executed by a native application which embeds a conforming Tetral execution environment. This environment has no pre-defined entry point, nor any predefined libraries that the environment must implement.

Native-level bindings are not pre-defined for embedded environments are defined by the program embedding the Tetral execution environment.

7.Data Types🔗

A data type is a specific unit of memory that holds data in a specific layout to represent some piece of information.

This section defines the data types implementations must support and the kinds of data types that can be declared by users of the language. Additional terminology and information may be defined for each data type in its corresponding section.

Each section will also define the following properties for its data type:

Data types additionally exist in two categories. The first category is value types. When value types are passed to a callable object or assigned, the value is copied to the destination. Reference types, on the other hand, only pass a reference to the data type’s value.

Data types may be referred to more simply as just types.

7.1.The Boolean Type🔗

The boolean data type shall be a value data type which represents a false/true state.

The boolean data type must be represented by a single byte in memory. If the byte’s value is 0, then the boolean value is false, otherwise it is true.

Boolean values shall be default-initialized. The default boolean value shall be false.

A boolean value’s string representation shall be either “true” if the value is not false, otherwise it’s string representation shall be “false.”

Boolean values shall be compared only to other boolean values. A boolean value shall be considered “less than” another boolean value if it’s value is false, and the other boolean value is true. A boolean value shall be equal to another boolean value if both hold the same true/false state.

Boolean values shall be boolean-assignable, the boolean value of a boolean value is the boolean value itself.

7.2.The Void Type🔗

The void data type represents a non-existent value. Used for functions/methods which return no value. This data type shall only be used in specifying the return type of callable objects. No variables, properties or class fields shall use the void data type.

The void type’s string representation shall be “void”. Since the void type must not exist as a value, it cannot be compared to another type, nor shall it be possible to establish equality with any value of any type.

The void type shall not be hashable.

7.3.Integral Types🔗

Integral types shall be value types of varying sizes used to represent whole numbers.

Integral types shall be default-initialized. Each integral type’s default value shall be its equivalent of the value 0.

Each integral value’s string representation shall be its numerical value converted to a base-10 string. If the integral value is signed and is negative, the string representation shall be prefixed with a "-".

Integral value comparability and equality Semantics are stated in the next section.

Integral values shall be boolean-assignable. An integral value’s boolean value shall be true if it’s value is not 0.

The following is a table of the integral types which implementations must support along with the range of values of each integral type.

Table 1 - Tetral Integral Types
Type NameSize and alignmentDescriptionMinimum valueMaximum value
uint81Unsigned 8-bit integer0255
int81Signed 8-bit integer-128127
uint162Unsigned 16-bit integer065535
int162Signed 16-bit integer-3276832767
uint324Unsigned 32-bit integer04294967295
int324Signed 32-bit integer-21474836482147483647
uint648Unsigned 64-bit integer018446744073709551615
int648Signed 64-bit integer-92233720368547758089223372036854775807

7.4.Floating Point Types🔗

The floating-point types shall be value types which hold a numeric value according to the corresponding IEEE-745 standard format.

Floating point values shall be default-initialized. Each floating point type’s default value shall be that type’s 0 value.

Table 2 - Tetral Floating Point Types
Type NameSize and alignmentDescriptionIEEE Format
float32432-bit floating point typebinary32
float64864-bit floating point typebinary64

All floating point types and integral types are collectively referred to as arithmetic types.

All floating point types, integral types and the boolean type are collectively referred to as primitive types.

The string representation of a floating point value shall be locale-independent and use only ASCII characters. The decimal separator shall always be "."

The value NaN shall be represented as “NaN”. Positive infinity shall be represented as “Infinity” and negative infinity as "-Infinity". Positive zero shall be represented as “0.0” and negative zero as "-0.0".

For any other value, let D be the shortest sequence of decimal digits that uniquely identifies the value among all values of the same floating point type. If several sequences of that length qualify, the one closest to the exact value shall be used. A negative value shall be prefixed with “-”.

If the absolute value is at least 1e-3 and less than 1e7, the digits of D shall be written in plain decimal notation with at least one digit on each side of the decimal separator (for example “3.0”, “0.001”, “1234.5”).

Otherwise, the value shall be written in scientific notation: the first digit of D, a “.”, the remaining digits of D (or “0” if there are none), the letter “e”, and the decimal exponent, prefixed with “-” if negative, with no plus sign and no leading zeros (for example “1.0e7”, “1.5e-7”).

Arithmetic values shall only be compared to other arithmetic values. An arithmetic value shall be considered less than another arithmetic value if and only if the numeric value it represents is lesser than the other value’s represented numeric value. An exception to this comparison rule shall be NaN values. NaN values are never lesser, greater or equal to another arithmetic value.

Arithmetic value equality shall only be established between any two arithmetic values. An arithmetic value shall be equal to another if it’s represented numeric value is equal to the other arithmetic value’s represented numeric value. Positive and negative zero floating point values shall be equal. An exception to this rule shall be the NaN (Not-A-Number) value. A NaN value shall never be equal to another arithmetic value, not even to another NaN value.

Floating point values shall be boolean-assignable. A floating point value’s boolean value shall be true if it’s value is not positive 0 or negative 0.

Floating point values shall be hashable. Positive zero and negative zero are equal and shall have the same hash value.

7.5.Array Types🔗

Array types shall be a kind of reference type which hold a sequential list of a specific data type.

Each unit of data contained in an array shall be referred to as an “element,” and the amount of items the array holds shall be called its “length.” If an array has a length of 0, it is referred to as an “empty” array and an array with a length greater than zero shall be considered “non-empty.”

The data type contained by an array type shall be referred to as its component type.

Arrays are an indexable type. Array types shall be accessible with an indexer value of any signed or unsigned integral type. The indexed type of an array shall be its component type.

Arrays shall exist in two separate kinds: mutable and read-only. Elements in an read-only array cannot be changed, while in a mutable array, they can.

Regardless of an array’s mutability kind, an array’s length shall be fixed and cannot be modified after creation.

No operation on an array shall access data beyond the length of an array, or before the array.

Array types shall be default-initialized. An array type’s default value shall be an empty array, an array with length 0.

The string representation of an array value shall be a string prefixed with "[" followed by the string representation of each of its elements, delimited by ", " and then followed with "]". The string representation of an empty array shall be "[]".

Equality between array values shall only be established between two array values of the same component type. If the lengths of two arrays differ, they shall not be equal, then if every element of one array is equal to the corresponding element in another array, the arrays shall be equal.

Array values shall only be compared if both arrays are of the same, comparable type. The first N elements of both arrays are compared, with N being the length of the smaller array. The first element that is greater than or less than the corresponding element in another array determines how the arrays compare. If no element is greater than or less than a corresponding element in another array, then the array with the smaller capacity is lesser. If both arrays are of the same length, the arrays are equal.

Array values shall be boolean-assignable. An array value’s boolean value shall be true if it is not empty.

Array values with a hashable component type shall themselves be hashable.

7.6.The String Type🔗

The String type shall be a reference type which holds a sequential list of UTF-8 code units.

The string type shall be immutable, none of its elements can be changed. The amount of UTF-8 code units stored in a string shall be called its “length.”

No operation on a string shall access data beyond the length of the string, or before the string.

Strings are an indexable type. String values shall be accessible with an indexer value of any signed or unsigned integral type. The indexed type of a string shall be an unsigned 8-bit integral, representing the UTF-8 code unit at that index inside the string.

The string type shall be default-initialized. Its default value shall be an empty string, a string with length 0.

The string representation of a string shall be the string itself.

String value equality shall only be established between two string values. Likewise, strings shall only be compared with other strings. The Semantics for both string equality and comparability is the same as Array equality and comparability.

String values shall be boolean-assignable. A string value’s boolean value shall be true if it’s length is greater than 0.

7.7.Struct Types🔗

Struct types shall be a kind of value type, which are made up of “properties,” each of which shall have a name and a pre-set data type, determined by the user.

Structs shall not hold any properties that directly or indirectly reference the struct itself.

A struct type may be default-initialized. If each property’s type in a struct can be default-initialized, then so can the struct. Otherwise, if all properties which cannot default-initialized have a default value specified, then the struct shall be default-initialized. Otherwise, if a struct contains properties which are not of a default-initialized type and do not have a specified default value, the struct shall not be default-initialized.

The string representation of a struct shall be a string prefixed with "{" followed by the name and value of each property. The name of a property shall be separated from its value with a " = “ sequence and each pair of property name and value delimited with ”, “. The string shall finally be suffixed with a ”}" sequence.

Each defined struct property shall be subject to padding and layout semantics. This shall require each struct’s property to be located on a memory address which is a multiple of its alignment value. The empty space between one property’s value in memory and the beginning of the next property is the padding of that property.

Struct equality shall only be established between two struct values of the same struct type. If every property’s value in a struct is equal to another, then the struct values shall be equal.

Struct values shall not be comparable, nor shall struct values be boolean-assignable.

A struct type shall be hashable if all of its properties are of a hashable type.

For example this struct:

struct A {
  uint32 a = 0
  float64 b = 0
}

Defines two properties:

Both properties are initialized to a default value of 0.

7.8.Enum Types🔗

Enum types shall be a kind of value type that declare a list of named constant integer values. Each constant value will be referred to as an enum-constant.

The underlying value of an enum constant shall be referred to as its “constant value”.

Enum constants may have a constant value explicitly declared, but this is not required. If an enum constant’s value is not declared explicitly, then it’s value shall be the value of the previous enum constant plus 1. If no previous enum constant exists, the constant value shall be 0. Enum constants may declare the same value as another enum constant in the same enum type, such values are aliases of the enum constant with the same value.

Each enum constant must be declared with a name unique among the enum constants in its enum type.

The maximum possible constant value an enum constant shall hold is 2147483647 and the smallest possible value shall be -2147483648. The underlying type of the ordinal value shall be a 32-bit signed integral type.

An enum type may be default-initialized, if there exists an enum constant in that enum type with the constant value 0. Otherwise, it shall not be default-initialized.

The string representation of an enum constant shall be the name of the first enum constant declared with that enum’s constant value. If an enum constant with that constant value does not exist, then the string representation of the constant value shall be used instead.

Enum values shall only be compared to other enum values of the same enum type. An enum value shall be less than another enum value if it’s constant value is less than another enum’s constant value.

Enum value equality shall only be established with enum values of the same enum type. An enum value shall only be equal to another enum value if its constant value is identical to another enum value’s constant value.

Enum values shall not be boolean-assignable.

For example the enum declaration:

struct E {
  CONST_A = 1,
  CONST_B,
  CONST_C = 0,
  CONST_D,
}

In this enum declaration:

7.9.Variant Types🔗

Variant types shall be a kind of value type which define a list of variants the variant type itself can take the form of.

Variant types will be referred to as variant types, while each declared variant will be referred to as a variant of the variant type, or more simply as just variant.

Each variant of a variant type shall declare 0 or more properties, each of which must have a name and a pre-set data type. Variant properties shall be subject to the same padding and alignment semantics as struct properties.

The index of a variant in a variant type is referred to as its “ordinal” value.

Variant types can hold type parameters.

Variant types shall be default-initialized if the variant with ordinal 0 has no properties.

The string representation of a variant shall be a string prefixed with the name of the variant type of the value and then followed by a string representation of each of its properties in the same manner as the string representation of structs.

Variant values shall not be comparable.

Establishing equality of variant type values shall only be possible with variant type values of the same variant type. Equality shall first depend on the variant type values having identical ordinal values. If the variant declares any properties, all property values must be equal between the variant values. If no properties were specified, then the variant type values shall only be equal if their ordinal values are identical.

Variant types shall be boolean-assignable. A variant’s boolean value shall be true if the ordinal value of the variant is not 0.

Variant types shall be hashable if every variant’s properties are all hashable.

For example the variant declaration:

variant Optional<T> {
Empty(),
Present(T value),
}

Has two variant types:

7.10.Interface Types🔗

An interface type shall be a kind of reference type, but not a type which can itself be instantiated.

Interfaces shall declare 0 or more methods which must be defined by any class wishing to implement the interface.

Implementing an interface shall mean declaring a class as being an implementer of an interface type and defining a function body for each of the methods the interface declares.

Interfaces may hold type parameters.

Interface types shall not be default-initialized.

Interface equality and comparability semantics shall be the same as those for class types.

Interface values shall not be boolean-assignable.

7.11.Class Types🔗

Class types shall be a kind of reference type which define class members. Class members are either constructors, methods or fields.

Constructors are functions which shall be invoked upon the creation of a class type’s value. Constructs may, like functions and methods, require certain arguments to correctly initialize the class instance.

Methods shall be functions that exist within the namespace of a class. Methods shall also be divided into two separate types: static and non-static. Static methods belong to the class, while non-static methods belong to a class instance. Methods inside classes and interfaces shall have access to the this keyword that shall refer to the instance of the class the method belongs to. For static methods, the keyword shall not be available.

Fields shall be the properties that belong either to class instances, or for static fields, to the class itself. Non-static Fields shall be subject to the same padding and alignment Semantics as struct properties. Non-static fields may be referred to as “instance fields” and static fields referred to as “class members.”

Classes may extend one other class and can implement as many non-conflicting interfaces as described in the limits section (See 8. Limits.) Non-conflicting shall mean that none of the implemented interfaces have themselves declared methods, or inherited methods from another extended interface, whose function signatures are in conflict. Two function signatures are in conflict if their argument types and name are the same, but not their return types.

Class extension shall mean the extending class gains access to all its public and protected members. Classes can also override any non-const methods of its extended class.

Unless specified otherwise, the term extend will be used for classes implementing interface as well.

Classes and interfaces will be referred to collectively as object types.

An object type extended by another object type is referred to as the parent of the extending object type. An object type extending another object type is referred to as the child type of the extended object type.

A type which directly or indirectly extends another type (by way of its parent extending the type, for example) is referred to as a derived object type of the extended object type. Vice versa, the term super will be used for an object type which is extended indirectly or directly by another object type.

Class types may hold type parameters.

Functions, and methods on object types are collectively referred to as callable objects, or just callables.

Classes may override any non-static methods of their super types that are not marked as const. Overriding shall mean that all calls to the super type’s method instead go to the derived object type’s method.

Class types shall not be default-initialized.

The string representation of a class type value shall be a string prefixed by the fully qualified name of the class, followed by an "@" character and then followed by the memory address of the referenced object instance.

Class type values shall not be comparable.

Class type value equality shall only be established between class values of identical class types or between class types where one is a derived type of the other. If two object type values reference the same instance, they shall be equal. Otherwise, they shall not be equal.

Object type values shall not be boolean-assignable.

Object type values shall be hashable. An object type’s hash value shall be derived from its idenity and does not change over the object’s lifetime.

7.12.Function Types🔗

A function type shall be a kind of reference type which outlines the argument types and returned type of a callable object.

Function types shall not be instantiated nor shall they be default-initialized.

The string representation of a function type shall be a string prefixed "(", followed by a ", “-delimited list of the names of each argument’s data type. The string is then suffixed with ”) -> “ followed by the name of the returned type.

Function types shall not be comparable to any value of any type.

Function value equality shall be possible to establish with other function values of the same function signature. Function type values shall only be equal if they refer to the same function.

Function type values shall not be boolean-assignable nor shall they be hashable.

7.13.Nullables🔗

A nullable type shall be a value type which marks another type as nullable, meaning its value may or may not exist.

The value existence state of a nullable value is referred to as it’s presence state. And the type a nullable type is being used on shall be referred to as the “nulled type.”

Nullable values shall be default-initialized. Nullable values shall be initialized to a value with a false presence state by default.

The string representation of a nullable shall be either the string “null” if the presence state of the nullable value is false, or the string representation of the nulled type’s value, if it’s value is present.

Nullable values shall not be comparable to any value of any type.

Nullable value equality shall only be established between nullable values of the same nulled type, or between a nullable value and a non-nullable value of the same nulled type. If both nullable values have a false presence state, they shall be equal. Otherwise, the nullable value’s nulled type’s values must be equal in order to establish equality.

Nullable values shall be boolean-assignable. A nullable value’s boolean value shall be true if it’s presence state is true.

Nullable values shall be hashable if their nulled type is hashable. All nullable values with a false presence state shall have the same hash value.

7.14.Type Compatibility And Assignability🔗

Type compatibility shall determine if a type can be passed as an argument to a callable, set as the value of a variable, a variant/struct property, or a class field. The following table only determines semantic compatibility, it does not list conversions that may or not need to be performed when assigning a value of one type to an object of another, compatible, type.

Table 3 - Type Compatibility Table
TypeCan be assigned from
StringsOnly other Strings.
Read-only ArraysOnly arrays of the same component type.
Mutable ArraysOnly mutable arrays of the same component type.
Unsigned IntegersAny unsigned integer of the same or smaller size.
Signed IntegersAny signed integer of the same or smaller size, or any unsigned integer of a smaller size.
Floating point numbersAny floating point value of the same or smaller size, or any integer.
StructsOnly other struct values of the same struct type.
EnumsOnly other values of the same enum type.
Variant TypesOnly other values of the same variant type.
VariantsOnly other values of the same variant.
InterfacesAny value of the same interface, or any value of a dervied object type which extends the interface.
ClassesAny value of the same class or a derived class.
NullablesFor non-object types, the nulled type must be identical. For object types, the assigned nulled type must be a compatible type with the target nullable's type.

For types with type parameters, all the type parameters must be set to the same exact type.

7.15.Type Conversions🔗

This section defines the conversion operations that must occur between types. If there is no conversion listed from one type to another in this section, then it means that nothing must be done to convert from one type to another, or that the conversion is not possible. See the previous section for type compatibility and assignability.

7.15.1.Implicit Conversions🔗

These conversions must be done implicitly without requiring an explicit cast operation by a user of the language. When the term “usual arithmetic conversions” is referenced, the following conversions are what they reference.

Table 4 - Implicit conversion operations
Source TypeTarget TypeConversion
Any signed or unsigned integral typeA larger signed or unsigned integral typeThe value is converted from the smaller to the equivalent value in the larger type.
Any enum typeA 32-bit signed integer, or a 64-bit signed or unsigned integerThe enum's constant value is used as the integral value.
Any signed or unsigned integral typeA floating point typeThe value is converted from the integral type the closest possible floating point value.
A 32-bit floating point valueA 64-bit floating point valueThe value is converted to the closest value possible in the larger type.

7.15.2.Explicit Conversions🔗

These conversions must be explicitly done by users by using a casting expression (Defined in the language grammar).

Table 5 - Explicit conversions
Source TypeTarget TypeConversion
Any integral typeAny integral type of smaller sizeThe resulting value shall be the larger integral's value reduced modulo 2N, where N is the number of value bits in the target type. The resulting bit pattern shall be interpreted according to the target type's signedness.
A 64-bit floating point valueA 32-bit floating point valueThe larger type's value shall be converted to the closest equivalent value of the smaller type. Any value beyond the range of float32 shall become positive infinity or negative infinity, whichever is closer.
Any floating point valueAny integral valueThe floating point value shall be truncated towards 0, then converted to the equivalent integral value. A floating point value outside the integral type's value range shall become either the maximum or minimum value that integral can hold, whichever is closer. NaN becomes 0.
A 32-bit signed integral value, or a 64-bit signed or unsigned integral valueAny enum valueIf the integral type is larger than 32-bits, then the value is converted to a signed 32-bit integer value according to the above specified rules. The integral value is then treated as the constant value of the enum.

7.16.Type Parameters🔗

Type parameters allow a declaration to be written with types that are filled in later. A declaration with one or more type parameters is a template. A template is not itself a type or a function.

Only types previously stated to allow type parameters may be declared with type parameters.

Supplying a type argument for every type parameter of a template produces an instantiation of the template. Instantiating a type template yields an instantiated type, and instantiating a function or method template yields an instantiated function. A template shall always be used with a type argument for each of its type parameters, except where the type arguments of a function are inferred. (See Inference below.)

Execution environments shall treat each instantiation as if every occurrence of a type parameter in the template had been replaced by the corresponding type argument. Bytecode retains templates in their uninstantiated form.

7.16.1.Identity and Assignability🔗

Two instantiations of the same template are the same type if and only if each corresponding type argument is the same type. Instantiated types that are not the same type shall not be assignable to one another, regardless of any relationship between their type arguments.

Each instantiated type shall not have its own copy of the static fields of the template. Static fields shall not be declared with a type from a type parameter.

7.16.2.Constraints🔗

A type parameter may declare constraints that limit which types may be used as its type argument. A type parameter with no constraints accepts any type. Constraints are written before the name of the type parameter.

The Void type shall never be used as a type parameter.

The following constraints are defined:

A type argument shall satisfy the constraint of its type parameter, otherwise the program is invalid.

7.16.3.Use of Type Parameters🔗

A type parameter has no properties of its own. Its default-initializability, boolean-assignability, string representation, equality and every other property defined in the Data Types section are those of the type argument, and are only known once the template is instantiated.

Within the body of a template, a value whose type is a type parameter may be used only in ways permitted by the constraints of that parameter. Equality comparison and conversion to a string shall be permitted for every type parameter. Using a type parameter in a way that requires a property it has not declared a constraint for is invalid, and shall be reported when the template is translated, not when it is instantiated.

7.16.4.Inference🔗

A type argument of a function or method may be omitted if it can be determined from the types of the arguments in the call. Inference shall use the exact type of each argument, and shall not take any implicit conversion into account. If the same type parameter is determined to be different types by different arguments, the call is invalid.

A type argument shall not be inferred from the type that the result of a call is expected to have. A type argument that cannot be determined from the arguments shall be specified explicitly.

7.17.Hashing🔗

A hash is a value of the int64 type associated with a hash container, such as a hash map or hash set. Two values that are equal shall have the same hash value, while two values which are not equal shall not have the same hash value.

Hashing strategy and algorithm are implementation defined. Values of all types except for function types shall be “hashable.”

Positive zero and negative zero shall have the same hash value. The hash of an object type’s value is derived from its identity shall not change during its lifetime.

8.Limits🔗

The following limits are defined for features and aspects of the Tetral Language.

Table 6 - Language Limits
AspectLimit
Maximum number of implemented interfaces256
Maximum number of function/method/constructor declaration arguments62
Maximum number of function/method/constructor call arguments62
Maximum number of enum constants per enum type1024
Maximum number of variants per variant type256
Maximum depth of nested functions8

9.Language🔗

9.1.Identifier Semantics🔗

An identifier is a name that denotes a symbol. The same identifier may denote different symbols at different points in a program. Symbols and namespaces are defined in the Terms, Concepts and Definitions section.

A qualified identifier consists of a namespace name, ::, and an identifier, and names a symbol declared in that namespace. An identifier without a namespace prefix is an unqualified identifier.

A distinction shall be made between identifiers in a primary-expression and identifiers in other contexts. In a primary expression, an identifier shall refer to a symbol that is visible at that point, as defined below.

An unqualified identifier shall be resolved by searching for a symbol of that name in the following scopes, in order. The first scope containing a symbol of that name determines the result:

  1. The block containing the identifier, then each enclosing block in turn, up to and including the body of the enclosing function. The parameters of a function belong to the outermost block of its body.
  2. The global scope of the current namespace, including the declarations of every source file in that namespace.
  3. The symbols made available by imports.

A local variable is visible only after its declaration. Symbols declared in the global scope are visible throughout the global scope regardless of the order of their declarations.

Names are shared by all kinds of symbols: functions, types, variables and namespaces occupy one set of names in a scope. The only exception is function overloading, described below.

Several functions in the same scope may have the same name if their parameter type lists differ. Functions that differ only in their return type shall not share a name. When the identifier of a call denotes functions, the result of the lookup is the set of all functions with that name in the scope that determined the result. The function called is then chosen from that set according to the argument types, as defined in the call expression section.

A local variable or parameter shall not have the same name as another local variable or parameter that is visible at its declaration, nor as a symbol declared in the global scope of the current namespace. A symbol provided by an import may be hidden by a local variable or parameter of the same name. Hiding a function by declaring another function of the same name with a different parameter type list is overloading, not hiding.

If several imports provide a symbol of the same unqualified name, the following applies:

Imports are ordered by their position in the source file in which the identifier appears. Implicit imports are ordered after all explicit imports. A symbol from an import other than the first may be named by qualifying it with its namespace.

A qualified identifier shall not be resolved through the scopes above. Each namespace name in a qualified identifier shall be resolved starting from the root namespace.

9.2.Overflow/Underflow Semantics🔗

Integral arithmetic shall not produce errors on overflow. If the mathematical result of an operation on integral operands cannot be represented in the result type, the result shall be that value reduced modulo 2N, where N is the number of bits of the result type, and interpreted according to the signedness of the result type. Signed integral types use two’s complement representation. This applies to all operations that produce an integral value, including addition, subtraction, multiplication, negation, increment, decrement, shifts and the division of the minimum value of a signed type by -1.

Floating point operations shall follow IEEE 754. A result too large to represent is an infinity, and a result too small to represent is a subnormal value or zero. These cases shall not be errors.

Division or remainder of an integral value by zero shall cause a panic.

Constant expressions evaluated by the translation environment shall produce the same results as the same operations evaluated at runtime. A translation environment should warn when it detects that a constant expression overflows. An integer literal that cannot be represented in the type it is converted to makes the program invalid.

9.3.Runtime Errors🔗

A panic is an error that cannot be handled by a program. When a panic occurs, execution of the current thread of the program stops, and the call stack is unwound without executing any further Tetral code.

A panic shall occur when the program performs an operation for which this document specifies a panic. Every such operation shall have a condition that a program can test beforehand, so that a correct program never panics. (Failure to allocate memory is an exception to this requirement.)

In a standalone environment, a panic shall terminate the program with a nonzero exit status, after reporting a diagnostic message. In an embedded environment, a panic shall stop at the nearest native function call and be reported to the native function, which is not invoked again. The manner of reporting is defined by the native interface section.

An implementation shall not read or write memory outside the objects the program may legitimately reach, whether or not a panic occurs.

9.4.Object Lifetimes🔗

An object shall remain valid for as long as it can be reached by the program. When or whether the memory of an unreachable object is reclaimed is unspecified, and shall not be observable by a program. No code is executed when an object is reclaimed.

9.5.Source Text🔗

A source file shall be encoded as UTF-8. A byte order mark shall not be present. A source file that is not valid UTF-8 or that begins with a byte order mark is invalid.

9.6.Syntax Notation🔗

References to other syntactic rules are in italic, literal values are in bold, monospaced font. An italic syntactic rule followed by a colon (:) defines the rule. Alternative definitions of the rule are defined on new lines.

The syntax x denotes a part of the grammar where x may occur zero or one times. The syntax x denotes a part of the grammar where x may occur zero or multiple times. The syntax x denotes a part of the grammar where x may occur one or more times.

Syntax rule definitions followed by a “one of:” mean that any of the specified literals are a valid value for the token.

Syntax rule definitions that are written in regular font are used when the number of alternative definitions is too great to specify manually.

Basic Syntax Notation Example: ( expression )

Indicates a Syntax element enclosed with ”()" which might contain an expression, or several expressions.

9.7.Lexical Elements🔗

Syntax
keyword identifier constant string-literal operator
Semantics

Lexical analysis shall consume the largest sequence of source characters that constitutes a valid token.

Tokens, outside of character or string literals, shall ignore all white space. White space is defined as any Unicode codepoint in the input test with the White_Space binary property.

Any use of a literal (eg: const) in the definition of the language grammar is case-sensitive and thus must match the literal exactly.

No Unicode normalization is performed on the parsed tokens.

9.7.1.Keywords🔗

Syntax
real-keyword type-keyword alias-keyword contextual-keyword if else break continue return while for struct module import export do const assert native this override static protected public private constructor this super class enum struct interface variant cast bitcast extendable new from implements extends mutable readonly void uint8 bool int8 uint16 int16 uint32 int32 uint64 int64 float32 float64 string boolean byte ubyte short ushort int uint long ulong float double
Semantics

When lexical analysis encounters a sequence which can be both a keyword or an identifier, then keywords shall take precedence over identifiers.

After lexical analysis, alias keywords shall have the same syntactic meaning as their corresponding real keywords. For alias token mappings, see Table 7 - Alias token mappings.

Contextual keywords shall only be keywords in specific contexts. Those contexts are defined in the grammar as they appear. Outside the context which will be defined, contextual-keywords shall be identifiers.

Table 7 - Alias token mappings
Alias TokenMapped Token
booleanbool
byteint8
ubyteuint8
charuint8
shortint16
ushortuint16
intint32
uintuint32
longint64
ulonguint64

9.7.2.Identifiers🔗

Syntax
identifier-start identifier-continue nondigit XID_Start character (Defined by Unicode) digit nondigit XID_Continue character (Defined by Unicode) 0 1 2 3 4 5 6 7 8 9 _ $ a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Constraints

Identifiers must reference a valid symbol that is accessible in the current semantic context. (Lookup Semantics defined in 9.1. Identifier Semantics.)

Semantics

A symbol lookup is performed as defined in 9.1. Identifier Semantics.

The result of an identifier expression, is value of the symbol it is
referencing.

An identifier which references a valid semantic variable or a constant is a valid lvalue. If the value it references is mutable, the result is a valid mutable lvalue.

9.7.3.Constants🔗

Syntax
integer-constant floating-point-constant character-constant predefined-constant
9.7.3.1.Integer Constants🔗
Syntax
sign decimal-integer-constant sign octal-constant sign hexadecimal-constant sign binary-constant + - i I u U l L UL ul uL Ul b B ub UB uB Ub s S us US uS Us 0o octal-sequence integer-suffix 0O octal-sequence integer-suffix octal-digit underscore octal-digit 0 1 2 3 4 5 6 7 0x hexadecimal-sequence integer-suffix 0X hexadecimal-sequence integer-suffix hexadecimal-sequence underscore hexadecimal-digit 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F 0b binary-sequence integer-suffix 0B binary-sequence integer-suffix binary-digit underscore binary-digit 0 1 digit-sequence integer-suffix digit digit-sequence underscore digit _
Constraints

Unsuffixed integer constants shall not represent a value that exceeds the maximum value of an unsigned 64-bit integer.

Suffixed integer constants shall not represent a value that exceeds the suffix specifier’s type. (See Table 8 - Suffix type mappings.)

Any integer constant with the value of -0 shall be invalid.

Semantics

Unsuffixed integer constants shall result in one of three types of integral types based on the smallest type that can hold the constant value. (See Table 9 - Unsuffixed integer types.)

Suffixed integer constants shall result in a value with the integral type specified by the suffix. (See Table 8 - Suffix type mappings.)

Table 8 - Suffix type mappings
SuffixMapped Type
b, Bint8
s, Sint16
i, Iint32
l, Lint64
ub, UB, uB, Ubuint8
us, US, uS, Usuint16
u, U, ui, UI, uI, Uiuint32
ul, UL, uL, Uluint64
Table 9 - Unsuffixed integer types
Minimum ValueMaximum ValueResulting Type
-21474836482147483647int32
21474836489223372036854775807int64
-9223372036854775808-2147483649
922337203685477580818446744073709551615uint64
9.7.3.2.Floating Point Constants🔗
Syntax
sign fractional-part exponent-part floating-point-suffix digit-sequence digit-sequence . digit-sequence digit-sequence . . digit-sequence e sign digit-sequence E sign digit-sequence f F d D
Constraints

An unsuffixed floating point constant must contain a valid floating point value that can be represented as a 64-bit floating point value.

A suffixed floating point constant must contain a valid floating value that can be represented by the type specified by the suffix. (See Table 10 - Floating point suffix type table.)

Hexadecimal/Octal/Binary floating point numbers are explicitly not supported in Tetral grammar.

Semantics

The result of an unsuffixed floating point constant shall be a 64-bit floating point value.

The result of a suffixed floating point constant shall be a floating point value of the type matching the suffix. (See Table 10 - Floating point suffix type table.)

Table 10 - Floating point suffix type table
SuffixesType
f, Ffloat32
d, Dfloat64
9.7.3.3.Character Constants🔗
Syntax
' char-sequence ' Any valid Unicode codepoint except the single-quote, backslash or newline character escape-sequence simple-escape-sequence hex-escape-sequence \' \" \\ \t \r \n \T \R \N \$ \u hexadecimal-digit \U hexadecimal-digit
Constraints

A character constant’s contained codepoint must be a valid Unicode codepoint.

A hexadecimal escape sequence shall not contain more than 6 hexadecimal digits.

Semantics

Character constants result in a value of a 32-bit unsigned integer type, representing the Unicode codepoint of the character.

An escaped sequence shall lead to the escaped character’s value being used. See Table 11 - String/Character escape sequence values.

Table 11 - String/Character escape sequence values
Escape SequenceResulting codepoint name.Unicode codepoint.
\'Single quote characterU+0027
\"Double quote characterU+0022
\\Slash characterU+002F
\t, \TTabulation characterU+0009
\n, \NLinefeed characterU+000A
\r, \RCarriage Return characterU+000D
\$Dollar Sign characterU+0024
9.7.3.4.Predefined Constants🔗
Syntax
true false null nan inf -inf +inf
Semantics

The result of the true and false keywords shall be a boolean value of the corresponding value.

The result of the null value shall be a nullable value with a false presence state value. A null value can be implicitly cast to any nullable type.

The result of the nan keyword shall be a 32-bit floating point value with the special Not-A-Number value.

The result of the inf, -inf and +inf keywords shall be 32-bit floating point value with an infinite value of the corresponding signedness. If no sign is specified, then the result shall be the same as with the + sign.

9.7.4.Operators🔗

Syntax
( ) { } [ ] : ; , . ... & &= && &&= | |= * *= / /= + += - -= ^ ^= % %= << <<= >> >>= < <= > >= ++ -- == != = ! ~ => ** **= || ||= ? ?? ??= ?. !. ::

9.7.5.Semicolons🔗

Syntax
;
Semantics

The semicolon as a marker for the end of an expression or for a statement shall be completely optional and need not be used unless there may be ambiguity in the syntax.

Certain syntactic elements (For example, the for-loop-statement) explicitly use semicolons to delimit parts of the grammar. In such cases the semicolon shall be required.

9.7.6.Comments🔗

Except within a string or character literal, the characters // and ## denote the beginning of a line comment. The comment consumes the rest of the source text’s line, or until the end of input has been reached.

Except within a string or character literal, the characters /* denote the beginning of a block comment. The comment consumes input until a matching */ sequence has been found, or until the end of input has been reached.

Except within a string or character literal, the characters /** denote the beginning of a documentation comment. The comment consumes input until a matching */ sequence has been found, or until the end of input has been reached.

In almost all cases, comments may be simply skipped over and ignored, except for documentation comments (Starting with /**) which may be linked to the specific declaration that they prefix. This may be ignored by implementations that do not generate documentation or otherwise make use of user-written documentation.

9.8.Expressions🔗

9.8.1.Primary Expressions🔗

Syntax
constant identifier object-literal array-literal string-literal cast-expression super-expression this-expression new-expression switch-expression ( expression )
9.8.1.1.New Expression🔗
Syntax
object-instantiation-expression array-instantiation-expression new function-call new type-name-expression function-call new type-expression [ expression ] new type-expression [ expression ] function-call
Constraints

New expressions shall only be used to instantiate structs, classes and arrays.

Semantics

A new-expression shall instantiate a new instance of a specific type.

If the type name was not specified, the type must be inferred from the surrounding context.

Object Instantiation
Constraints

The specified arguments must match a constructor that exists on the type.

Semantics

The object instantiation expression shall instantiate an object by calling the appropriate constructor if it is constructing a class.

If the object being instatiated is a struct, then no arguments shall be specified.

Array Instantiation
Constraints

The specified expression must result in a value that can be implictly converted to an unsigned 32-bit integer, this expression’s result will be referred to as the instantiated array’s length.

The array type must be default initialize-able.

Semantics

Instantiates an array of the defined length and initializes each value in the created array to the array type’s default initialized value.

9.8.1.2.‘Super’ Expression🔗
Syntax
super
Constraints

The super expression shall only be used inside an object type’s method body or constructor body.

The super expression shall only be used inside an object type which has a parent type.

Semantics

The result of the expression shall be a reference to the instance of the parent of the class in which the expression was used.

Any members which are accessed through the super keyword shall not be redirected to any members of the current class which override the parent class’ members.

9.8.1.3.‘This’ Expression🔗
Syntax
this
Constraints

This expression shall only be used inside an object type’s method body or constructor body.

Semantics

The result of the expression shall be a reference to the instance of the class in which the expression was used.

9.8.1.4.Cast Expression🔗
Syntax
value-cast-expression bit-cast-expression cast ( type-expression , expression ) bitcast ( type-expression , expression )
Constraints

Regular cast expressions shall only convert a value to a specified type if the type of the value resulting from the expression can be implcitly or explicitly converted to the specified type. (See 7.15. Type Conversions.)

Bit cast expressions shall only be performed with an expression that results in an arithmetic value and shall only allow casting from that arithmetic value to another arithmetic type of the same size as the expression value’s resulting type.

Semantics

A regular casting expression shall return a value of the specified type by performing either an implicit or explicit conversion on the value resulting from the expression.

A bit casting expression shall return a value of the specified type by simply treating bits of the value resulting from the expression as a value of the specified type.

9.8.1.5.Object Literals🔗
Syntax
{ object-literal-property-list } object-literal-property-list , object-literal-property , identifier : expression
Constraints

If an object literal’s struct type cannot be inferred from the surrounding context, then the expression shall be invalid.

An object literal shall only initialize properties that exist on the struct type.

An object literal shall not declare any duplicate properties.

Object literals shall not be used to initialize class values.

If an object literal property omits value expression, then a symbol with the name specified by the identifier must exist in the current semantic context.

Semantics

The type of struct initialized by an object literal must be inferred from the surrounding context. If the object literal is being assigned to a property of a struct or variant, or if the object literal is being assigned to a variable or class field, the inferred type shall be the assigned object’s type. If the object literal is used as a return value in a return-statement then the inferred type shall be the function’s return type.

An object literal expression shall result in a value of an inferred struct type with each of the struct value’s properties being set to the values specified.

If an object literal property omits the value expression, then it shall be semantically equivalent to assigning a property with the name of the identifier to a symbol with the same as the identifier.

9.8.1.6.Array Literals🔗
Syntax
[ array-literal-values ] expression , expression ,
Constraints

If an array literal’s type cannot be inferred from the surrounding semantic context, then the expression shall be invalid.

Semantics

The type of the array initialized by an array literal must be inferred from the surrounding context. The semantics for inferring the component type shall be the same as inferring an object literal’s type.

Semantically, an array literal is identical to constructing the array with a new-expression and setting each element separately.

9.8.1.7.String Literals🔗
Syntax
line-string-literal multiline-string-literal " line-string-content " line-string-character line-string-content line-string-character line-string-content string-template """ multiline-string-content """ multiline-string-character multiline-string-content multiline-string-character multiline-string-content string-template $identifier ${expression} Any valid Unicode codepoint except ", \, $ or newline character. escape-sequence Any valid Unicode codepoint except \ or $, provided it is not the start of three consecutive " characters. escape-sequence
Constraints

All expressions and identifiers declared inside a string shall return a non-void value.

A template of the form $identifier must not have any white space between the dollar sign character and the start of the identifier.

Semantics

A string literal shall always result in a value of the String type.

It can be assumed that each line in a multiline string will have some level of indentation. After parsing, this indentation must be stripped from the start of each line. Since indentation can vary from line to line, the amount indentation removed depends on the line with the least indentation.

The template of the form $identifier shall be semantically identical to a template of the form ${identifier}.

If a string contains any templates it is considered a templated string. Otherwise, if a string literal contains no templates, it is considered a non-templated string. Templated strings are made up of the following parts:

  1. A string head, which is the part of the string’s content up to the first template.
  2. A template.
  3. For each additional template, a string part which is the part of the string between two templates, followed by another template.
  4. A string tail, which is the part of the string’s content from the end of the last template until the end of the string’s content.

A string head, string tail and each string part, may be empty. A templated string contains exactly one string head and tail and one more template than it has string parts.

Evaluation

Templated strings are evaluated in order, beginning from the head. Each template is evaluated and the string representation of the value resulting from the evaluation is then appended to the resulting string.

After a template has been evaluated, evaluation of the string moves on to the next part of the string. If the next part is the tail, the tail’s content is appended to the resulting string and evaluation ends. Otherwise, the next string part is appended to the resulting string and the next template is then evaluated.

9.8.2.Trail Expressions🔗

Syntax
primary-expression property-access-expression index-access-expression function-call-expression coalescence-expression

9.8.3.Index Access Expression🔗

Syntax
trail-expression [ expression ]
Constraints

The type of value returned by the trail-expression must be a value of an indexable type.

The indexer expression must result in a value of the type that is used to index into the indexable operand’s value.

Semantics

The value returned by an index access expression shall be of the indexed type of the object being indexed into.

A valid index access expression is a valid lvalue. Accessing a non-immutable array shall be a valid mutable lvalue.

If the type of value being indexed into is a string or an array, and the index is beyond the length of that value, then it shall be a runtime error to access the element.

9.8.4.Property Access Expression🔗

Syntax
trail-expression . identifier trail-expression ?. identifier trail-expression !. identifier
Constraints
  1. The property being accessed must exist on the object operand.
  2. A property access must not violate class/interface access Semantics.
  3. The . operator cannot be used on a nullable operand. Either the !. or ?. operator must be used by the user to acknowledge the nullability value.
Semantics
  1. The result of the . and !. operator is a copy of the value of the property or virtual property being accessed.
  2. The result of the ?. operator is a nullable copy of the value of the property or virtual property being accessed. If the object operand is an empty nullable, then the resulting value is an empty nullable.
  3. Accessing a property of a nullable type with the ?. operator causes the nullable to be flattened.
  4. A valid property access expression is a valid lvalue.
Runtime Errors
  1. It is a runtime error if the object operand is an empty nullable value.

9.8.5.Function Call Expression🔗

Syntax
trail-expression function-call type-parameter-instatiation ( arguments-list ) expression arguments-list , expression
Constraints
  1. The value returned by the target trail-expression must be a function.
  2. All arguments passed to the function must be assignable to that function’s declared arguments.
  3. All type parameters passed to the function must conform with any type paramater Constraints the function declared.
Semantics
  1. Invokes a function with the specified arguments.
  2. Calling arguments are evaluated from left to right.
  3. The value returned by the expression is dependent on the return type of the function being invoked.
  4. When the trail-expression matches multiple overloading functions, the one that would require the least number of type conversions is selected.

9.8.6.Coalescence Expression🔗

Syntax
trail-expression trail-expression ?? expression
Constraints
  1. The left operand must be a nullable value.
  2. The right operand must be assignable to the left operand, or be a non-nullable value of an assignable type to the left operand.
Semantics
  1. The result of the ?? operator is the left operand if it is present. Otherwise, the result of the operator is the right operand.
  2. If the left operand is returned, the right operand must not be evaluated.

9.8.7.Unary Expressions🔗

Syntax
trail-expression unary-increment-expression unary-decrement-expression unary-arithmetic-expression unary-bitwise-negation-expression unary-logical-negation-expression
9.8.7.1.Unary Increment Expressions🔗
Syntax
++ unary-expression unary-expression ++
Constraints
  1. The operand must be a valid lvalue that can be modified.
  2. The operand must be of an integral or floating point type.
Semantics
  1. If the increment operator is placed before the operand, the result is the value of the operand incremented by 1. As a side effect, the resulting value is written to the operand object.
  2. If the increment operator is placed after the operand, the result is the value of the operand. As a side effect, the operand’s value is incremented by 1 and written to the operand object.
9.8.7.2.Unary Decrement Expressions🔗
Syntax
-- unary-expression unary-expression --
Constraints
  1. The operand must be a valid lvalue that can be modified.
  2. The operand must be of an integral or floating point type.
Semantics
  1. If the decrement operator is placed before the operand, the result is the value of the operand decremented by 1. As a side effect, the resulting value is written to the operand object.
  2. If the decrement operator is placed after the operand, the result is the value of the operand. As a side effect, the operand’s value is decremented by 1 and written to the operand object.
9.8.7.3.Unary Arithmetic Expressions🔗
Syntax
- unary-expression + unary-expression
Constraints
  1. For the - operator, the operand must be of an arithmetic type.
  2. For the + operator, the operand must be of an arithmetic type or a boolean. (Not boolean-assignable, an explicit boolean.)
Semantics
  1. The result of the - operator is the negative of the operand’s value, or positive, if the operand’s value is already negative. If the operand’s type an unsigned type, the resulting type is a signed type of the same size.
  2. The result of the + operator, for arithmetic values, is the value of the operand.
  3. The result of the + operator, for boolean values, is the value 0, if the boolean value is false, otherwise the result is 1.
9.8.7.4.Unary Bitwise Negation Expressions🔗
Syntax
~ unary-expression
Constraints
  1. The operand must be a valid lvalue.
  2. The operand must be of an integral type.
Semantics
  1. The result of the expression is the value of the operand with all the bits flipped (All zeroes set to ones and vice versa)
9.8.7.5.Unary Logical Negation Expressions🔗
Syntax
! unary-expression
Constraints
  1. The operand’s value must be boolean-assignable. (Defined in .)
Semantics
  1. The result of the ! operator is the value of the operand, converted to a boolean, and then the value inverted.

9.8.8.Power (POW) Expression🔗

Syntax
unary-expression power-expression ** unary-expression
Constraints
  1. Both operands must be of a compatible arithmetic type.
Semantics
  1. The usual arithmetic conversions are applied.
  2. The result of the ** operator is the left operand raised to the power of the right operand.

9.8.9.Multiplicative Expressions🔗

Syntax
power-expression multiplicative-expression * power-expression multiplicative-expression / power-expression multiplicative-expression % power-expression
Constraints
  1. Both operands must be of a compatible arithmetic type.
  2. In the case of the * operator, if the left operator is a string, the right operand must be an integral.
Semantics
  1. The usual arithmetic conversions are applied.
  2. The result of the * operator, when applied to two arithmetic types, is the left operand multiplied by the right operand.
  3. The result of the * operator, when applies to a string operand and an integral operand, is the value of the string operand with its content repeated an amount of times specified by the integral operand.
  4. The result of the / operator is the left operand divided by the right operand.
  5. The result of the % operator is the remainder of dividing the left operand by the right operand.

9.8.10.Additive Expressions🔗

Syntax
multiplicative-expression additive-expression + multiplicative-expression additive-expression - multiplicative-expression
Constraints
  1. For the - operator, both operands must be a compatible arithmetic type.
  2. For the + operator, either both operands must be of a compatible arithmetic type, or the left operand must be a string, and the other operand must be a non-void value.
Semantics
  1. The usual arithmetic conversions are applied.
  2. The result of the + operator, when both operands are arithmetic, is the left operand plus the right operand.
  3. The result of the + operator, when the left operand is a string, is the string operand’s string value concatenated with the string representation of the other operand. (See .)
  4. The result of the - operator is the left operand minus the right operand.

9.8.11.Shift Expressions🔗

Syntax
additive-expression bitshift-expression << additive-expression bitshift-expression >> additive-expression
Constraints
  1. Both operands must be of an integral type.
Semantics
  1. The result of the « operator is the value of the left operand with its bits shifted to the left by the value of the right operand.
  2. The result of the » operator is the value of the left operand with its bits shifted to the right by the value of the right operand.
  3. In the case the right operand is a negative value, the operation acts as the inverse operation: left shift becomes right shift and vice versa.

9.8.12.Relational Expressions🔗

Syntax
bitshift-expression relational-expression < bitshift-expression relational-expression <= bitshift-expression relational-expression > bitshift-expression relational-expression >= bitshift-expression
Constraints
  1. Both operands must be of a compatible comparable type (See .)
Semantics
  1. If both operands are compatible arithmetic types, then the usual arithmetic conversions are applied.
  2. The result of the < operator is a boolean true value if the left operand’s value is less than the right operand’s value.
  3. The result of the <= operator is analogous to the result of the < operator, except that it also returns a boolean true value when the left operand’s value is equal to the right operand’s value.
  4. The result of the > operator is a boolean true value if the left operand’s value is greater than the right operand’s value.
  5. The result of the >= operator is analogous to the result of the > operator, except that it also returns a boolean true value when the left operand’s value is equal to the right operand’s value.

9.8.13.Equality Expressions🔗

Syntax
relational-expression equality-expression == relational-expression equality-expression != relational-expression
Constraints
  1. Both operands must be of a compatible type.
Semantics
  1. If both operands are compatible arithmetic types, then the usual arithmetic conversions are applied.
  2. The result of the == operator is a boolean true value if the left operand’s value is equal to the right operand’s value.
  3. The result of the != operator is the inverse of the == operator’s value.

9.8.14.XOR Expressions🔗

Syntax
equality-expression xor-expression ^ equality-expression
Constraints
  1. Both operands must be of a valid integral type
Semantics
  1. The usual arithmetic conversions are applied.
  2. The result of the ^ operator is the value of the left operand with every bit set to true if and only if the corresponding bit is set in only one of the operands.

9.8.15.Bitwise AND Expressions🔗

Syntax
xor-expression bitwise-and-expression & xor-expression
Constraints
  1. Both operands must be of a valid integral type
Semantics
  1. The usual arithmetic conversions are applied.
  2. The result of the & operator is the value of the left operand with every bit set to true if the corresponding bit in the right operand is also set to true.

9.8.16.Bitwise OR Expressions🔗

Syntax
bitwise-and-expression bitwise-or-expression | bitwise-and-expression
Constraints
  1. Both operands must be of a valid integral type
Semantics
  1. The usual arithmetic conversions are applied.
  2. The result of the | operator is the value of the left operand with every bit set to true if the bit is set in either the left operand or the right operand.

9.8.17.Logical AND Expressions🔗

Syntax
bitwise-or-expression logical-and-expression && bitwise-or-expression
Constraints
  1. Both operands must be of a valid integral or boolean-assignable type.
Semantics
  1. The usual arithmetic conversions are applied if both operands are arithmetic types.
  2. The result of the && operator is a boolean true value if both operands evaluate to a true value.
  3. If the first operand evaluates to a false value, the second operator must not be evaluated.

9.8.18.Logical OR Expressions🔗

Syntax
logical-and-expression logical-or-expression || logical-and-expression
Constraints
  1. Both operands must be of a valid integral or boolean-assignable type.
Semantics
  1. The usual arithmetic conversions are applied if both operands are arithmetic types.
  2. The result of the || operator is a boolean true value if at least one of the operands are a boolean true value.
  3. If the left operand evaluates to a true value, the right operand must not be evaluated.

9.8.19.Conditional Expression🔗

Syntax
logical-or-expression logical-or-expression ? expression : conditional-expression
Constraints
  1. The condition expression must result in a boolean-assignable value.
  2. Both the left and the right operands must result in a compatible type.
Semantics
  1. The condition operand is evaluated first, if it results in a true value, the left operand is the result of the expression, otherwise the right operand is the result.
  2. If the left operand is the result, the right operand must not be evaluated, and vice versa.

9.8.20.Assignment Expression🔗

Syntax
conditional-expression conditional-expression assignment-operator assignment-expression = &= &&= |= *= /= += -= ^= %= <<= >>= **= ||= ??=
Constraints
  1. The left operand must be a valid mutable lvalue.
  2. Both operands must meet all Constraints, as declared in each operator’s section.
Semantics
  1. For non-simple assignment operations (Not =), the result of an assignment expression is the left operand and right operand’s result according to the operator before the = operator. As a side effect, the result of this operator is written to the left operand’s object.
  2. For simple assignment operations, the result of an assignment expression is the right operand’s value. As a side effect, the right operand’s value is written to the left operand’s object.

9.8.21.Top Level Expression🔗

Syntax
assignment-expression

9.8.22.Loop Condition Expression🔗

Syntax
( expression ) expression
Constraints
  1. The operand must result in a boolean-assignable value.
Semantics
  1. The result of the loop condition expression is a boolean true/false value.

9.9.Type Expressions🔗

Syntax
array-type-expression

9.9.1.Type Name Expressions🔗

Syntax
type-keyword identifier module-name :: identifier
Constraints
  1. The referenced type must be accessible in the current scope.
Semantics
  1. References a declared/imported type.
  2. The order of type declarations must be irrelevant to when its referenced.

9.9.2.Type Parameter Instantiation Expressions🔗

Syntax
type-name-expression type-name-expression type-parameter-instatiation < type-expression-list > type-expression type-expression-list , type-expression
Constraints
  1. The type being referenced must support type parameters and have declared type parameters.
  2. Each type parameter must match the one on the declared type.
Semantics
  1. Fills out a referenced type’s type parameters.

9.9.3.Nullable Type Expressions🔗

Syntax
parameterized-type-expression parameterized-type-expression ?
Semantics
  1. Declares a type to be nullable.
  2. Variables, properties, fields or function arguments marked as nullable may be set as null.

9.9.4.Array Type Expressions🔗

Syntax
nullable-type-expression array-type-expression [] array-type-expression readonly []
Semantics
  1. References an array of a specific type.
  2. Declaring a readonly array prohibits all modification of the array’s elements.

9.10.Declarations🔗

Syntax
function-declaration extension-function-declaration variable-declaration struct-declaration enum-declaration variant-type-declaration interface-declaration class-declaration module-declaration import-declaration module-declaration import-declaration identifier module-name :: identifier

9.10.1.Declaration Modifiers🔗

Syntax
declaration-modifier native export const
Constraints
  1. No declaration modifier may be set more than once.

9.10.2.Type Parameter Lists🔗

Syntax
< type-parameter-list > type-parameter type-parameter-list , type-parameter identifier class identifier class identifier extends type-expression value identifier enum identifier

9.10.3.Module Declarations🔗

Syntax
regular-module-declaration native-module-declaration module module-name native module module-name from line-string-literal
Concepts
Module name
The name of the module itself declared after the module keyword.
Native Library Name
The string literal declared after the from keyword in a native module declaration. It is a file name for the dynamically-loadable native C/C++ library that any native functions declared in the file will be linked to. The string must not include the file extension. (eg: .dll)
Constraints
  1. The file name/path referenced by the native library path, if present, must be a valid path to a dynamically linkable library. The path must be accessible to the compiler and known at compile time.
  2. It is not required for a module declaration to declare a name unique to the file it’s declared in. Multiple files may share the same namespace.
Semantics
  1. A module declaration is used by import statements to know from which file to import certain symbols.
  2. Adding a module declaration is fully optional.
  3. Omitting the module declaration means the file will be able to export any symbols.

9.10.4.Import Declarations🔗

Syntax
import module-name
Constraints
  1. The import statement must result in at least one symbol being included in the source file. If no symbols are found with the namespace specified in the import, then the import is considered a failure.
Semantics
  1. Import all export symbols with the specified module name namespace into the source file.
  2. All IR, or source files, the compiler is able to find that share the specified namespace are imported into the current source file.
  3. When an IR file, or valid source file is found that is declared as native, the native module need not be loaded.
  4. During importing, any currently existing native bindings should also be checked for import. This is because native bindings can be registered without a pre-existing Tetral IR or source file to represent the declarations.

9.10.5.Function Declarations🔗

Syntax
declaration-modifiers type-expression identifier function-definition function-argument-declaration function-argument-list , function-argument-declaration type-expression identifier ... type-expression identifier type-arguments ( function-argument-list ) block-statement
Constraints
  1. The name and parameter types must not match a function that already exists in the current scope.
  2. Function argument lists can only ever have one variadic argument: the last one. Multiple variadic arguments or a variadic argument not being the last one are invalid.
  3. Functions declared with the export keyword can only be declared in the global scope.
  4. Functions declared with the native keyword must not have a function body.
Description

Declares a function that will be accessible in the current scope.

9.10.6.Extension Function Declarations🔗

Syntax
declaration-modifiers type-expression extension-function-name function-definition type-expression . identifier
Constraints
  1. The type referenced in the extension-function-name must be a valid type.
  2. The function may not access any private variables declared in the extended type if it is a class type.
Semantics

9.10.7.Variable Declarations🔗

Syntax
declaration-modifiers type-expression identifier declaration-modifiers type-expression identifier = expression
Constraints
  1. Must not have the name of an already accessible variable in the current scope.
  2. If a value is specified for the declaration, the variable’s resulting value must match the declared type, or be easily convertible to the variable’s type.
  3. If the variable is declared with const, then a value must be specified.
  4. Variable declared with the const modifier may not be modified at a later time.
  5. Variables declared with the export keyword must only be declared in the global scope.
  6. Variables cannot be declared with the following keywords:
    • native
  7. If an initializer value is present, the initializer cannot reference the declared variable.
  8. If the variable’s type cannot be default-initialized, then a value must be explicitly specified. (See )
Semantics
  1. Declares a variable or a constant that will be accessible in the current scope.
  2. If an initializer value is present, it becomes the value of the variable.
  3. Variables declared with the export keyword are made available for access outside the declaring file.

9.10.8.Struct Declarations🔗

Syntax
declaration-modifiers struct identifier { property-declaration } type-expression identifier type-expression identifier = expression
Constraints
  1. A struct must not be declared with the native modifier.
  2. Struct’s must only be declared in the main scope of a source file.
  3. Each struct property must have a unique name.
  4. Each struct property, if a default value is set, must have an expression whose type is assignable to the property’s type.
  5. Struct properties may not directly or indirectly reference the declared struct type unless through a nullable value.
Semantics
  1. Declares a struct data type and its properties.

9.10.9.Enum Declarations🔗

Syntax
declaration-modifiers enum identifier { enum-constant-declaration-list } enum-constant-declaration enum-constant-declaration-list , enum-constant-declaration enum-constant-declaration-list , identifier identifier = expression
Constraints
  1. An enum type must not be declared with the same name as an existing type in the same namespace.
  2. Each enum constant declaration must have a unique name.
  3. Any enum constant declared with a value expression must be an expression which only contains integer constant operands.
Semantics
  1. An enum declaration declares an enumeration data type.
  2. The ordinal value of each declared enum constant is either the value of the previous declared constant plus 1, if the constant has no specified value. Otherwise, if the constant has a specified value, its value becomes the result of its expression.

9.10.10.Variant Declarations🔗

Syntax
declaration-modifiers variant-prefix { variant-declaration-list } variant identifier type-arguments variant-declaration variant-declaration-list , variant-declaration variant-declaration-list , identifier identifier ( function-argument-list )
Constraints
  1. A Variant may not be declared with the same name as an existing declaration in the same namespace.
  2. Each declared variant of a variant type declaration must have a unique name.
Semantics
  1. Declares a variant type with the specified name and variants.
  2. Declares each variant’s properties.

9.10.11.Interface Declarations🔗

Syntax
declaration-modifiers interface-prefix { interface-method-declaration } interface identifier type-arguments interface-extensions-declaration extends type-name-list type-name-expression type-name-list , type-name-expression type-expression identifier function-definition
Constraints
  1. Interfaces can only be declared in a source file’s global scope.
Semantics

9.10.12.Class Declarations🔗

Syntax
declaration-modifiers class-prefix { class-property-declaration } class identifier type-arguments class-extension-declaration class-implements-declaration extends type-name-expression implements type-name-list class-property-modifier public private protected static override const class-field-declaration class-method-declaration class-constructor-declaration class-property-modifiers type-expression identifier class-property-prefix class-property-prefix = expression class-property-prefix function-definition class-property-modifiers constructor ( function-argument-list ) block-statement
Constraints
  1. Classes may only be declared in a file’s global scope.
  2. Classes must not be declared with the same name as an already existing function, struct, enum, interface or global variable.
  3. Classes implementing interfaces must declare a valid method implementation for every function outlined by its interfaces.
  4. Classes may not implement 2 or more interfaces with methods whose implementation would cause other Constraints to be violated.
  5. Classes may not extend themselves, directly or indirectly.
  6. Classes may not extend a class that has not been marked with the extendable keyword.
  7. Classes may only extend other valid classes.
  8. Classes may only implement valid interfaces.
  9. Classes may not extend classes if the extension would cause an inheritence cycle.
Semantics
  1. The same padding and alignment Semantics apply to classes as do to structs.
9.10.12.1.Class Fields🔗
Constraints
  1. Classes may not have 2 or more fields with the same name.
  2. Fields declared with the const modifier must either have a value specified by default or be initialized in the constructor.
  3. If a field has a default value, its value must be a valid expression that results in a type compatible with the field’s type.
Semantics
  1. Declares an accessible property.
9.10.12.2.Class Constructors🔗
Constraints
  1. Classes may not have 2 or more constructors with the same function signature.
  2. Constructors may not be declared with the override or static keyword.
  3. Constructors may not return a value.
  4. All Constraints that apply to regular function argument lists also apply to constructor arguments.
  5. If a class is declared with a base type that requires explicit initialization, then each constructor declared in a class must initialize the base type with a super-constructor-expression.
Semantics
9.10.12.3.Class Methods🔗
Constraints
  1. The declared return type must be a valid type.
  2. The same Constraints that apply to regular function declarations also apply to method declarations, except for those which cannot be applied to method declarations.
  3. Classes may only declare functions with the same name if the argument signatures differs.
  4. Classes may not override any methods declared in an inherited type that have the const keyword.
  5. Classes may not override any methods declared in an inherited type that have the const keyword.
  6. Classes overriding methods from an inherited class or interface must use the override modifier.
  7. A method declared with the static modifier cannot also use the modifier override.
Semantics
  1. Declares a member function that belongs to the class the method was declared in.
9.10.12.4.Class Access Modifiers🔗
Constraints
  1. Each modifier is mutually exclusive to another access modifier.
Semantics
  1. Access modifiers modify how fields and methods may be accessed from outside the class the symbol was declared in.
  2. The private keyword ensures a class symbol is only accessible in the class it was declared in.
  3. The protected keyword ensures a class symbol is only accessible in the class it was declared in, or in a class extending the class.
  4. The public modifier allows a class symbol to be accessed from anywhere.
  5. Omitting the access modifier is equivalent to using the public access modifier.

9.11.Statements🔗

Syntax
labeled-statement declaration body-statement block-statement for-loop-statement for-each-loop-statement do-while-statement while-statement switch-statement if-statement return-statement control-flow-statement assert-statement expression

9.11.1.Block Statements🔗

Syntax
{ statement }
Description

Declares a list of statements delimited by { and } characters.

Variables declared inside of block statements cannot be referenced from outside of that block.

9.11.2.Loop Flow Control Statements🔗

Syntax
continue identifier break identifier
Description

Influences the way a loop executes. Continue statements instruct the loop to move on to the next iteration of execution, while break statements cause the loop to be exited early before its condition can evaluate to a false value.

Control Flow statements can be declared with a label. This label is optional, if no label is specified, the statement changes how the immediate loop behaves. If a label is set, then it controls how the referenced loop behaves.

Constraints
  1. Can only be used inside a loop
  2. If a label is specified, the label can only reference a label of a loop the statement is inside.

9.11.3.If Statements🔗

Syntax
if statement-condition-expression body-statement if statement-condition-expression body-statement else body-statement
Description

Evaluates a condition and executes either a body, an else statement or moves on without executing.

Constraints
  1. The if statement’s condition must result in a value that can be assigned to a true/false value.

9.11.4.Labeled Statements🔗

Syntax
identifier : for-loop-statement identifier : for-each-loop-statement identifier : do-while-statement identifier : while-statement identifier : switch-statement

9.11.5.Switch Statements🔗

Syntax
9.11.5.1.Switch Expression🔗
switch statement-condition-expression { } simple-switch-case simple-case-list simple-switch-case block-switch-case block-case-list block-switch-case default case expression simple-switch-case-prefix : statement except case or default expression comma-delimited-expression , expression default case comma-delimited-expression switch-case-prefix => expression switch-case-prefix => block-statement

9.11.6.For Loop Statements🔗

Syntax
for ( variable-declaration ; expression ; expression ) body-statement
Terminology

A for loop has three operands, the first, second and third operand. The first, if present, declares a variable, the second evaluates a condition, and a third expression performs some operation to move the for-loop forward.

Constraints
  1. The second operand, if present, must result in a boolean-assignable value.
Semantics

9.11.7.For-Each Loop Statement🔗

Syntax
for ( type-expression identifier : expression ) body-statement
Constraints
  1. The right operand, after the identifier, must result in an array or a string.
  2. The variable declaration must be of the type that the right operand contains.
Semantics
  1. Iterates over each element of the right operand and performs some operation.
  2. The element being iterated over is the one declared in the identifier and must be available as a variable.

9.11.8.Do While Loop Statements🔗

Syntax
do block-statement while statement-condition-expression
Constraints
  1. The loop’s condition must result in a value that can be evaluated as a boolean.
Description

Evaluates a block of code until the defined loop condition results in a false value. The loop’s block will be evaluated at least once until the condition is reached.

9.11.9.Regular While Loop Statements🔗

Syntax
while statement-condition-expression block-statement
Constraints
  1. The loop’s condition must result in a value that can be evaluated as a boolean.
Description

Evaluates a block of code until the defined loop condition results in a false value. If the condition results in a false value when the loop is first reached, the loop’s block is not evaluated at all.

9.11.10.Return Statements🔗

Syntax
return expression
Description

Causes the current function to halt execution and return to the caller.

Constraints
  1. Can only be used inside a function body.
  2. If the return statement is used in a non-void function, it must always return a value.
  3. If the return statement is used in a void function, it must never return a value.
  4. The value returned by a return statement, must be assignable to the function’s return type.

9.11.11.Yield Statements🔗

Syntax
yield expression
Constraints
  1. Can only be used inside a switch statement’s case.
  2. The yielded value must be a non-void value.
Semantics
  1. Evaluate an expression and return, or yield, it as the result of a switch statement’s case.

9.11.12.Assert Statements🔗

Syntax
assert expression assert expression : expression
Semantics
  1. Evaluates the condition operand. If the condition results in a true boolean-assignable value, nothing happens. Otherwise, an error is thrown.
  2. If the message operand is present, it is evaluated and used as the error message for the thrown error.
  3. If no message operand is present, it must be created from the values of the variables present in the condition expression. (See Message Generation section below).
  4. The inclusion of the assert statement in the compiled output is optional, as is the execution of the assert statement
Constraints
  1. The expression the assert statement evaluates must always result in a boolean-assignable value.
  2. The message expression, if present, must always result in a String value.
Message Generation

The messages used by assert statements, if one is not explicitly provided, should be composed of the values of each variable used in the expression, for example, when asserting that a variable named “foo” is equal to 10, the automatic error message should be composed of the expression string and followed by the variable’s value. In effect, turning the statement into this:

1
assert foo == 10 : "foo == 10, foo: ${foo}"
Examples
1
2
3
assert true // Does nothing
assert false // Assertion failed!
assert false : "message" // Assertion failed: message

9.12.Translation Unit🔗

module-header-declarations declaration declaration

10.Intermediate Representation (Bytecode Format)🔗

The result of the compilation of a Tetral source file should be a Tetral Bytecode file.

Bytecode files are binary files with little-endian byte ordering.

10.1.File Header🔗

Each Tetral IR file must be prefixed with a file header to provide information about the file’s contents. The layout of the header shall be as follows.

The header shall begin with an ASCII string that must always have the value TetralLang. This shall be immediately followed by a 16-bit unsigned integer denoting the file’s version.

The file version integer is an incrementing integer which specifies what version of the Tetral bytecode format the file complies with.

The following file versions are valid

Table 12 - Tetral File Versions
Version numberDescription
1The first version of the Tetral Language

The vile version integer must then followed by a repeating pattern. Each instance of this pattern shall begin with a single unsigned byte, the entry type. No entry may be defined twice. Each entry’s presence in the file is optional.

The following types are valid.

Table 13 - Bytecode Header Entry Types
NameHexadecimal ValueDescription
END0x00Special entry type that shall mark the end of the header.
STRTABLE0x01String table information
STRDATA0x02String pool information
TYPETABLE0x03Type table information
FUNCTABLE0x04Function table information
INSTRBLOCK0x05Instruction block information
RDATA0x06Read only data block information
MDATA0x06Pre-defined metadata properties
ADATA0x06List of arbitrary key,value string pairs.
MODINFO0x07Information about the import and export list.

10.1.1.The STRTABLE Entry🔗

This entry shall be comprised of a 64-bit unsigned integer: an offset of the string table’s data from the start of the file, and a 32-bit unsigned integer: the number of entries in the string table.

(See 10.2. String Pool Table)

10.1.2.The STRDATA Entry🔗

This entry shall be comprised of two 64-bit unsigned integers, the first is an offset and the second is a size. The offset specifies where, from the start of the file, the file’s string pool data is located and the size specifies the size (in bytes) of the file’s string pool data.

(See 10.3. String Pool Data)

10.1.3.The TYPETABLE Entry🔗

This entry shall be comprised of a 64-bit unsigned integer: an offset of the type table’s data from the start of the file, and a 32-bit unsigned integer: the number of entries in the type table.

(See 10.4. Type Table)

10.1.4.The FUNCTABLE Entry🔗

This entry shall be comprised of a 64-bit unsigned integer: an offset of the function table’s data from the start of the file, and a 32-bit unsigned integer: the number of entries in the function table.

(See 10.5. Function Table)

10.1.5.The INSTRBLOCK Entry🔗

This entry shall be comprised of the following pieces of data. The values shall appear in the binary in the order they are defined here.

Instruction block offset
A 64-bit unsigned integer that must specify the file's instruction block offset from the start of the file.
Instruction block size
A 32-bit unsigned integer that must specify the file's instruction block size in bytes.
Instruction count
A 32-bit unsigned integer that must specify how many instructions are in the instruction block.

(See 10.6. Instructions Block)

10.1.6.The RDATA Entry🔗

This entry shall be comprised of two 64-bit unsigned integers, they are as follows and appear in the order they are listed.

  1. The offset of the data block from the start of the file.
  2. The size of the data block, in bytes.

(See 10.7. Data Block)

10.1.7.The MDATA Entry🔗

This entry shall be comprised of the following values which and appear in the order they are listed.

The file's global scope size
A 64-bit unsigned integer that shall determine how many bytes are required to represent the variables stored in the file's global scope.
Entrypoint function index

An 32-bit unsigned integer index that shall reference an entry in the function table. This referenced function shall be where execution of this file shall begin.

A value (in hexadecimal) of 0xFFFFFFFF shall mean that the file has no entrypoint and cannot be executed by itself.

10.1.8.The ADATA Entry🔗

This entry shall begin with a 32-bit unsigned integer that denotes the number of key value pairs stored in the section.

It shall then be followed by a number of key-value pairs of strings. The number of these pairs shall be determined by the prefixing 32-bit unsigned integer. Each string must be prefixed with a 16-bit unsigned integer denoting the length of the string and must then be followed by that many bytes of UTF-8 code units.

10.2.String Pool Table🔗

To be referred to as the String Pool Table, or just the String Table, shall be a list of 32-bit unsigned integer pairs. The number of entries in the table is determined in the STRTABLE entry in the file header.

Each 32-bit unsigned integer in each pair is defined as follows:

String Pool Offset
The first 32-bit unsigned integer must be an address of a string's content in the String Pool Data.
String Length
The second integer must be the number of UTF-8 code units in the string.

The first entry in the list may be a “null” string entry, meaning an entry with offset 0 and length 0, used as a placeholder for an empty, or null, string.

If this section is present in a bytecode file, then the String Pool Data section must be present too, as well as the corresponding entries in the header.

10.3.String Pool Data🔗

This section shall be a block of UTF-8 code units. The size and location of this section shall determined by the STRPOOL entry in the file’s header.

If this section is present in a bytecode file, then the String Pool Table section must be present too, as well as the corresponding entries in the header.

10.4.Type Table🔗

This section shall be a list of type definitions. The number of definitions in this section and the section’s location in the file shall be determined by the TYPETABLE entry in the header.

Each definition must be prefixed with 2 values, an unsigned 32-bit integer and an 8-bit unsigned integer.

The first integer shall be the “type index” of the type definition. This index is used in function table entries, other type table entries, and in some IR instructions to reference the type definition.

The second 8-bit unsigned integer shall mark the type of the entry. The following values are considered valid.

Table 14 - Type Table Definition Types
NameHexadecimal Value
ARRAY0x00
FUNCSIGN0x01
STRUCT0x02
ENUM0x03
INTERFACE0x04
CLASS0x05
NULLABLE0x06
PARAMETERIZED0x07
TYPEPARAMETER0x08
PARAMLIST0x09
IMPORTED0x0A

Depending on the type, one of the schemas defined in the following sections is used for the type.

Some entries may reference a “null type index,” this is a type index constant with the hexadecimal value of 0xFFFFFFFF and means that the type index references no type

10.4.1.Array Values Inside Entries🔗

Multiple entries in the type table may define a list or array of which holds some kind of values. An array is a sequential list of data. The terms array and list will be used interchangeably inside the following sections.

All arrays inside type table entries are prefixed with a 16-bit unsigned integer that determines the number of entries in that array or list.

10.4.2.Arrays, Nullable Definitions and Reference Definitions🔗

These are defined in one section since their schema is identical, but each type results in a different type construct.

These entries shall define only a single 32-bit unsigned integer value. It is the type index of the type they reference.

The referenced type index must not be a null type index.

10.4.3.Function Signatures🔗

Function signatures shall defined with the following values. The values appear in the binary in the order they are defined here.

Return type index
32-bit unsigned integer index into the type table, referencing the type the function signature uses as a return type. This may not be a null type index.
Variadic state
8-bit unsigned integer that shall have a value of either 0 or 1 used to determine if the function takes in a variable number of arguments.
Parameter list index
A 32-bit unsigned integer referencing the PARAMLIST entry that outlines the type arguments for this type. If the type has no type arguments, this will be a null type index.
Argument types list

An array of 32-bit unsigned type indexes referencing the type of the corresponding function argument's type.

None of these may be null type indices. If the variadic state of the function is set to 1, then the last parameter to appear in this list must reference an entry with the type ARRAY.

10.4.4.Structs🔗

Structs are defined with the following values. The values appear in the binary in the order they are defined here.

Name index
32-bit unsigned integer index referring to the entry in the file's string table that is used as the type's name.
Namespace index
32-bit unsigned integer index referring to the entry in the file's string table that is used as the type's namespace. If the type has no namespace, the referenced entry will be the table's null entry.
Property list

A list of struct properties. Each entry in this list shall contain the following data in the order they are written here.

Property Name
32-bit unsigned integer index referring to the entry in the file's string table that is used as the property's name.
Property Type
32-bit unsigned integer index referring to the type index in the file's type table that shall be the struct property's type.

10.4.5.Enums🔗

Enumerations shall be defined with the following values. The values appear in the binary in the order they are defined here.

Name index
32-bit unsigned integer index referring to the entry in the file's string table that is used as the type's name.
Namespace index
32-bit unsigned integer index referring to the entry in the file's string table that is used as the type's namespace. If the type has no namespace, the referenced entry will be the table's null entry.
Constant list
A list of 32-bit unsigned integers. Each integer in this list shall be a reference to an entry in the file's string table. The constant value of each name in this list shall be its index in the list.

10.4.6.Interfaces🔗

Interfaces are defined with the following values. The values appear in the binary in the order they are defined here.

Name index
32-bit unsigned integer index referring to the entry in the file's string table that is used as the type's name.
Namespace index
32-bit unsigned integer index referring to the entry in the file's string table that is used as the type's namespace. If the type has no namespace, the referenced entry will be the table's null entry.
Type parameter list index
A 32-bit unsigned integer referencing the PARAMLIST entry that outlines the type arguments for this type. If the type has no type arguments, this will be a null type index.
Extends count
A 32-bit unsigned integer that shall determine how many other interfaces an interface extends.
Extends list

An array of 32-bit unsigned integers that shall list the extended interfaces of an interface. The size of this list shall be determined by the Extends count value.

Each type index in this array must reference a INTERFACE type table entry, and may not be a null type index.

Method count
A 32-bit unsigned integer that shall determine how many methods the interface declares.
Method list

This value shall be an array of 32-bit unsigned integers. The number of entries in this list shall be determined by the Method count value.

Each integer value in this list must be an index into the file's function table, referencing the function that's declared by an interface. No entry in this list may be a null function index.

10.4.7.Classes🔗

Classes shall be defined with the following values. The values appear in the binary in the order they are defined here.

Name index
32-bit unsigned integer index referring to the entry in the file's string table that is used as the type's name.
Namespace index
32-bit unsigned integer index referring to the entry in the file's string table that is used as the type's namespace. If the type has no namespace, the referenced entry will be the table's null entry.
Type parameter list index
A 32-bit unsigned integer referencing the PARAMLIST entry that outlines the type arguments for this type. If the type has no type arguments, this will be a null type index.
Parent type
Implements count
Implements list
Member count
Method list

10.4.8.Parameter List Instantiation🔗

Parameter lists define the types another type requires to be complete.

Parameter lists are defined with the following values. The values appear in the binary in the order they are defined here.

Referenced type index
Type count
Type list

10.4.9.Imported Type🔗

Imported types are types which are not defined in the current file, but are instead defined in another file and must be imported. They are defined with the following values. The values appear in the binary in the order they are defined here.

Name index
32-bit unsigned integer index referring to the entry in the file's string table that is used as the type's name.
Namespace index
32-bit unsigned integer index referring to the entry in the file's string table that is used as the type's namespace. If the type has no namespace, the referenced entry will be the table's null entry.

10.5.Function Table🔗

10.6.Instructions Block🔗

10.7.Data Block🔗

10.8.Import List🔗

10.9.Export Table🔗

11.Bytecode Instructions🔗

The Tetral Bytecode Instruction Set is a simple instruction set with instructions that have pre-defined layouts for their arguments. Which instructions exist, their arguments and their numerical codes are defined in the following sections.

Many instructions operate on registers. A register is a virtual container of memory. The Bytecode Instruction Set uses 32 registers, each 64-bits large.

Register 0 is reserved for the program counter. An index of the current instruction being executed by the execution environment. This register will be referred to as the pcr, or as the program counter register.

Each instruction’s numerical value is represented as a hexadecimal number prefixed with 0x

11.1.General Purpose Instructions🔗

11.2.Stack Memory Instructions🔗

11.3.Global Memory Instructions🔗

11.4.Closure Instructions🔗

11.5.Heap Memory Instructions🔗

11.6.Function Call Instructions🔗

11.7.Foreign Symbol Instructions🔗

11.8.Conversion Instructions🔗

11.9.Unary Instructions🔗

11.10.Binary Instructions🔗

11.10.1.Integer-only Binary Instructions🔗

11.10.2.Boolean-only Binary Instructions🔗

11.10.3.Arithmetic Binary Instructions🔗

11.10.4.Comparison Instructions🔗

11.10.5.String/Array Instructions🔗

12.The Standard Library🔗

This section defines the modules that are part of the Tetral Standard Library. Whether any function defined in the following sections is implemented natively or within Tetral itself is explicitly left up to implementations to decide on.

The export keyword in each stated type and function definition is omitted for brevity. Similarly, definitions of classes will only list and describe public methods, fields and constructors, as such, the public keyword is omitted.

12.1.The std Module🔗

The most basic standard library functions that would be required by a program.

12.1.1.The Result Variant🔗

Declaration
variant Result<V, E> {
Error(E err),
Ok(V value)
}

12.1.2.The List Class🔗

Declaration
class List<T> {
constructor()
constructor(T readonly[] elements)
constructor(uint32 initialCapacity)

bool isEmpty()
void clear()
uint32 size()

Result<T, Error> get(int32 index)
Result<T, Error> set(int32 index, T value)
bool add(T value)
bool add(T value, int32 index)
}
Constructors

The List class shall provide three constructors, they are defined as the following:

  1. The first constructor shall accept no arguments, it shall initialize an array with no values and an implementation-defined initial capacity.
  2. The second constructor shall take in a readonly array of elements. The list instance is then initialized such that it contain those elements.
  3. The third constructor shall take in a 32-bit unsigned integer, the initial capacity of the list. The list must then be initialized such that it is able to hold at least that many elements.
Methods
isEmpty
This method shall take no input arguments and shall return true if the list contains no elements. Otherwise, it shall return false.
clear
The clear method shall remove all elements stored in the list. Any calls to the isEmpty shall return true until more elements are inserted into the list.
size
The size method shall return the number of elements currently stored in the list.
get
This method shall take an index as input and return a result containing the element at the specified index inside the list. If the index is outside the bounds of the list, the returned result shall be erroneous.

12.1.3.The Map Class🔗

12.1.4.The Set Class🔗

12.1.5.Reading Terminal Input, readln🔗

Signature
string readln()
Description

The read line function shall block execution until the user has submitted input from the command line.

12.1.6.Printing to Standard Out, println🔗

Signature
void println(string message)
Description

The print line function shall print the specified message to the standard output of the program.

12.1.7.Reading Environment Variables, getenv🔗

Signature
string? getenv(string name)
Description

The getenv function shall take as input the name of an environment variable and return the value associated with that environment variable.

If no value is associated with that value, a null value shall be returned instead.

12.1.8.Writing Environment Variables, setenv🔗

Signature
void setenv(string name, string value)
void setenv(string name, string value, bool overwrite)
Description

This function is defined with two overloads. Both definitions shall take in a variable name and a value. One of the overloads shall take in a boolean value. If this value is false, then the envirnoment variable will not be overwritten if it is already set.

The function shall change a value in, or add to, the list of environment variables.

12.1.9.Numeric Parsing Functions🔗

Signatures
int32? parseInt(string s)
uint32? parseUint(string s)
int64? parseInt64(string s)
uint64? parseUint64(string s)
float32? parseFloat(string s)
float64? parseFloat64(string s)
Description

Each of the defined functions shall take as input a single string, interpreted as the string representation of the number to parse.

Any whitespace in the beginning of the input string shall be trimmed. The trimmed string shall then be parsed as a number of the function’s corresponding type.

If the numerical value was successfully parsed, it shall be returned, if an error occurred during parsing, a null value shall be returned instead.

The specific algorithm used for parsing each numerical type’s value is implementation-defined, but it must accept any string representation of the corresponding numerical type’s value as valid input.

12.1.10.Enum parsing, parseEnum🔗

Signature
E? <enum E> parseEnum(string s)
Description

The enum parsing function shall take a string as input and attempt return an enum value with the equivalent exact name as the string.

If no enum constant exists with the name, a null value shall be returned. Otherwise, that enum constant shall be returned.

12.2.The std::strings Module🔗

12.2.1.Creating String Objects From UTF Data🔗

Result<string, StringError> stringFromUtf8(uint8 readonly[] bytes)
Result<string, StringError> stringFromUtf16(uint16 readonly[] bytes)
Result<string, StringError> stringFromUtf32(uint32 readonly[] codepoints)

12.2.2.String Trimming Functions🔗

string string.trim()
string string.trimLeft()
string string.trimRight()

string string.substring(uint32 start)
string string.substring(uint32 start, uint32 end)

uint32? string.indexOf(uint8 utf8char)
uint32? string.indexOf(uint8 utf8char, uint32 start)
uint32? string.indexOf(uint32 codepoint)
uint32? string.indexOf(uint32 codepoint, uint32 start)
uint32? string.indexOf(string other)
uint32? string.indexOf(string other, uint32 start)

uint32? string.lastIndexOf(uint8 utf8char)
uint32? string.lastIndexOf(uint8 utf8char, uint32 end)
uint32? string.lastIndexOf(uint32 codepoint)
uint32? string.lastIndexOf(uint32 codepoint, uint32 end)
uint32? string.lastIndexOf(string other)
uint32? string.lastIndexOf(string other, uint32 end)

bool string.contains(uint8 utf8char)
bool string.contains(uint8 utf8char, uint32 end)
bool string.contains(uint32 codepoint)
bool string.contains(uint32 codepoint, uint32 end)
bool string.contains(string other)
bool string.contains(string other, uint32 end)

bool string.replace(string sequence, string with)

bool string.startsWith(string other)
bool string.endsWith(string other)

uint32? string.codepointAt(uint32 index)
uint32 string.codepoints()

uint32[] string.toUtf32()
uint16[] string.toUtf16()
uint8[] string.toUtf8()

bool string.isEmpty()
bool string.isBlank()

string string.toUpperCase()
string string.toLowerCase()

12.3.The std::math Module🔗

12.4.The std::io Module🔗

12.4.1.File encoding enumeration🔗

enum CharacterEncoding {
  UTF8 = 0,
  UTF16 = 1,
  UTF32 = 2,
  UTF16LE = 3,
  UTF16BE = 4,
  UTF32LE = 5,
  UTF32BE = 6,
  ISO_8859_1 = 7,
  US_ASCII = 8,
  WINDOWS_1252 = 9,
}

12.5.The std::filepaths Module🔗

12.5.1.Accessing the current working directory, cwd🔗

string cwd()

12.5.2.Accessing the current program directory, pwd🔗

string pwd()

12.5.3.Reading a Path’s File Extension🔗

string extname(string path)

12.5.4.Reading a Path’s Base Name🔗

string basename(string path)

12.5.5.Reading a Path’s Directory Name🔗

string dirname(string path)

12.5.6.Normalizing paths🔗

string normalize(string path)

12.5.7.Path joining🔗

string joinPaths(string base, string... others)

12.5.8.Relativizing Paths🔗

string relativePath(string from, string to)

12.5.9.Absolute Paths🔗

string absolutePath(string path)
bool isAbsolutePath(string path)

12.5.10.Real Paths🔗

Result<string, PathError> realPath(string path)

12.6.The std::reflection Module🔗

12.6.1.Data Type Kind, DataTypeKind🔗

enum DataTypeKind {
  VOID = 0,
  PRIMITIVE = 1,
  STRING = 2,
  ARRAY = 3,
  READONLY_ARRAY = 4,
  FUNCTION = 5,
  ENUM = 6,
  VARIANT = 7,
  VARIANT_TYPE = 8,
  INTERFACE = 9,
  CLASS = 10,
  STRUCT = 11,
  NULLABLE = 12,
}

12.6.2.Tetral Data Type Object, DataType🔗

interface DataType {
  DataTypeKind getKind()

  bool isDefaultInitializeable()

  string getNamespace()
  string getSimpleName()
  string getName()

  uint32? getPropertyCount()
  string? getPropertyName(uint32 index)
  DataType? getPropertyType(uint32 index)

  uint32? getArgumentCount()
}

12.6.3.Accessing Type Data, getTetralDataType🔗

DataType getTetralDataType<T>()

12.7.The std::json Module🔗

12.7.1.Serialization Errors, JsonError🔗

enum JsonErrorType {
  SCHEMA_ERROR = 0,
  OBJECT_ERROR = 1,
}

class JsonError {
  public JsonErrorType type
  public string message

  constructor(JsonErrorType type, string message) {
    this.type = type
    this.message = message
  }
}

12.7.2.Serializing values, stringify🔗

Result<string, JsonError> <T> stringify(T value)

12.7.3.Deserializing values, parseJson🔗

Result<T, JsonError> <T> parseJson(string json)