This document defines the formal syntactic grammar of the Kyro language using a modified context-free BNF (Backus-Naur Form) notation, accompanied by practical code examples.
Lexical Tokens and Keywords
Kyro keywords are reserved and cannot be used as identifiers.
keyword -> "and" | "class" | "else" | "false" | "fn" | "property"
| "for" | "if" | "in" | "nil" | "or" | "echo" | "return"
| "super" | "self" | "true" | "var" | "while"
| "try" | "catch" | "throw" | "break" | "continue"
symbol -> "(" | ")" | "{" | "}" | "[" | "]" | ":" | "?" | ","
| "." | "-" | "+" | ";" | "/" | "*" | "%" | "!"
| "!=" | "=" | "==" | "+=" | "-=" | "*=" | "/=" | "%="
| "<" | "<=" | ">" | ">=" | "&" | "|" | "^" | "~" | "<<" | ">>"
Program and Declarations
A Kyro program is a sequence of declarations executed dynamically from top to bottom.
program -> declaration* eof
declaration -> classdecl | propdecl | fundecl | vardecl | statement
Class Declaration
Defines a class. Class bodies support class variables, methods (fn), and property getters (property). Multiple inheritance is supported by separating parent classes with commas (< Parent1, Parent2). If no superclass is specified, classes implicitly inherit from Object.
classdecl -> "class" identifier ( "<" identifier ( "," identifier )* )? "{" ( vardecl | methoddecl )* "}"
methoddecl -> ( "fn" | "property" ) fundecl
class Flyer {
fn fly(self) { return "flying"; }
}
class Swimmer {
fn swim(self) { return "swimming"; }
}
// Multiple Inheritance
class Duck < Flyer, Swimmer {}
Function and Property Declarations
Defines a named callable block (fn) or a getter property (property) that auto-evaluates on access without parentheses.
fundecl -> identifier "(" parameters? ")" block
propdecl -> "property" fundecl
parameters -> parameter ( "," parameter )*
parameter -> ( identifier | "self" ) ( "=" expression )?
fn multiply(x, y = 2.0) {
return x * y;
}
property is_ready() {
return true;
}
echo is_ready; // Auto-executes getter
Variable Declaration
Declares variables dynamically, supports multi-variable declarations, and binds values using list/dictionary destructuring.
vardecl -> "var" identifier ( "," identifier )* ( "=" expression ( "," expression )* )? ";"
| "var" "[" identifier ( "," identifier )* "]" "=" expression ";"
| "var" "{" identifier ( "," identifier )* "}" "=" expression ";"
var x = 10.0;
var a, b = 1, 2;
var [first, second] = ["apple", "banana"];
var { name, role } = { "name": "bob", "role": "dev" };
Statements
Statements represent execution units that do not evaluate to values.
statement -> exprstmt | echostmt | block | ifstmt | whilestmt
| forstmt | forinstmt | returnstmt | trycatchstmt
| throwstmt | breakstmt | continuestmt
Expression Statement
Evaluates an expression and discards the result.
exprstmt -> expression ";"
list.push(5.0);
Echo Statement
Evaluates an expression and prints its string representation followed by a newline.
echostmt -> "echo" expression ";"
echo "hello world";
Block Statement
Defines a nested lexical scope for its inner declarations.
block -> "{" declaration* "}"
{
var local = "nested";
echo local;
}
If Statement
Conditional branching execution.
ifstmt -> "if" "(" expression ")" statement ( "else" statement )?
if (x > 10.0) {
echo "greater";
} else {
echo "less or equal";
}
While Statement
Pre-test loop execution.
whilestmt -> "while" "(" expression ")" statement
while (x > 0.0) {
x = x - 1.0;
}
For Statement
A loop construct containing an initializer, condition, and increment expression.
forstmt -> "for" "(" ( vardecl | exprstmt | ";" )
expression? ";"
expression? ")" statement
for (var i = 0; i < 5.0; i += 1) {
echo i;
}
For-In Statement
Loops over elements of lists, keys of dictionaries, or custom iterators implementing __next__.
forinstmt -> "for" "(" "var" identifier "in" expression ")" statement
var list = ["a", "b", "c"];
for (var val in list) {
echo val;
}
Return Statement
Exits a function call, optionally returning an evaluated value.
returnstmt -> "return" expression? ";"
return true;
Try-Catch Statement
Gracefully catches runtime exceptions thrown inside the try block.
trycatchstmt -> "try" block "catch" "(" identifier ")" block
try {
var value = list[10.0];
} catch (err) {
echo "failed: " + err.message;
}
Throw Statement
Raises a runtime exception with an evaluated exception object.
throwstmt -> "throw" expression ";"
throw ValueError("something went wrong");
Expressions
Expressions evaluate to a single runtime value.
expression -> assignment
Assignment & Swapping
Assigns single or multiple values to variables, instance properties (invoking __setattribute__), or subscript indices (invoking __setitem__). Supports atomic variable swapping and compound assignment operators (+=, -=, *=, /=, %=).
assignment -> target ( "," target )* "=" expression ( "," expression )*
| target ( "+=" | "-=" | "*=" | "/=" | "%=" ) assignment
| ternary
target -> identifier | call "." identifier | call "[" expression "]"
name = "bob";
a, b = b, a; // Atomic variable swap!
x += 5; // Compound addition
list[2] = "mutated";
Ternary Operator
Inline conditional expression evaluating to the then branch if truthy, otherwise the else branch.
ternary -> logic_or ( "?" expression ":" expression )?
var status = age >= 18 ? "adult" : "minor";
Logic OR
Evaluates boolean short-circuiting disjunction.
logic_or -> logic_and ( "or" logic_and )*
true or false;
Logic AND
Evaluates boolean short-circuiting conjunction.
logic_and -> bitwise_or ( "and" bitwise_or )*
is_valid and x > 0.0;
Bitwise OR
Computes bitwise OR on numerical operands (invokes __or__ on instances).
bitwise_or -> bitwise_xor ( "|" bitwise_xor )*
var flags = status | 4.0;
Bitwise XOR
Computes bitwise XOR on numerical operands (invokes __xor__ on instances).
bitwise_xor -> bitwise_and ( "^" bitwise_and )*
var difference = mask1 ^ mask2;
Bitwise AND
Computes bitwise AND on numerical operands (invokes __and__ on instances).
bitwise_and -> equality ( "&" equality )*
var is_active = status & 1.0;
Equality
Comparisons for absolute equivalence or difference (invokes __eq__ or __ne__ on instances).
equality -> comparison ( ( "!=" | "==" ) comparison )*
x == y;
"apple" != "banana";
Comparison
Relational comparison operations (invokes __lt__, __le__, __gt__, or __ge__ on instances).
comparison -> bitwise_shift ( ( ">" | ">=" | "<" | "<=" ) bitwise_shift )*
x < 100.0;
Bitwise Shift
Computes bitwise left and right shifts (invokes __lshift__ or __rshift__ on instances).
bitwise_shift -> term ( ( "<<" | ">>" ) term )*
var shifted = value << 2.0;
Term
Addition and subtraction (invokes __add__ or __sub__ on instances).
term -> factor ( ( "-" | "+" ) factor )*
var sum = x + y;
Factor
Multiplication, division, and modulo calculations (invokes __mul__, __div__, or __mod__ on instances).
factor -> unary ( ( "/" | "*" | "%" ) unary )*
var product = x * y;
var rem = x % y;
Unary
Logical negation, arithmetic negation (__neg__), and bitwise invert (__invert__).
unary -> ( "!" | "-" | "~" ) unary | call
!is_ready;
-5.0;
~mask;
Call & Subscript Slicing
Function calls, class instantiations, property gets (__getattribute__), subscript indexing (__getitem__), and bracket slicing ([start:end:step]).
call -> primary ( "(" arguments? ")" | "." identifier | "[" subscript_index "]" )*
subscript_index -> expression | slice
slice -> expression? ":" expression? ( ":" expression? )?
arguments -> argument ( "," argument )*
argument -> expression | identifier "=" expression
math.square(x);
list[1:4:2]; // Slicing
str[::-1]; // Reverse string
Primary
Literals, groupings, identifiers, self/super accesses, collection literals, list comprehensions, and anonymous functions.
primary -> NUMBER | STRING | RAW_STRING | "true" | "false" | "nil" | "self" | identifier
| "super" "." identifier
| "(" expression ")"
| listliteral | dictliteral
| lambda
List Literal & List Comprehension
Constructs a list object or evaluates a list comprehension with optional conditional guards.
listliteral -> "[" expression "for" "var" identifier "in" expression ( "if" expression )? "]"
| "[" ( expression ( "," expression )* )? "]"
var fruits = ["apple", "banana"];
var evens = [x * 2 for var x in range(0, 10) if x % 2 == 0];
Dictionary Literal
Constructs a key-value dictionary object.
dictliteral -> "{" ( expression ":" expression ( "," expression ":" expression )* )? "}"
var user = { "name": "bob", "role": "dev" };
String Literals & Interpolation
Kyro evaluates dynamic format strings at scan-time via inline ${expr} interpolation. Multi-line raw strings are created using triple-quotes """ ... """.
string -> '"""' char* '"""'
| '"' ( char* | "${" expression "}" )* '"'
var label = "progress";
var percent = 50.0;
echo "${label}: ${percent}%";
var query = """
SELECT * FROM users;
""";