From 23240335309739837c49f8384d161e72828b710e Mon Sep 17 00:00:00 2001 From: bialger Date: Tue, 7 Oct 2025 01:46:01 +0300 Subject: [PATCH 1/2] docs: add submodule for Ovum documentation and remove outdated files - Introduced a new submodule for the Ovum documentation repository. - Deleted outdated documentation files including BUILD.md, README.md, and various reference materials to streamline the documentation structure. --- .gitmodules | 4 + docs | 1 + docs/BUILD.md | 58 --- docs/README.md | 11 - docs/reference/README.md | 28 -- docs/reference/builtin_types.md | 224 ----------- docs/reference/code_examples.md | 338 ---------------- docs/reference/control_flow.md | 60 --- docs/reference/design.md | 38 -- docs/reference/expressions_and_operators.md | 54 --- docs/reference/lexical_structure.md | 151 -------- docs/reference/nullable.md | 111 ------ docs/reference/object_model.md | 404 -------------------- docs/reference/runtime.md | 55 --- docs/reference/syntax.md | 86 ----- docs/reference/system_library.md | 202 ---------- docs/reference/types.md | 284 -------------- docs/reference/unsafe.md | 121 ------ 18 files changed, 5 insertions(+), 2225 deletions(-) create mode 100644 .gitmodules create mode 160000 docs delete mode 100644 docs/BUILD.md delete mode 100644 docs/README.md delete mode 100644 docs/reference/README.md delete mode 100644 docs/reference/builtin_types.md delete mode 100644 docs/reference/code_examples.md delete mode 100644 docs/reference/control_flow.md delete mode 100644 docs/reference/design.md delete mode 100644 docs/reference/expressions_and_operators.md delete mode 100644 docs/reference/lexical_structure.md delete mode 100644 docs/reference/nullable.md delete mode 100644 docs/reference/object_model.md delete mode 100644 docs/reference/runtime.md delete mode 100644 docs/reference/syntax.md delete mode 100644 docs/reference/system_library.md delete mode 100644 docs/reference/types.md delete mode 100644 docs/reference/unsafe.md diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..db37aa6 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "docs"] + path = docs + url = https://github.com/Ovum-Programming-Language/OvumDocs.git + branch = main diff --git a/docs b/docs new file mode 160000 index 0000000..6d0d63e --- /dev/null +++ b/docs @@ -0,0 +1 @@ +Subproject commit 6d0d63e212ab7c58c19e45f87e899408f2e51a46 diff --git a/docs/BUILD.md b/docs/BUILD.md deleted file mode 100644 index 37e38cd..0000000 --- a/docs/BUILD.md +++ /dev/null @@ -1,58 +0,0 @@ -# Build instructions for Ovum toolset - -This documents describes build process for Ovum programming language toolset and tests. - -## How to build and run - -Run the following commands from the project directory. - -1. Create CMake cache - -```shell -cmake -S . -B cmake-build -``` - -2. Build all targets - -```shell -cmake --build cmake-build -``` - -4. Run main executable - -* On Windows: - -```shell -.\cmake-build\ovum.exe -``` - -* On *nix: - -```shell -./cmake-build/bin/ovum World -``` - -5. Run tests - -* On Windows: - -```shell -.\cmake-build\ovum_tests.exe -``` - -* On *nix: - -```shell -./cmake-build/tests/ovum_tests -``` - -6. Installation - -Running this script will build and install Ovum main executable at `$HOME/ovum`. -Define `$SAVE_PREV` environment variable to save previous configuration. - -> There is only a shell script, so on Windows one should use Git Bash. - -```shell -./install.sh -``` \ No newline at end of file diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 508f41d..0000000 --- a/docs/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# Ovum Documentation Page - -This page contains documentation for the Ovum programming language. - -## Build instructions - -If you want to build Ovum from scratch, please read the [BUILD.md](./BUILD.md) file. - -## Ovum Language Reference - -If you want to read the Ovum language reference, please read the [README.md](../README.md) file. diff --git a/docs/reference/README.md b/docs/reference/README.md deleted file mode 100644 index 1f92c91..0000000 --- a/docs/reference/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# Ovum Language Reference - -This page contains the Ovum language reference. - -## About Ovum - -* [Ovum design principles](./design.md) -* [Ovum runtime](./runtime.md) -* [Code examples](./code_examples.md) - -## Language rules - -* [Lexical structure](./lexical_structure.md) -* [Syntax and semantics](./syntax.md) -* [Expressions and operators](./expressions_and_operators.md) -* [Type system](./types.md) -* [Control flow](./control_flow.md) -* [Unsafe operations](./unsafe.md) - -## Type system - -* [Object model](./object_model.md) -* [Nullable types](./nullable.md) - -## Standard functionality - -* [Built-in types](./builtin_types.md) -* [Standard library](./system_library.md) diff --git a/docs/reference/builtin_types.md b/docs/reference/builtin_types.md deleted file mode 100644 index 2ace559..0000000 --- a/docs/reference/builtin_types.md +++ /dev/null @@ -1,224 +0,0 @@ -# Built-in Reference Types - -This document describes the built-in reference types in Ovum, their methods, and the standard interfaces that all types implement. - -## String Type - -`String` is a reference type (not primitive) for text data. All strings are immutable by default and implement `IStringConvertible`, `IComparable`, and `IHashable`. - -### String Methods - -* `Length(): Int` - Returns the number of characters in the string -* `ToString(): String` - Returns the string itself (implements `IStringConvertible`) -* `IsLess(other: Object): Bool` - Lexicographic comparison (implements `IComparable`) -* `GetHash(): Int` - Returns hash code for the string (implements `IHashable`) -* `+` operator - String concatenation (e.g., `"Hello" + " " + "World"`) - -### String Usage - -```ovum -val greeting: String = "Hello, World!" -val length: Int = greeting.Length() // Returns 13 -val combined: String = "Hello" + ", " + "World!" - -// String comparison -val a: String = "apple" -val b: String = "banana" -val isLess: Bool = a.IsLess(b) // true (lexicographic order) - -// String hashing -val hash: Int = greeting.GetHash() -``` - -## Nullable Types - -> **Note**: For detailed information about nullable types, see [`nullable.md`](nullable.md). This section only covers basic information. - -Any primitive type can be made nullable by appending `?` (e.g., `Int?`, `String?`). Nullable types are passed by reference and can hold either a value or `null`. - -**Important**: You cannot directly call methods on nullable types using `.` - you must use the safe call operator `?.`. - -```ovum -val nullableString: String? = "Hello" -// val length: Int = nullableString.Length() // ERROR: Cannot call method directly on nullable -val safeLength: Int = nullableString?.Length() ?: 0 // Correct: Use safe call -``` - -## Array Types - -Ovum provides specialized array classes for different data types. Arrays are reference types and support indexing, iteration, and length operations. All array types implement `IStringConvertible`, `IComparable`, and `IHashable`. - -### Primitive Arrays - -* `IntArray` - Array of 64-bit signed integers -* `FloatArray` - Array of 64-bit floating-point numbers -* `BoolArray` - Array of Boolean values -* `CharArray` - Array of characters -* `ByteArray` - Array of 8-bit unsigned integers -* `PointerArray` - Array of raw memory addresses (unsafe) - -### Object Arrays - -* `ObjectArray` - Array of any object type (implements `Object`) -* `StringArray` - Convenience array of `String` objects (used for `Main` function) - -## File Type - -`File` is a reference type for file operations. Files are nullable by default (`File?`) since file operations can fail. The `File` type implements `IStringConvertible`, `IComparable`, and `IHashable`. - -### File Methods - -* `ReadAllBytes(): ByteArray?` - Reads all bytes from the file, returns `null` on error -* `ReadAllText(): String?` - Reads all text from the file as UTF-8, returns `null` on error -* `WriteAllBytes(data: ByteArray): Bool` - Writes all bytes to the file, returns `false` on error -* `WriteAllText(text: String): Bool` - Writes all text to the file as UTF-8, returns `false` on error -* `AppendText(text: String): Bool` - Appends text to the file, returns `false` on error -* `Close(): Void` - Closes the file handle -* `IsOpen(): Bool` - Returns `true` if the file is currently open -* `GetSize(): Int?` - Returns file size in bytes, or `null` if error -* `ToString(): String` - Returns file path (implements `IStringConvertible`) -* `IsLess(other: Object): Bool` - Compares file paths lexicographically (implements `IComparable`) -* `GetHash(): Int` - Returns hash of file path (implements `IHashable`) - -### File Usage - -```ovum -// File operations -val file: File? = sys::OpenFile("data.txt", sys::FileMode::Read) -if (file != null) { - val content: String? = file.ReadAllText() - if (content != null) { - sys::Print("File content: " + content) - } - file.Close() -} - -// Writing to file -val outputFile: File? = sys::OpenFile("output.txt", sys::FileMode::Write) -if (outputFile != null) { - val success: Bool = outputFile.WriteAllText("Hello, World!") - if (success) { - sys::Print("File written successfully") - } - outputFile.Close() -} - -// File comparison -val file1: File? = sys::OpenFile("a.txt", sys::FileMode::Read) -val file2: File? = sys::OpenFile("b.txt", sys::FileMode::Read) -if (file1 != null && file2 != null) { - val isLess: Bool = file1.IsLess(file2) // Compares file paths -} -``` - -### Array Methods - -All array types support the following methods: - -* `Length(): Int` - Returns the number of elements in the array -* `[index]: ElementType` - Indexing operator for element access -* `[index] = value` - Assignment operator for mutable arrays -* `ToString(): String` - String representation of the array (implements `IStringConvertible`) -* `IsLess(other: Object): Bool` - Lexicographic comparison of array elements (implements `IComparable`) -* `GetHash(): Int` - Hash code based on array contents (implements `IHashable`) - -### Array Usage - -```ovum -// Creating and using arrays -val numbers: IntArray = IntArray(3) -numbers[0] = 10 -numbers[1] = 20 -numbers[2] = 30 - -val count: Int = numbers.Length() // Returns 3 - -// Iteration -for (num in numbers) { - sys::Print(num.ToString()) -} - -// Array comparison -val arr1: IntArray = IntArray(2) -arr1[0] = 1 -arr1[1] = 2 - -val arr2: IntArray = IntArray(2) -arr2[0] = 1 -arr2[1] = 3 - -val isLess: Bool = arr1.IsLess(arr2) // true (lexicographic comparison) - -// Array hashing -val hash: Int = numbers.GetHash() - -// String array (used in Main) -fun Main(args: StringArray): Int { - for (arg in args) { - sys::Print("Argument: " + arg) - } - return 0 -} -``` - -## Built-in Interfaces - -All types in Ovum implicitly implement certain standard interfaces that provide common functionality. - -### Object (Root Interface) - -The implicit root interface for all types. Provides: -* `destructor(): Void` - Virtual destructor called by GC during finalization - -### IStringConvertible - -Provides string conversion capability: -* `ToString(): String` - Converts the object to its string representation - -All built-in types implement this interface: -```ovum -val num: Int = 42 -val str: String = num.ToString() // "42" - -val flag: Bool = true -val flagStr: String = flag.ToString() // "true" -``` - -### IComparable - -Provides ordering capability for sorting and comparison: -* `IsLess(other: Object): Bool` - Returns true if this object is less than the other - -Required for user-defined types used as parameters to pure functions (ensures stable ordering). - -```ovum -val a: Int = 5 -val b: Int = 10 -val isLess: Bool = a.IsLess(b) // true -``` - -### IHashable - -Provides hashing capability for use in hash tables and caching: -* `GetHash(): Int` - Returns a hash code for the object - -```ovum -val text: String = "Hello" -val hash: Int = text.GetHash() -``` - -## Type Hierarchy - -``` -Object (implicit root) -├── IStringConvertible -├── IComparable -└── IHashable - -Built-in Types: -├── String (implements all interfaces) -├── File (implements all interfaces) -├── IntArray, FloatArray, etc. (implements all interfaces) -├── Int, Float, Bool, Char, Byte (implements all interfaces) -└── Int?, String?, File?, etc. (nullable versions, implements all interfaces) -``` diff --git a/docs/reference/code_examples.md b/docs/reference/code_examples.md deleted file mode 100644 index 2400276..0000000 --- a/docs/reference/code_examples.md +++ /dev/null @@ -1,338 +0,0 @@ -# Code Examples - -Here are some code examples to help you get started with Ovum. - -## 1) Entry point (`StringArray`) - -```ovum -// .ovum file -fun Main(args: StringArray): Int { - val count: Int = args.Length() // Built-in returns Int - sys::Print("Args count: " + count.ToString()) - return 0 -} -``` - -## 2) Variables, Nulls, Elvis, Safe Calls - -```ovum -fun DemoNulls(): Void { - val a: Int? = null - val b: Int? = 5 - - val aVal: int = a ?: 0 - val bVal: int = b ?: 0 - val sum: int = aVal + bVal - sys::Print("Sum = " + Int(sum).ToString()) - - val name: String? = null - val length: int = (name?.Length() ?: 0) as int // Built-in returns Int - sys::Print("Name length = " + Int(length).ToString()) -} -``` - -## 3) Interfaces, Classes, Fields, Overrides - -```ovum -interface IGreeter { - fun Greet(name: String): String // public + virtual by default -} - -class FriendlyGreeter implements IGreeter { - private val Prefix: String = "Hello" - public var Suffix: String = "!" - - public fun FriendlyGreeter(prefix: String, suffix: String): FriendlyGreeter { - this.Prefix = prefix - this.Suffix = suffix - return this - } - - public override fun Greet(name: String): String { - return Prefix + ", " + name + Suffix - } - - // Optional destructor (finalization logic) - public destructor(): Void { - // release non-memory resources if any (files, handles, etc.) - } -} -``` - -## 4) Standard Interfaces (`IStringConvertible`, `IComparable`, `IHashable`) - -```ovum -interface IStringConvertible { fun ToString(): String } -interface IComparable { fun IsLess(other: Object): Bool } -interface IHashable { fun GetHash(): Int } - -class Point implements IStringConvertible, IComparable, IHashable { - public val X: int - public val Y: int - - public fun Point(x: int, y: int): Point { this.X = x; this.Y = y; return this; } - - public override fun ToString(): String { - return "(" + Int(X).ToString() + ", " + Int(Y).ToString() + ")" - } - - public override fun IsLess(other: Object): Bool { - if (!(other is Point)) return false - val p: Point? = other as Point - if (p != null) { - val nonNullP: Point = p ?: Point(0, 0) // Use Elvis operator - if (this.X != nonNullP.X) return this.X < nonNullP.X - return this.Y < nonNullP.Y - } - return false - } - - public override fun GetHash(): Int { - val hash: int = (X * 1315423911) ^ (Y * 2654435761) - return Int(hash) - } -} -``` - -## 5) Pure Functions with Caching - -```ovum -pure fun Fib(n: int): int { - if (n <= 1) return n - val fib1: int = Fib(n - 1) - val fib2: int = Fib(n - 2) - return fib1 + fib2 -} -// For user-defined reference types as parameters, implement IComparable. -``` - -## 6) `is`, `as`, and ByteArray Casts - -```ovum -fun DemoCasts(obj: Object): Void { - if (obj is Point) { - val p: Point? = obj as Point - if (p != null) { - val nonNullP: Point = p ?: Point(0, 0) // Use Elvis operator - sys::Print(nonNullP.ToString()) - } - } - - // bool cast - val b1: Bool = 0 as bool // false - val b2: Bool = 42 as bool // true - val b3: Bool = obj as bool // always true - val b4: Bool = (obj as Point) as bool // true if obj is a Point - - // Unsafe: raw byte views - unsafe { - val bytesConst: ByteArray = (obj as ByteArray) - val bytesMut : ByteArray = (obj as var ByteArray) - } -} -``` - -## 7) Functional Objects (`call`) & Literals - -```ovum -interface CustomFunctional { - call(a: Int?, b: Int?): Int -} - -class DefinedFunctional { - public var Multiplier: Int - - public fun DefinedFunctional(multiplier: Int): DefinedFunctional { - this.Multiplier = multiplier - return this - } - - public call(secondMultiplier: Int): Int = fun(secondMultiplier: Int): Int { - return Multiplier * secondMultiplier - } -} - -val AddNullable: CustomFunctional = pure fun(a: Int?, b: Int?): Int { - return (a ?: 0) + (b ?: 0) -} - -fun Main(args: StringArray): Int { - return AddNullable(2, DefinedFunctional(-1)(2)) -} -``` - -## 8) Control Flow Examples - -```ovum -fun DemoControlFlow(): Void { - var i: int = 0 - - // While loop with break and continue - while (i < 10) { - if (i == 3) { - i = i + 1 - continue // Skip to next iteration - } - if (i == 7) { - break // Exit loop - } - sys::Print("i = " + Int(i).ToString()) - i = i + 1 - } - - // For loop over array - val numbers: IntArray = IntArray(3) - numbers[0] := 10 - numbers[1] := 20 - numbers[2] := 30 - - for (num in numbers) { - sys::Print("Number: " + num.ToString()) - } -} -``` - -## 9) Unsafe Operations - -```ovum -fun DemoUnsafeOperations(): Void { - // Unsafe block for low-level operations - unsafe { - // Global mutable state (unsafe) - static var globalCounter: int = 0 - globalCounter = globalCounter + 1 - - // Pointer operations (unsafe) - val obj: Point = Point(10, 20) - val ptr: pointer = &obj // address-of - val deref: Object = *ptr // dereference to Object, pointer is not typed - - // ByteArray casting (unsafe) - val bytes: ByteArray = (obj as ByteArray) - val mutableBytes: ByteArray = (obj as var ByteArray) - - // Foreign function interface (unsafe) - val input: ByteArray = "Hello".ToUtf8Bytes() - val output: ByteArray = ByteArray(8) - val result: int = sys::Interope("libc.so", "strlen", input, output) - } -} -``` - -## 10) Type Aliases - -```ovum -// Define type aliases for better readability -typealias UserId = Int -typealias UserName = String -typealias UserList = ObjectArray - -class User { - public val Id: UserId - public val Name: UserName - - public fun User(id: UserId, name: UserName): User { - this.Id = id - this.Name = name - return this - } -} - -fun ProcessUsers(users: UserList): Void { - for (i in 0..users.Length()) { - val user: User? = users[i] as User - if (user != null) { - val nonNullUser: User = user ?: User(0, "Unknown") // Use Elvis operator - sys::Print("User " + nonNullUser.Id.ToString() + ": " + nonNullUser.Name) - } - } -} -``` - - -## 11) Memory Management and Destructors - -```ovum -class DatabaseConnection { - private val ConnectionId: int - private val IsConnected: bool - - public fun DatabaseConnection(id: int): DatabaseConnection { - this.ConnectionId = id - this.IsConnected = true - // Establish database connection - return this - } - - public fun Query(sql: String): String { - if (!IsConnected) return "Not connected" - // Execute query - return "Query result" - } - - // Destructor called automatically by GC - public destructor(): Void { - if (IsConnected) { - // Close database connection - sys::Print("Closing connection " + Int(ConnectionId).ToString()) - } - } -} - -fun DemoMemoryManagement(): Void { - val db: DatabaseConnection = DatabaseConnection(1) - val result: String = db.Query("SELECT * FROM users") - sys::Print("Query result: " + result) - - // db will be garbage collected automatically - // destructor will be called by GC -} -``` - -## 12) Complete Program Example - -```ovum -// Complete Ovum program demonstrating key features -interface ICalculator { - fun Calculate(a: Int, b: Int): Int -} - -class Adder implements ICalculator { - public override fun Calculate(a: Int, b: Int): Int { - return a + b - } -} - -class Multiplier implements ICalculator { - public override fun Calculate(a: Int, b: Int): Int { - return a * b - } -} - -pure fun ProcessNumbers(calc: ICalculator, numbers: IntArray): int { - var result: int = 0 - for (num in numbers) { - val calcResult: Int = calc.Calculate(num, 2) - result = result + calcResult - } - return result -} - -fun Main(args: StringArray): int { - val numbers: IntArray = IntArray(3) - numbers[0] := 5 - numbers[1] := 10 - numbers[2] := 15 - - val adder: ICalculator = Adder() - val multiplier: ICalculator = Multiplier() - - val sumResult: int = ProcessNumbers(adder, numbers) - val productResult: int = ProcessNumbers(multiplier, numbers) - - sys::Print("Sum result: " + Int(sumResult).ToString()) - sys::Print("Product result: " + Int(productResult).ToString()) - - return 0 -} -``` \ No newline at end of file diff --git a/docs/reference/control_flow.md b/docs/reference/control_flow.md deleted file mode 100644 index 7037c28..0000000 --- a/docs/reference/control_flow.md +++ /dev/null @@ -1,60 +0,0 @@ -# Control Flow - -Ovum supports standard control flow constructs following structured programming principles: - -## Conditional Execution - -**If/Else**: Conditional execution with syntax `if (condition) { ... } else { ... }`. The condition must be a Boolean expression (`Bool`). Braces are required for blocks, but for single statements the braces can be omitted (though using braces is encouraged for clarity). - -```ovum -if (x > 0) { - sys::Print("Positive") -} else if (x < 0) { - sys::Print("Negative") -} else { - sys::Print("Zero") -} -``` - -## Loops - -**While Loop**: `while (condition) { ... }` repeats the body while the condition is true. - -```ovum -var i: Int = 0 -while (i < 10) { - sys::Print(i.ToString()) - i = i + 1 -} -``` - -**For Loop**: `for (item in collection) { ... }` iterates over elements of a collection (arrays, etc.). - -```ovum -for (item in items) { - sys::Print(item.ToString()) -} -``` - -## Flow Control - -**Return**: `return expression;` exits the current function with the given value (or `return;` with no value to exit a void function). In pure functions, a return simply provides the result; in impure, it may terminate early as usual. - -**Break/Continue**: `break` exits a loop immediately, `continue` skips to the next iteration of the loop. - -```ovum -var i: Int = 0 -while (i < 10) { - if (i == 5) { - break // Exit loop - } - if (i == 3) { - i = i + 1 - continue // Skip to next iteration - } - sys::Print(i.ToString()) - i = i + 1 -} -``` - -All control flow follows structured programming principles (no `goto`). diff --git a/docs/reference/design.md b/docs/reference/design.md deleted file mode 100644 index 461ce30..0000000 --- a/docs/reference/design.md +++ /dev/null @@ -1,38 +0,0 @@ -# Overview - -**Ovum** is a new general-purpose programming language with a design emphasis on safety, purity, and clarity. It is a strongly **statically typed**, **single-threaded** language with Kotlin-like syntax and a focus on safety, clarity, and performance. - -## Design Philosophy - -Ovum's core design principles center around: - -* **Memory Safety**: Automatic memory management through garbage collection eliminates whole classes of bugs like dangling pointers, memory leaks, and buffer overruns. -* **Immutability by Default**: Variables, object fields, and function parameters are constant by default, reducing unintended side effects and making code easier to reason about. -* **Pure Functions**: Functions with no side effects whose results can be cached for performance optimization through memoization. -* **Interface-Based Polymorphism**: No class inheritance; polymorphism achieved through interface implementation and composition, avoiding complex inheritance hierarchies. -* **Explicit Unsafe Operations**: Low-level or potentially unsafe operations are isolated within explicit `unsafe { ... }` blocks. -* **Less is More**: The language is designed to be simple and easy to learn, with a focus on clarity and readability. The less ways there are to do the same thing, the better. - -## Key Design Points - -* **Strong static typing** with **immutability by default** (`var` required for mutation). -* **Nullable types** and Kotlin-style null-handling: `Type?`, safe calls `?.`, Elvis `?:`. -* **Pure functions** (no side effects, VM-level result caching). -* **Classes & interfaces** - - * **No class inheritance**; classes only **implement interfaces**. - * **Root `Object`** is implicit for all classes and interfaces (no need to write `: Object`). It declares only a **virtual destructor**. - * Interfaces are named with **leading `I`** (C# style): e.g., `IGreeter`, `IComparable`. - * Interface methods are **public** and **virtual** by default. - * Class methods implementing interface members must be marked `override`. - * **Access modifiers are mandatory** for all fields and methods in classes (`public`/`private`). - * **Fields use `val` (immutable) or `var` (mutable)**. -* **Namespaces** with `::` resolution (e.g., `sys::Print`). -* **Functional objects** (`call` member) for functional programming. -* **Type aliases** (`typealias` keyword) for better readability. -* **Built-in operators**; **no user-defined operators**. -* **Preprocessor**: `#import`, `#define`, `#ifdef`, `#ifndef`, `#else`, `#undef`. -* **Managed runtime**: VM with **JIT** and **GC**; **no manual memory management**. -* **Single-threaded runtime**: no concurrency primitives. -* **Passing semantics**: all user-defined and non-primitive types (including `String` and all arrays) are **passed by reference** (const by default). -* **File extension**: `.ovum`. diff --git a/docs/reference/expressions_and_operators.md b/docs/reference/expressions_and_operators.md deleted file mode 100644 index e56a42f..0000000 --- a/docs/reference/expressions_and_operators.md +++ /dev/null @@ -1,54 +0,0 @@ -# Expressions and Operators - -Expressions in Ovum include literal values, variable references, function calls, method calls, field accesses, and combinations of these with operators. Operator syntax and precedence are designed to be familiar to C/Java/Kotlin developers. - -## Arithmetic Operators - -* `+` (addition) - operates on numeric types and may be overloaded internally for string concatenation -* `-` (subtraction) - operates on numeric types -* `*` (multiplication) - operates on numeric types -* `/` (division) - operates on numeric types -* `%` (modulo) - operates on numeric types - -## Comparison Operators - -* `==` (equality) - most types can be compared for equality -* `!=` (inequality) - opposite of equality -* `<`, `<=`, `>`, `>=` (ordering) - only valid on types that have a defined ordering (numeric types or classes implementing `IComparable`) - -## Logical Operators - -* `&&` (logical AND) - short-circuit evaluation -* `||` (logical OR) - short-circuit evaluation -* `!` (negation) - unary operator -* `xor` (exclusive OR) - infix operator on `bool` - -## Assignment Operators - -* `=` (reference assignment) - assigns a reference to a mutable variable or field. The left-hand side must be a mutable variable or field. -* `:=` (copy assignment) - performs deep copy for reference types. Creates a new object with the same content as the source. - -## Member Access - -* `object.field` - access a field of an object -* `object.method()` - call a method on an object -* `object?.field` - safe field access (returns null if object is null) -* `object?.method()` - safe method call (returns null if object is null) - -## Type Operations - -* `expr as Type` - explicit cast (downcast yields nullable type) -* `expr is Type` - type test (returns `bool`) - -## Null Handling - -* `expr?.member` - safe call (calls only if expr is not null) -* `expr ?: default` - Elvis operator (returns expr if not null, otherwise default) - -## Namespace Resolution - -* `Namespace::Name` - refers to a definition from a specific namespace (e.g., `sys::Print`) - -## No User-Defined Operators - -Programmers cannot create new operator symbols or overload the existing ones for user-defined types. The set of operators and their meanings are fixed by the language. This keeps the language syntax clear and consistent and avoids operator overloading misuse. diff --git a/docs/reference/lexical_structure.md b/docs/reference/lexical_structure.md deleted file mode 100644 index c207aee..0000000 --- a/docs/reference/lexical_structure.md +++ /dev/null @@ -1,151 +0,0 @@ -# Lexical Structure - -Ovum's source code uses a lexical syntax familiar to C-style and Kotlin-style languages: - -## Identifiers - -Names for variables, functions, classes, etc., consist of letters, digits, and underscores, and must not begin with a digit. For example: `myVar`, `compute_sum`, `GraphNode`. Identifiers are case-sensitive. - -**Naming Convention**: Classes, functions, methods use **PascalCase** (e.g., `Main`, `ToString`, `IsLess`). Keywords/modifiers remain lowercase (`class`, `interface`, `var`, `override`, `pure`, `unsafe`, etc.). - -## Keywords - -Ovum reserves certain words like `fun`, `class`, `interface`, `var`, `override`, `pure`, `if`, `else`, `for`, `while`, `return`, `unsafe`, `val`, `static`, `public`, `private`, `implements`, `as`, `is`, `null`, `true`, `false`, `typealias`, `destructor`, `call`, etc. These cannot be used as identifiers. - -## Literals - -* **Numeric literals**: integers (e.g., `42`, `-17`) and floating-point numbers (e.g., `3.14`, `-2.5`) -* **Boolean literals**: `true`, `false` -* **Character literals**: single characters in single quotes (e.g., `'A'`, `'\n'`, `'\t'`) -* **String literals**: text in double quotes (e.g., `"hello"`, `"world"`) with escape sequences like `"\n"` for newline, `"\t"` for tab, `"\\"` for backslash, `"\""` for quote - -## Operators and Punctuation - -* **Arithmetic**: `+`, `-`, `*`, `/`, `%` -* **Comparison**: `==`, `!=`, `<`, `<=`, `>`, `>=` -* **Boolean logic**: `&&` (logical AND), `||` (logical OR), `!` (negation), `xor` (exclusive OR) -* **Assignment**: `=` (reference assignment), `:=` (copy assignment) -* **Null handling**: `?.` (safe call), `?:` (Elvis) -* **Type operations**: `as` (cast), `is` (type test) -* **Punctuation**: `,` (comma), `;` (semicolon), `:` (colon), `()` (parentheses), `{}` (braces), `[]` (brackets) -* **Namespace resolution**: `::` - -## Comments - -* **Line comments**: start with `//` and continue to the end of the line -* **Block comments**: start with `/*` and end with `*/`, can span multiple lines. Nested comments are not allowed - -## Whitespace - -Spaces, tabs, and newlines are generally ignored outside of separating tokens. Indentation is not significant (Ovum is not whitespace-sensitive except that newlines can terminate statements if no semicolon is present). - -## Formal Grammar (EBNF) - -> Core EBNF; whitespace/comments omitted. Operator precedence in §7. - -```ebnf -Program ::= { Import | Conditional | GlobalDef } ; - -Import ::= "#import" StringLiteral ; -Define ::= "#define" Identifier [ NumberLiteral ] ; -Undef ::= "#undef" Identifier ; -Conditional ::= "#ifdef" Identifier { GlobalDef | Import | Conditional } - [ "#else" { GlobalDef | Import | Conditional } ] "#endif" - | "#ifndef" Identifier { GlobalDef | Import | Conditional } - [ "#else" { GlobalDef | Import | Conditional } ] "#endif" ; - -GlobalDef ::= FunctionDecl | ClassDecl | InterfaceDecl | GlobalVarDecl | TypeAliasDecl ; - -FunctionDecl ::= [ "pure" ] "fun" Identifier "(" [ ParamList ] ")" [ ":" Type ] Block ; -ParamList ::= Parameter { "," Parameter } ; -Parameter ::= [ "var" ] Identifier ":" Type ; - -ClassDecl ::= "class" Identifier [ "implements" TypeList ] ClassBody ; -TypeList ::= Type { "," Type } ; -ClassBody ::= "{" { ClassMember } "}" ; -ClassMember ::= FieldDecl | StaticFieldDecl | MethodDecl | DestructorDecl | CallDecl ; - -FieldDecl ::= ( "private" | "public" ) ( "val" | "var" ) Identifier ":" Type [ "=" Expression ] ";" ; -StaticFieldDecl ::= "static" ( "private" | "public" ) ( "val" | "var" ) Identifier ":" Type [ "=" Expression ] ";" ; - -MethodDecl ::= ( "private" | "public" ) [ "override" ] [ "pure" ] - "fun" Identifier "(" [ ParamList ] ")" [ ":" Type ] ( Block | ";" ) ; - -CallDecl ::= ( "private" | "public" ) "call" "(" [ ParamList ] ")" [ ":" Type ] ( Block | ";" ) ; - -DestructorDecl ::= ( "private" | "public" ) "destructor" "(" ")" ":" "Void" Block ; - -InterfaceDecl ::= "interface" Identifier InterfaceBody ; // implicitly extends Object -InterfaceBody ::= "{" { InterfaceMember } "}" ; -InterfaceMember ::= InterfaceMethod | InterfaceCall ; -InterfaceMethod ::= "fun" Identifier "(" [ ParamList ] ")" [ ":" Type ] ";" ; // public & virtual -InterfaceCall ::= "call" "(" [ ParamList ] ")" [ ":" Type ] ";" ; // public & virtual - -GlobalVarDecl ::= [ "var" ] Identifier ":" Type "=" Expression ";" ; - -TypeAliasDecl ::= "typealias" Identifier "=" Type ";" ; - -Type ::= NullableType | NonNullType ; -NullableType ::= NonNullType "?" ; -NonNullType ::= FundamentalType - | PrimitiveRefType - | "String" - | "IntArray" | "FloatArray" | "BoolArray" | "CharArray" | "ByteArray" | "PointerArray" - | "ObjectArray" - | "StringArray" - | Identifier ; // class/interface names (non-primitive) - -FundamentalType ::= "int" | "float" | "bool" | "char" | "byte" | "pointer" ; -PrimitiveRefType ::= "Int" | "Float" | "Bool" | "Char" | "Byte" | "Pointer" ; - -Block ::= "{" { Statement } "}" ; -Statement ::= VarDeclStmt | ExprStmt | ReturnStmt | IfStmt | WhileStmt | ForStmt | UnsafeStmt | Block ; - -VarDeclStmt ::= [ "var" ] Identifier ":" Type "=" Expression ";" ; -ExprStmt ::= Expression ";" ; -ReturnStmt ::= "return" [ Expression ] ";" ; -IfStmt ::= "if" "(" Expression ")" Statement [ "else" Statement ] ; -WhileStmt ::= "while" "(" Expression ")" Statement ; -ForStmt ::= "for" "(" Identifier "in" Expression ")" Statement ; -UnsafeStmt ::= "unsafe" Block ; - -Expression ::= Assignment ; -Assignment ::= ElvisExpr [ ("=" | ":=") Assignment ] ; - -ElvisExpr ::= OrExpr [ "?:" ElvisExpr ] ; // right-assoc - -OrExpr ::= AndExpr { "||" AndExpr } ; -AndExpr ::= XorExpr { "&&" XorExpr } ; -XorExpr ::= EqualityExpr { "xor" EqualityExpr } ; - -EqualityExpr ::= RelExpr { ("==" | "!=") RelExpr } ; -RelExpr ::= AddExpr { ("<" | "<=" | ">" | ">=") AddExpr } ; -AddExpr ::= MulExpr { ("+" | "-") MulExpr } ; -MulExpr ::= UnaryExpr { ("*" | "/" | "%") UnaryExpr } ; - -UnaryExpr ::= ("!" | "-" | "&" | "*") UnaryExpr - | Postfix ; - -Postfix ::= Primary { PostfixOp } ; -PostfixOp ::= "." Identifier - | "." Identifier "(" [ ArgList ] ")" - | "(" [ ArgList ] ")" // function call or callable object call - | "as" Type // explicit cast; downcast yields nullable type - | "is" Type // type test → bool - | "?." Identifier [ "(" [ ArgList ] ")" ] // safe call chain - | "?." "(" [ ArgList ] ")" // safe callable object call - ; - -Primary ::= Identifier - | Literal - | "(" Expression ")" - | NamespaceRef - | FunctionLiteral ; - -FunctionLiteral ::= "fun" "(" [ ParamList ] ")" [ ":" Type ] Block ; - -NamespaceRef ::= Identifier "::" Identifier ; -ArgList ::= Expression { "," Expression } ; - -Literal ::= NumberLiteral | StringLiteral | CharLiteral | "true" | "false" ; -``` diff --git a/docs/reference/nullable.md b/docs/reference/nullable.md deleted file mode 100644 index 248ea24..0000000 --- a/docs/reference/nullable.md +++ /dev/null @@ -1,111 +0,0 @@ -# Nullability (Kotlin-style) - -This document describes how nullable types work in Ovum, including their restrictions and available operations. - -## Creating Nullable Types - -Append `?` to make a **reference type** nullable: `Int?`, `String?`, `Point?`. **Fundamental types** (`int`, `float`, `bool`, `char`, `byte`, `pointer`) cannot be made nullable. - -```ovum -val nullableInt: Int? = null -val nullableString: String? = "Hello" -val nullablePoint: Point? = Point(10, 20) - -// val invalidNullable: int? = null // ERROR: Fundamental types cannot be nullable -``` - -## Method Call Restrictions - -**Important**: You cannot directly call methods on nullable types using `.` - you must use the safe call operator `?.`. - -```ovum -val nullableString: String? = "Hello" -// val length: Int = nullableString.Length() // ERROR: Cannot call method directly on nullable -val safeLength: Int = nullableString?.Length() ?: 0 // Correct: Use safe call -``` - -## Null Handling Operators - -### Safe Call (`?.`) - -`expr?.Method()` calls only if `expr != null`; otherwise yields `null` (if the method returns a reference type) or a sensible default for chaining to Elvis. - -```ovum -val name: String? = null -val length: Int = name?.Length() ?: 0 // Returns 0 if name is null -val upper: String? = name?.ToUpper() // Returns null if name is null -``` - -### Elvis Operator (`?:`) - -`a ?: b` evaluates to `a` if non-null, else `b`. - -```ovum -val nullableInt: Int? = null -val defaultValue: Int = nullableInt ?: 42 // Uses 42 if nullableInt is null - -val nullableString: String? = null -val result: String = nullableString ?: "default" // Uses "default" if nullableString is null -``` - - -## Type Casting - -### Cast to Bool - -Any value can be explicitly cast to `bool`: - -* **Fundamentals, primitive reference types**: zero → `false`, non-zero → `true` -* **Non-primitive reference types and nullable primitives**: `true` iff the reference is a valid (non-null, live) object - -```ovum -val nullableInt: Int? = null -val isNull: bool = (nullableInt as bool) // false (null is falsy) - -val someInt: Int? = 42 // Implicit conversion from literal -val isNotNull: bool = (someInt as bool) // true (non-null is truthy) - -// Converting nullable primitives to fundamentals -val nullablePrimitive: Int? = 42 // Implicit conversion from literal -val fundamentalValue: int = (nullablePrimitive as Int) as int // Two-step conversion -``` - -## Chaining Operations - -You can chain safe calls and Elvis operators for complex null handling: - -```ovum -val person: Person? = getPerson() -val nameLength: Int = person?.Name?.Length() ?: 0 - -// Equivalent to: -val nameLength: Int = if (person != null && person.Name != null) { - val nonNullPerson: Person = person ?: Person("Unknown") // Use Elvis operator - val nonNullName: String = nonNullPerson.Name ?: "Unknown" // Use Elvis operator - nonNullName.Length() -} else { - 0 -} -``` - -## Nullable Type Methods - -All nullable types support the same operators but cannot directly call methods: - -```ovum -val nullableString: String? = "Hello" -val nullableInt: Int? = 42 // Implicit conversion from literal - -// Safe operations -val safeLength: int = (nullableString?.Length() ?: 0) as int // Built-in returns Int -val safeToString: String = nullableInt?.ToString() ?: "null" -``` - -## Best Practices - -1. **Always use safe calls** (`?.`) for nullable types -2. **Use Elvis operator** (`?:`) to provide sensible defaults -3. **Chain operations** for cleaner null handling code -4. **Consider using `if` statements** for complex null checks instead of deeply nested safe calls -5. **Use copy assignment** (`:=`) when you need independent copies of nullable objects -6. **Convert to fundamentals** when you need value semantics: `(nullablePrimitive as PrimitiveType) as fundamentalType` diff --git a/docs/reference/object_model.md b/docs/reference/object_model.md deleted file mode 100644 index 19a175b..0000000 --- a/docs/reference/object_model.md +++ /dev/null @@ -1,404 +0,0 @@ -# Object Model - -Ovum uses an interface-based object model with no class inheritance. All types derive from `Object`, and polymorphism is achieved through interface implementation. - -## Object Hierarchy - -### Root Type: `Object` - -* **`Object`** - implicit root of all reference types - * Contains only a virtual destructor - * Enables safe, uniform storage (e.g., in `ObjectArray`) - * All user-defined classes implicitly extend `Object` - * Cannot be instantiated directly - -```ovum -// Object is the root of all reference types -val obj: Object = Point(10, 20) // Upcast to Object -val point: Point? = (obj as Point) // Downcast to Point (nullable) -``` - -## Standard Interfaces - -All standard interfaces implicitly extend `Object` and provide common functionality: - -### `IStringConvertible` - -Provides string representation capability: - -```ovum -interface IStringConvertible { - fun ToString(): String -} - -class Person implements IStringConvertible { - public val Name: String - public val Age: Int - - public fun Person(name: String, age: Int): Person { - this.Name = name - this.Age = age - return this - } - - public override fun ToString(): String { - return Name + " (" + Age.ToString() + ")" - } -} -``` - -### `IComparable` - -Provides ordering capability for sorting and comparison: - -```ovum -interface IComparable { - fun IsLess(other: Object): Bool -} - -class Point implements IComparable { - public val X: Int - public val Y: Int - - public fun Point(x: Int, y: Int): Point { - this.X = x - this.Y = y - return this - } - - public override fun IsLess(other: Object): Bool { - if (!(other is Point)) return false - val p: Point = (other as Point) ?: Point(0, 0) - if (this.X != p.X) return this.X < p.X - return this.Y < p.Y - } -} -``` - -**Required for pure function parameters** (provides stable ordering/keys). - -### `IHashable` - -Provides hash code generation for use in hash tables: - -```ovum -interface IHashable { - fun GetHash(): Int -} - -class Point implements IHashable { - public val X: Int - public val Y: Int - - public override fun GetHash(): Int { - return (X * 1315423911) ^ (Y * 2654435761) - } -} -``` - -## Class Definitions - -### Basic Class Syntax - -```ovum -class ClassName implements Interface1, Interface2 { - // Fields - // Constructor - // Methods - // Destructor (optional) -} -``` - -### Fields - -Fields can be immutable (`val`) or mutable (`var`): - -```ovum -class BankAccount { - public val AccountNumber: String // Immutable field - public var Balance: Float // Mutable field - private val CreatedDate: Int // Private field -} -``` - -### Access Modifiers - -* **`public`** - accessible from anywhere -* **`private`** - accessible only within the same class - -```ovum -class DataContainer { - public val PublicData: String = "Public" - private val PrivateData: String = "Private" - - public fun GetPrivateData(): String { - return PrivateData // OK: accessing private member from within class - } -} -``` - -### Constructors - -Constructors initialize new instances: - -```ovum -class Rectangle { - public val Width: Float - public val Height: Float - - public fun Rectangle(width: Float, height: Float): Rectangle { - this.Width = width - this.Height = height - return this - } - - // Multiple constructors (overloading) - public fun Rectangle(size: Float): Rectangle { - this.Width = size - this.Height = size - return this - } -} -``` - -### Methods - -Methods can be regular, pure, or override: - -```ovum -class Calculator implements IStringConvertible { - public fun Add(a: Int, b: Int): Int { - return a + b - } - - public pure fun Multiply(a: Int, b: Int): Int { - return a * b - } - - public override fun ToString(): String { - return "Calculator" - } -} -``` - -### Destructors - -Optional destructors are called by the garbage collector: - -```ovum -class FileHandler { - private val FilePath: String - - public destructor(): Void { - // Release file handles, network connections, etc. - // Manual calls are unsafe - } -} -``` - -## Interface Definitions - -### Basic Interface Syntax - -```ovum -interface InterfaceName extends BaseInterface { - // Method declarations - // Property declarations -} -``` - -### Method Declarations - -```ovum -interface IShape { - fun GetArea(): Float - fun GetPerimeter(): Float - fun Draw(): Void -} - -interface IColorable { - fun SetColor(color: String): Void - fun GetColor(): String -} -``` - -### Property Declarations - -Interfaces can declare properties that implementing classes must provide: - -```ovum -interface IReadable { - val IsReadable: Bool - val Content: String -} - -class Document implements IReadable { - public val IsReadable: Bool = true - public val Content: String -} -``` - -### Multiple Interface Implementation - -Classes can implement multiple interfaces: - -```ovum -class ColoredRectangle implements IShape, IColorable { - public val Width: Float - public val Height: Float - public var Color: String - - public fun ColoredRectangle(width: Float, height: Float, color: String): ColoredRectangle { - this.Width = width - this.Height = height - this.Color = color - return this - } - - public override fun GetArea(): Float { - return Width * Height - } - - public override fun GetPerimeter(): Float { - return 2 * (Width + Height) - } - - public override fun Draw(): Void { - sys::Print("Drawing " + Color + " rectangle") - } - - public override fun SetColor(color: String): Void { - this.Color = color - } - - public override fun GetColor(): String { - return Color - } -} -``` - -## Type Casting and Tests - -**Upcasting** (to `Object` or interfaces): safe, non-nullable -**Downcasting** (to concrete classes): nullable result - -```ovum -val point: Point = Point(10, 20) -val obj: Object = point // Upcast to Object -val comparable: IComparable = point // Upcast to interface - -// Downcasting with type test -if (obj is Point) { - val p: Point = (obj as Point) ?: Point(0, 0) - sys::Print("Point: " + p.ToString()) -} - -// Type test operator -if (shape is ColoredRectangle) { - val rect: ColoredRectangle = (shape as ColoredRectangle) ?: ColoredRectangle(0, 0, "red") - sys::Print("Rectangle color: " + rect.GetColor()) -} -``` - -**Unsafe casting** requires `unsafe` blocks: -```ovum -unsafe { - val obj: Object = Point(10, 20) - val bytes: ByteArray = (obj as ByteArray) // Raw byte view - val mutableBytes: ByteArray = (obj as var ByteArray) // Mutable byte view -} -``` - -## Functional Objects - -Classes and interfaces can define a special `call` member to make them callable: - -```ovum -interface IAdder { - call(a: Int, b: Int): Int -} - -class Calculator implements IAdder { - public var Multiplier: Int - - public call(a: Int, b: Int): Int { - return (a + b) * Multiplier - } -} - -val calc: IAdder = Calculator(2) -val result: Int = calc(5, 3) // Calls the call method: (5 + 3) * 2 = 16 -``` - -**Function literals** can be assigned to interfaces with compatible `call` signatures: - -```ovum -interface IBinaryOperation { - call(a: Int, b: Int): Int -} - -val add: IBinaryOperation = pure fun(a: Int, b: Int): Int { - return a + b -} - -val sum: Int = add(5, 3) // 8 -``` - -## Memory Management - -Ovum uses garbage collection for automatic memory management: - -```ovum -fun CreateObjects(): Void { - val point1: Point = Point(10, 20) // Allocated on heap - val point2: Point = Point(30, 40) // Allocated on heap - - // Objects are automatically collected when no longer referenced -} -``` - -**Destructors** are called by the garbage collector, not manually: - -```ovum -class ResourceManager { - public destructor(): Void { - // Release resource - called automatically by GC - } -} - -// Manual destructor calls are unsafe and not recommended -``` - -## Best Practices - -**Interface Design:** -- Keep interfaces focused on single concepts -- Use descriptive names -- Prefer many small interfaces over few large ones - -**Class Design:** -- Implement standard interfaces (`ToString()`, `IsLess()`, `GetHash()`) -- Use appropriate access modifiers (private fields when possible) -- Prefer immutability (`val` over `var`) - -**Type Safety:** -- Use type tests before casting (`is` before `as`) -- Prefer safe operations -- Handle nullable types properly - -```ovum -// Good: focused interfaces -interface IReadable { fun Read(): String } -interface IWritable { fun Write(content: String): Void } - -// Good: safe type handling -fun SafeProcessObject(obj: Object?): Void { - val result: String = obj?.ToString() ?: "null" - if (obj is Person) { - val person: Person = (obj as Person) ?: Person("Unknown") - sys::Print("Person: " + person.ToString()) - } -} -``` - -> **Naming Conventions**: Classes, functions, methods, and properties use **PascalCase** (e.g., `Main`, `ToString`, `IsLess`). Keywords and modifiers remain lowercase (`class`, `interface`, `var`, `override`, `pure`, `unsafe`, etc.). diff --git a/docs/reference/runtime.md b/docs/reference/runtime.md deleted file mode 100644 index cdaa2e9..0000000 --- a/docs/reference/runtime.md +++ /dev/null @@ -1,55 +0,0 @@ -# Memory Management and Runtime - -One of Ovum's core principles is memory safety. Memory is managed by the runtime's garbage collector (GC), which automatically frees objects that are no longer in use, eliminating whole classes of bugs like dangling pointers, memory leaks, and buffer overruns. - -## Automatic Memory Management - -* **No Manual Memory Management**: There are no language constructs for pointer arithmetic, manual memory allocation (e.g., no `malloc`/`free` or `new`/`delete` outside of what the language runtime provides), nor explicit memory deallocation by the programmer. -* **Garbage Collection**: The runtime includes a garbage collector that runs periodically (or when allocation thresholds are exceeded) to reclaim memory. It finds objects that are no longer reachable from any live variables or object fields and frees them. -* **Modern GC Algorithm**: Ovum's GC is likely a modern algorithm (possibly generational, parallel, or incremental) to minimize pause times, but these are internal implementation details. - -## Just-In-Time Compilation - -* **JIT Compilation**: The VM includes a Just-In-Time compiler (JIT) that can compile frequently executed code paths to native machine code for speed. -* **Hot Path Optimization**: Initially, Ovum bytecode might be interpreted, but as functions or loops become "hot" (executed often), the JIT will optimize them. -* **Hybrid Approach**: This gives the flexibility of an interpreter (fast startup, platform independence of bytecode) with the performance of compiled code in long-running processes. - -## Runtime, VM & Platform Support - -* **Execution**: Source (`.ovum`) → bytecode → **Ovum VM**. -* **JIT**: Hot paths compiled to native for performance. -* **GC**: Automatic memory reclamation; **no manual memory management**. -* **Single-threaded**: Execution model and VM are single-threaded. -* **Architectures**: **amd64** and **arm64** supported. -* **Numeric widths**: `Int` **8 bytes**, `Float` **8 bytes**. - -The Ovum compiler translates Ovum source code into Ovum bytecode or an intermediate representation, which is executed on the Ovum Virtual Machine (OVM). The OVM provides a sandboxed, platform-independent environment for Ovum programs. - -## Development Workflow - -1. **Write Ovum source code** in `.ovum` files -2. **Compile** using the Ovum compiler, which will: - - Parse using the grammar rules - - Type-check (ensure types match and all variables are defined) - - Enforce const/pure rules - - Produce bytecode or an executable -3. **Execute** using the Ovum VM, which will: - - Load the bytecode - - Resolve any imports (linking together modules) - - Start executing (usually beginning with `Main(args: StringArray): Int`) - - Apply JIT optimization to hot code paths - - Manage memory with garbage collection - -## Platform Requirements - -* **Ovum VM**: Required on the target platform (distributed as standalone application or embedded) -* **Architecture Support**: JIT compiler generates code specific to host CPU architecture for performance -* **Portability**: Bytecode is portable across platforms; only the VM's JIT component is platform-specific -* **Dependencies**: Any necessary native libraries if the program uses `sys::Interope` to call external code - -## Execution Characteristics - -* **Single-threaded**: Execution model and VM are single-threaded -* **No Concurrency Primitives**: No built-in threading or concurrency features -* **Structured Programming**: All control flow follows structured programming principles (no `goto`) -* **Entry Point**: Programs start with `Main(args: StringArray): Int` function diff --git a/docs/reference/syntax.md b/docs/reference/syntax.md deleted file mode 100644 index d0a987e..0000000 --- a/docs/reference/syntax.md +++ /dev/null @@ -1,86 +0,0 @@ -# Syntax & Semantics (Description) - -## Functions - -* Declared with `fun`, PascalCase names: `fun Compute(a: Int): Int { ... }` -* **Pure** functions: `pure fun Hash(o: Object): Int { ... }` - * Side-effect free; VM may cache results. - * If parameters include user-defined reference types, those types must implement **`IComparable`**. - -## Classes - -* `class Name implements IFace1, IFace2 { ... }` - - * **No class inheritance**. - * **Access modifiers are mandatory** on fields and methods. - * **Fields** use `val` (immutable) or `var` (mutable): - - * `private val Prefix: String` - * `public var Count: Int` - * **Methods** must declare access and can be `override`/`pure`: - - * `public override fun Run(): Int { ... }` - * **Static** fields supported; **writing `static var` is unsafe**. - * **Destructor**: optional, overrides the implicit virtual destructor from `Object`. - - * Syntax: `public destructor(): Void { ... }` (no parameters, no return). - * Called automatically by GC finalization; **manual calls are unsafe**. - -## Interfaces - -* `interface IGreeter { fun Greet(name: String): String; }` - - * Methods are **public** and **virtual** by default. - * No fields, no bodies. - -## Type Aliases - -* Create type aliases for better readability: `typealias UserId = Int` -* Can be used anywhere a type is expected: `fun ProcessUser(id: UserId): Void` - -## Namespaces & Preprocessor - -* Namespace resolution with `::` (e.g., `sys::Print`). -* Preprocessor: `#import`, `#define`, `#ifdef`, `#ifndef`, `#else`, `#undef`. - -> **Note**: `#define` cannot be used to really define something, it is a way to control what code will be used. - -## Functional Objects (`call`) - -* Classes or interfaces can declare a **special `call`** member that makes instances **callable** like functions. -* Classes **define `call`**, it **may have other members**. -* Interfaces **contain undefined `call` member** (maybe not one, with all interface rules applying). -* A function literal `fun(...) : T { ... }` can be **coerced** to a interface type that exposes a compatible `call(...) : T` (and only this). - -Example: - -```ovum -interface CustomFunctional { - call(a: Int?, b: Int?): Int -} - -class DefinedFunctional { - public var Multiplier: Int - - public fun DefinedFunctional(multiplier: Int): DefinedFunctional { - this.Multiplier = multiplier - return this - } - - // Defines the callable behavior; pure body allowed - public call(secondMultiplier: Int): Int = fun(secondMultiplier: Int): Int { - return Multiplier * secondMultiplier - } -} - -val AddNullable: CustomFunctional = pure fun(a: Int?, b: Int?): Int { - val aVal: int = a ?: 0 // Conversion from Int? to int - val bVal: int = b ?: 0 - return aVal + bVal -} - -fun Main(args: StringArray): Int { - // Constructor call then functional call via `call` - return AddNullable(2, DefinedFunctional(-1)(2)) // Implicit conversion from literals -} -``` diff --git a/docs/reference/system_library.md b/docs/reference/system_library.md deleted file mode 100644 index 9c6ab50..0000000 --- a/docs/reference/system_library.md +++ /dev/null @@ -1,202 +0,0 @@ -# System Library & Interop - -The `sys` namespace provides essential system operations including I/O, time, process control, and foreign function interface capabilities. - -## Basic I/O - -* `sys::Print(msg: String): Void` - Prints a string to standard output -* `sys::PrintLine(msg: String): Void` - Prints a string followed by a newline -* `sys::ReadLine(): String?` - Reads a line from standard input, returns `null` on EOF -* `sys::ReadChar(): Char?` - Reads a single character from standard input, returns `null` on EOF - -## Time and Date Operations - -### Unix Time Functions - -* `sys::UnixTime(): Int` - Returns current Unix timestamp (seconds since epoch) -* `sys::UnixTimeMs(): Int` - Returns current Unix timestamp in milliseconds -* `sys::UnixTimeNs(): Int` - Returns current Unix timestamp in nanoseconds -* `sys::NanoTime(): Int` - Returns high-resolution monotonic time in nanoseconds - -### Date/Time Formatting - -* `sys::FormatDateTime(timestamp: Int, format: String): String?` - Formats Unix timestamp using format string -* `sys::FormatDateTimeMs(timestampMs: Int, format: String): String?` - Formats millisecond timestamp -* `sys::ParseDateTime(dateString: String, format: String): Int?` - Parses date string to Unix timestamp - -### Common Format Specifiers - -* `%Y` - 4-digit year (e.g., 2024) -* `%m` - Month (01-12) -* `%d` - Day of month (01-31) -* `%H` - Hour (00-23) -* `%M` - Minute (00-59) -* `%S` - Second (00-59) -* `%s` - Unix timestamp -* `%f` - Microseconds (000000-999999) -* `%n` - Nanoseconds (000000000-999999999) - -## File Operations - -### File Opening - -* `sys::OpenFile(path: String, mode: FileMode): File?` - Opens a file with specified mode -* `sys::OpenFile(path: String, mode: FileMode, permissions: Int): File?` - Opens file with custom permissions - -### FileMode Enumeration - -* `sys::FileMode::Read` - Open for reading only -* `sys::FileMode::Write` - Open for writing only (truncates existing file) -* `sys::FileMode::Append` - Open for writing, append to end -* `sys::FileMode::ReadWrite` - Open for both reading and writing -* `sys::FileMode::Create` - Create new file, fail if exists -* `sys::FileMode::CreateNew` - Create new file, fail if exists -* `sys::FileMode::Truncate` - Open and truncate to zero length - -### File System Operations - -* `sys::FileExists(path: String): Bool` - Checks if file exists -* `sys::DirectoryExists(path: String): Bool` - Checks if directory exists -* `sys::CreateDirectory(path: String): Bool` - Creates directory, returns `false` on error -* `sys::DeleteFile(path: String): Bool` - Deletes file, returns `false` on error -* `sys::DeleteDirectory(path: String): Bool` - Deletes empty directory, returns `false` on error -* `sys::MoveFile(source: String, destination: String): Bool` - Moves/renames file -* `sys::CopyFile(source: String, destination: String): Bool` - Copies file -* `sys::GetFileSize(path: String): Int?` - Returns file size in bytes, or `null` on error -* `sys::GetFileModifiedTime(path: String): Int?` - Returns file modification time as Unix timestamp - -### Directory Operations - -* `sys::ListDirectory(path: String): StringArray?` - Lists directory contents, returns `null` on error -* `sys::GetCurrentDirectory(): String?` - Returns current working directory -* `sys::ChangeDirectory(path: String): Bool` - Changes current directory, returns `false` on error -* `sys::GetAbsolutePath(path: String): String?` - Returns absolute path, or `null` on error - -## Process Control - -* `sys::Sleep(ms: Int): Void` - Sleeps for specified milliseconds -* `sys::SleepNs(ns: Int): Void` - Sleeps for specified nanoseconds -* `sys::Exit(code: Int): Never` - Terminates the process with exit code -* `sys::GetProcessId(): Int` - Returns current process ID -* `sys::GetEnvironmentVariable(name: String): String?` - Gets environment variable value -* `sys::SetEnvironmentVariable(name: String, value: String): Bool` - Sets environment variable - -## Random Number Generation - -* `sys::Random(): Int` - Returns random 64-bit integer -* `sys::RandomRange(min: Int, max: Int): Int` - Returns random integer in range [min, max) -* `sys::RandomFloat(): Float` - Returns random float in range [0.0, 1.0) -* `sys::RandomFloatRange(min: Float, max: Float): Float` - Returns random float in range [min, max) -* `sys::SeedRandom(seed: Int): Void` - Seeds the random number generator - -## Memory and Performance - -* `sys::GetMemoryUsage(): Int` - Returns current memory usage in bytes -* `sys::GetPeakMemoryUsage(): Int` - Returns peak memory usage in bytes -* `sys::ForceGarbageCollection(): Void` - Forces garbage collection -* `sys::GetProcessorCount(): Int` - Returns number of available CPU cores - -## Network Operations - -* `sys::ResolveHostname(hostname: String): String?` - Resolves hostname to IP address -* `sys::IsPortOpen(host: String, port: Int): Bool` - Checks if TCP port is open -* `sys::GetLocalIpAddress(): String?` - Returns local machine's IP address - -## System Information - -* `sys::GetOsName(): String` - Returns operating system name -* `sys::GetOsVersion(): String` - Returns operating system version -* `sys::GetArchitecture(): String` - Returns CPU architecture (e.g., "x64", "arm64") -* `sys::GetUserName(): String?` - Returns current username -* `sys::GetHomeDirectory(): String?` - Returns user's home directory - -## Error Handling - -* `sys::GetLastError(): String?` - Returns description of last system error -* `sys::ClearError(): Void` - Clears the last error state - -## Foreign Function Interface (FFI) - -* `sys::Interope(dllName: String, functionName: String, input: ByteArray, output: ByteArray): Int` - * **All interop calls are `unsafe`.** - * Returns 0 on success, non-zero error code on failure - * `input` contains parameters to pass to the function - * `output` buffer receives the function's return value - -## Usage Examples - -### Date/Time Operations - -```ovum -// Get current time in different formats -val unixTime: Int = sys::UnixTime() -val unixTimeMs: Int = sys::UnixTimeMs() -val unixTimeNs: Int = sys::UnixTimeNs() - -// Format current time -val formatted: String? = sys::FormatDateTime(unixTime, "%Y-%m-%d %H:%M:%S") -if (formatted != null) { - sys::PrintLine("Current time: " + formatted) -} - -// High-precision timing -val start: Int = sys::NanoTime() -// ... do some work ... -val end: Int = sys::NanoTime() -val duration: Int = end - start -sys::PrintLine("Operation took " + duration.ToString() + " nanoseconds") -``` - -### File Operations - -```ovum -// Read and write files -val file: File? = sys::OpenFile("data.txt", sys::FileMode::Read) -if (file != null) { - val content: String? = file.ReadAllText() - if (content != null) { - sys::PrintLine("File content: " + content) - } - file.Close() -} - -// Write to file -val outputFile: File? = sys::OpenFile("output.txt", sys::FileMode::Write) -if (outputFile != null) { - val success: Bool = outputFile.WriteAllText("Hello, World!") - if (success) { - sys::PrintLine("File written successfully") - } - outputFile.Close() -} - -// Directory operations -if (sys::CreateDirectory("new_folder")) { - sys::PrintLine("Directory created") -} - -val files: StringArray? = sys::ListDirectory(".") -if (files != null) { - for (filename in files) { - sys::PrintLine("File: " + filename) - } -} -``` - -### System Information - -```ovum -// Get system information -sys::PrintLine("OS: " + sys::GetOsName() + " " + sys::GetOsVersion()) -sys::PrintLine("Architecture: " + sys::GetArchitecture()) -sys::PrintLine("CPU cores: " + sys::GetProcessorCount().ToString()) -sys::PrintLine("Memory usage: " + sys::GetMemoryUsage().ToString() + " bytes") - -// Environment variables -val path: String? = sys::GetEnvironmentVariable("PATH") -if (path != null) { - sys::PrintLine("PATH: " + path) -} -``` - -> **Note**: All function names use **PascalCase** (e.g., `Print`, `UnixTime`, `OpenFile`). The namespace remains `sys`. diff --git a/docs/reference/types.md b/docs/reference/types.md deleted file mode 100644 index 12e346c..0000000 --- a/docs/reference/types.md +++ /dev/null @@ -1,284 +0,0 @@ -# Types - -Ovum has a rich type system with primitive types and user-defined types. The type system is static and does not permit implicit type coercions (an `Int` won't automatically become a `Float` without an explicit cast, for example). - -## Fundamental Types - -Fundamental types are passed by value and represent the basic building blocks of the language: - -### Numeric Types - -* **`int`** (8 bytes) - 64-bit signed integer - * Literals: `42`, `-17`, `0x1A` (hex), `0b1010` (binary) - -* **`float`** (8 bytes) - 64-bit floating-point number (IEEE 754 double precision) - * Literals: `3.14`, `2.0e10`, `1.5E-3`, `.5`, `5.` - * Special values: `Infinity`, `-Infinity`, `NaN` - -* **`byte`** (1 byte) - 8-bit unsigned integer - * Literals: `255`, `0x00`, `0b11111111` - -### Character and Boolean Types - -* **`char`** - single Unicode character (UTF-32) - * Literals: `'A'`, `'中'`, `'\n'`, `'\t'`, `'\0'` - -* **`bool`** - Boolean value (`true`, `false`) - * Any value can be explicitly cast to `bool` - -### Low-Level Types - -* **`pointer`** - raw memory address *(only meaningful in `unsafe` code)* - * Used for FFI and low-level memory operations - -> **Fundamental Type Constraints**: Fundamental types cannot be made nullable (`int?` is invalid). They are not `Object` types and cannot be stored in `ObjectArray` or cast to `Object`. To convert nullable primitives to fundamentals, cast to primitive first: `(nullableInt as Int) as int`. - -## Primitive Reference Types - -Primitive reference types are built-in reference wrappers around fundamental types, passed by reference: - -### Numeric Reference Types - -* **`Int`** - reference wrapper for `int` values -* **`Float`** - reference wrapper for `float` values -* **`Byte`** - reference wrapper for `byte` values - -### Character and Boolean Reference Types - -* **`Char`** - reference wrapper for `char` values -* **`Bool`** - reference wrapper for `bool` values - -### Low-Level Reference Types - -* **`Pointer`** - reference wrapper for `pointer` values *(only meaningful in `unsafe` code)* - -> **Nullable Primitives**: Any primitive reference type can be made nullable by appending `?` (e.g., `Int?`, `Float?`, `Bool?`). - -## Reference Types - -### Built-in Reference Types - -* **`String`** - immutable text data (UTF-8 encoded) - * Literals: `"Hello"`, `"Multi-line\nstring"`, `""` (empty string) - * Concatenation: `"Hello" + " " + "World"` - -* **`Object`** - root of all reference types - * Implicit base class for all user-defined types - * Contains only a virtual destructor - -### Array Types - -Ovum provides specialized array classes for different element types (no generics/templates): - -**Primitive Arrays:** -* `IntArray` - array of `Int` reference wrappers -* `FloatArray` - array of `Float` reference wrappers -* `BoolArray` - array of `Bool` reference wrappers -* `CharArray` - array of `Char` reference wrappers -* `ByteArray` - array of `Byte` reference wrappers -* `PointerArray` - array of `Pointer` reference wrappers - -**Object Arrays:** -* `ObjectArray` - array of any `Object`-derived types -* `StringArray` - convenience array of `String` (used for `Main` function arguments) - -**Array Creation:** -```ovum -val numbers: IntArray = IntArray(10) // Create array of Int reference wrappers -val names: StringArray = StringArray(5) // Create string array of size 5 -val objects: ObjectArray = ObjectArray(3) // Create object array of size 3 -``` - -## Type Aliases - -Create type aliases for better code readability: - -```ovum -typealias UserId = Int -typealias UserName = String - -fun ProcessUser(id: UserId, name: UserName): Void { - // Implementation -} -``` - - -## Assignment Operators - -### Reference Assignment (`=`) - -The standard assignment operator assigns references for reference types: - -```ovum -val original: String = "Hello" -val reference: String = original // Both variables point to the same string -``` - -### Copy Assignment (`:=`) - -The copy assignment operator performs deep copy for reference types: - -```ovum -val original: String = "Hello" -val copy: String := original // Creates a new string with the same content -``` - -## Type Casting - -### Explicit Casting - -Use the `as` operator for explicit casting: - -```ovum -val intValue: int = 42 -val floatValue: float = (intValue as float) // int to float - -val floatNum: float = 3.14 -val intNum: int = (floatNum as int) // float to int (truncates) - -// Implicit bidirectional casting between fundamental and primitive reference types -val fundamentalInt: int = 42 -val primitiveInt: Int = fundamentalInt // Implicit: int -> Int -val backToFundamental: int = primitiveInt // Implicit: Int -> int - -// Implicit conversion from literals to primitive types -val count: Int = 0 // Implicit: int literal -> Int -val flag: Bool = true // Implicit: bool literal -> Bool -val pi: Float = 3.14 // Implicit: float literal -> Float - -// Arithmetic works seamlessly -val sum: Int = 10 + 20 // Int + Int = Int (implicit conversion from literals) -val result: int = sum + 5 // Int + int = int (implicit conversion) -``` - -### Boolean Casting - -Any value can be explicitly cast to `bool`: - -```ovum -val intVal: int = 42 -val boolVal: bool = (intVal as bool) // true (non-zero) - -val zeroInt: int = 0 -val falseBool: bool = (zeroInt as bool) // false (zero) - -val nullString: String? = null -val nullBool: bool = (nullString as bool) // false (null) - -// With primitive reference types (implicit conversion) -val primitiveInt: Int = 42 // Implicit conversion from literal -val primitiveBool: bool = primitiveInt // Implicit: Int -> bool -val boolRef: Bool = true // Implicit: bool literal -> Bool -``` - -**Rules:** Fundamentals and primitive reference types: zero → `false`, non-zero → `true`. -References: `null` → `false`, non-null → `true` - -### Unsafe Casting - -Some casts require `unsafe` blocks: - -```ovum -unsafe { - val obj: Object = Point(10, 20) - val bytes: ByteArray = (obj as ByteArray) // Raw byte view - val mutableBytes: ByteArray = (obj as var ByteArray) // Mutable byte view -} -``` - -## Passing Semantics - -**Fundamental types** (`int`, `float`, `byte`, `char`, `bool`, `pointer`) are passed by value (copied): -```ovum -fun ModifyInt(x: int): Void { - x = x + 1 // Only modifies the local copy -} -``` - -**Primitive reference types** (`Int`, `Float`, `Byte`, `Char`, `Bool`, `Pointer`) and **all other reference types** (including `String`, arrays, and user-defined types) are passed by reference: -```ovum -fun ModifyIntRef(var x: Int): Void { - x = x + 1 // Implicit conversion: Int + int -> Int -} - -fun ModifyArray(arr: IntArray): Void { - arr[0] := Int(999) // Use := for deep copy assignment -} -``` - -**Immutability:** References are immutable by default - use `var` for mutable references: -```ovum -fun CannotReassign(str: String): Void { - // str = "New value" // ERROR: Cannot reassign immutable reference -} - -fun CanReassign(var str: String): Void { - str = "New value" // OK: str is mutable -} -``` - -## Type System Characteristics - -**Static typing:** Every variable and expression has a type checked at compile time -**Limited implicit conversions:** The compiler only performs implicit conversions between a primitive reference type and its matching fundamental (for example, `Int` ↔ `int`). Any conversion across different primitive families—such as `Int` to `Float` or `Float` to `int`—must use an explicit cast. -**Type safety:** Prevents many common errors -**Nullable types:** Any reference type (including primitive reference types) can be made nullable by appending `?`. Fundamental types cannot be nullable. - -```ovum -val x: int = 42 -val y: String = "Hello" -// val z: int = x + y // ERROR: Cannot add int and String - -val intVal: int = 42 -val floatVal: float = 3.14 -val result: float = (intVal as float) + floatVal // OK: Explicit conversion - -// Using primitive reference types (implicit conversion between wrappers and fundamentals) -val refInt: Int = 42 // Implicit conversion from literal to Int -val refFloat: Float = 3.14 // Implicit conversion from literal to Float -val sum: Int = refInt + (refFloat as Int) // Requires explicit narrowing -val fundamentalSum: int = sum + 10 // Implicit: Int -> int when assigning to a fundamental - -// Converting nullable primitives to fundamentals -val nullableInt: Int? = 42 // Implicit conversion from literal -val fundamentalFromNullable: int = (nullableInt ?: 0) as int // Two-step conversion -``` - -## Pure Function Constraints - -Types used as parameters in pure functions must implement `IComparable` for stable ordering: - -```ovum -pure fun ProcessData(data: IComparable): Int { - // data must implement IComparable for stable ordering - return data.GetHash() -} -``` - -## Runtime Behavior - -Type information is preserved at runtime for reference types: - -```ovum -fun ProcessObject(obj: Object): Void { - if (obj is String) { - val str: String? = obj as String - if (str != null) { - val nonNullStr: String = str ?: "default" // Use Elvis operator - sys::Print("String length: " + nonNullStr.Length().ToString()) - } - } else if (obj is IntArray) { - val arr: IntArray? = obj as IntArray - if (arr != null) { - val nonNullArr: IntArray = arr ?: IntArray(0) // Use Elvis operator - sys::Print("Array size: " + nonNullArr.Length().ToString()) - } - } else if (obj is Int) { - val intRef: Int? = obj as Int - if (intRef != null) { - val nonNullInt: Int = intRef ?: 0 // Use Elvis operator - sys::Print("Int value: " + nonNullInt.ToString()) // Implicit conversion to string - } - } -} -``` diff --git a/docs/reference/unsafe.md b/docs/reference/unsafe.md deleted file mode 100644 index 50bfa57..0000000 --- a/docs/reference/unsafe.md +++ /dev/null @@ -1,121 +0,0 @@ -# Unsafe Operations - -Unsafe operations bypass Ovum's safety guarantees and are allowed **only** inside `unsafe { ... }` blocks. These operations can lead to undefined behavior, memory corruption, or crashes if used incorrectly. - -## Global and Static Variables - -Global mutable state is unsafe because it can be accessed from anywhere: - -```ovum -unsafe { - global var globalCounter: Int = 0 - globalCounter = globalCounter + 1 - - static var staticValue: String = "initial" - staticValue = "modified" -} -``` - -## Const to Mutable Casting - -Converting immutable references to mutable bypasses immutability guarantees: - -```ovum -unsafe { - val immutable: String = "Hello" - val mutable: var String = (immutable as var String) - // mutable can now be modified, breaking immutability -} -``` - -## Pointer Operations - -Raw memory operations are inherently unsafe: - -```ovum -unsafe { - val obj: Point = Point(10, 20) - val ptr: Pointer = &obj // Address-of operator - val deref: Object = *ptr // Dereference to Object - - // Pointer arithmetic and manipulation - val nextPtr: Pointer = ptr + 8 // Assuming 8-byte alignment -} -``` - -## Manual Destructor Calls - -Destructors should only be called by the garbage collector: - -```ovum -unsafe { - val resource: FileHandler = FileHandler("file.txt") - resource.destructor() // Unsafe: manual destructor call -} -``` - -## Foreign Function Interface - -Calling external native code is unsafe: - -```ovum -unsafe { - val input: ByteArray = "Hello".ToUtf8Bytes() - val output: ByteArray = ByteArray(4) - val result: Int = sys::Interope("libc.so", "strlen", input, output) -} -``` - -## ByteArray Casting - -Raw byte access bypasses type safety: - -```ovum -unsafe { - val point: Point = Point(10, 20) - val bytes: ByteArray = (point as ByteArray) // Const byte view - val mutableBytes: ByteArray = (point as var ByteArray) // Mutable byte view - - // Direct memory manipulation - mutableBytes[0] = 0xFF -} -``` - -## Safety Guidelines - -When using unsafe operations: - -1. **Minimize scope** - Keep unsafe blocks as small as possible -2. **Validate assumptions** - Ensure pointers and casts are valid -3. **Document invariants** - Clearly document what makes the code safe -4. **Test thoroughly** - Unsafe code requires extensive testing -5. **Consider alternatives** - Use safe APIs when possible - -## Common Unsafe Patterns - -**Memory layout inspection:** -```ovum -unsafe { - val obj: MyClass = MyClass() - val bytes: ByteArray = (obj as ByteArray) - // Inspect object's memory layout -} -``` - -**Low-level data conversion:** -```ovum -unsafe { - val intValue: Int = 42 - val bytes: ByteArray = (intValue as ByteArray) - // Convert Int to raw bytes -} -``` - -**Performance-critical operations:** -```ovum -unsafe { - val largeArray: IntArray = IntArray(1000000) - val bytes: ByteArray = (largeArray as ByteArray) - // Direct memory operations for performance -} -``` From 0b8ad830af0b3f1069b18fbeb3001bc069d997b3 Mon Sep 17 00:00:00 2001 From: bialger Date: Tue, 7 Oct 2025 01:49:31 +0300 Subject: [PATCH 2/2] docs: update README with online documentation links - Changed project documentation links to point to the online documentation for easier access. - Updated the full language reference link to direct users to the online version while retaining the local file reference. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fa41408..9b23c05 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,8 @@ Ovum is a strongly statically typed, single-threaded language focused on safety, clarity, and performance. It uses Kotlin-like syntax, immutability by default, a GC + JIT VM, interface-based polymorphism, and support for pure functions and functional objects. - Contribute: see [`CONTRIBUTING.md`](CONTRIBUTING.md). -- Project docs: [`docs/README.md`](docs/README.md). -- Full language reference: [`docs/reference/README.md`](docs/reference/README.md). +- Project docs: [Online](https://ovum-programming-language.github.io/OvumDocs/) or [`docs/README.md`](docs/README.md). +- Full language reference: [Online](https://ovum-programming-language.github.io/OvumDocs/reference/) or [`docs/reference/README.md`](docs/reference/README.md). ---