Docs Examples Why Mantra About Language Tour Download GitHub
Architecture & Systems Engineering

Why Mantra?

Mantra was engineered from the ground up to solve the real-world friction of building large-scale software. It combines Python-like visual simplicity, strict object-oriented typing, and an ultra-fast Rust-powered compiler engine.

Built for serious software.

Every feature in Mantra exists to help you write clear, structured, maintainable code — at any scale.

πŸ›οΈ
Full OOP
Classes with constructors, public & private members, __init__, and self. Build real data models fast.
πŸ”—
Interfaces
Define contracts with interface. Any class can implements multiple interfaces enabling true polymorphism.
🧬
Inheritance
extends parent classes, call super().__init__(), and override methods. Full multi-level class hierarchies.
πŸ”’
Abstract Classes
Define abstract blueprints with abstract class and abstract def. Force subclasses to implement required behaviour.
⚑
Static Members
Class-level constants and functions with static. Utility classes like MathUtils.square(7) with zero boilerplate.
🧩
Properties & Composition
Computed @property getters and object composition — build rich models by assembling simpler objects.
πŸ¦€
Rust + C++ Core
Built on a modular Rust workspace (mantra_lexer, mantra_parser, mantra_codegen…). Native code output via Clang/LLVM.
πŸ“¦
Rich Standard Library
Built-in packages: mantra.lang, mantra.io, mantra.util.collections, mantra.net.http, mantra.sql.orm, mantra.web, mantra.rest.
πŸ› οΈ
Mantra MDK
The Mantra Development Kit scaffolds projects, formats code, generates docs, and manages mantra.toml manifests.
πŸ€–
AI & LLM Friendly
Mantra's consistent, minimal syntax is ideal for AI code generation and LLM integration. One class model, one function signature, no ambiguous overloads — AI assistants produce correct Mantra code on first attempt.
⚑
Native Performance
The entire toolchain is written in Rust. Zero garbage collection pauses, memory-safe by default, and production-grade error diagnostics. The native emit path leverages Clang/LLVM with no runtime overhead.
🌐
Build & Contribute
Use Mantra's standard packages as a foundation to build libraries and share them with the community. The MDK provides mantra new, mantra doc, and mantra fmt so contributing is one command away.
Back to top ↑
Back to top ↑

Is it better to build a programming language with Rust or C++ for faster performance?

Both Rust and C++ have virtually identical theoretical peak execution performance because both compile to bare-metal machine code using state-of-the-art optimizing backends (primarily LLVM or GCC) with zero runtime garbage collection.

However, in practice, Rust is generally better, faster to build, and often produces faster real-world compilers and language runtimes than C++.

Here is the comprehensive technical breakdown of why:

1. Architectural & Optimization Advantages of Rust for Compilers

Compilers are memory-intensive, tree-traversing systems. Rust provides specific language guarantees that allow optimizing compilers like LLVM to generate faster assembly than typical C++ equivalents.

Feature Rust C++ Why it Matters for Language Performance
Strict Aliasing Guarantees (noalias) Built into the language (&mut is guaranteed unique) Requires manual __restrict keywords which are rarely used throughout ASTs In Rust, LLVM knows two mutable references can never point to the same memory. This enables aggressive loop vectorization, register caching, and dead-code elimination that C++ compilers cannot safely perform.
AST Modeling (Enums & Pattern Matching) Native tagged unions (enum + match) std::variant / std::visit or OOP inheritance (virtual dispatch) Compilers traverse millions of AST nodes. Rust enums are contiguous in memory with single-word discriminants and compile to fast jump tables. In C++, OOP visitor patterns cause pointer chasing, cache misses, and vtable dispatch overhead.
Parallel Compilation / Multi-threading Fearless Concurrency (Send + Sync, Rayon) Manual locking, high risk of data races and undefined behavior Modern fast compilers achieve speed through parallelization (parallel parsing, type-checking, code emission). Rust prevents data races at compile time, making parallel compiler pipelines trivial to write.
Arena & Bump Allocation High-performance crates (bumpalo, typed-arena) with strict lifetime safety Manual pointer management or slow smart pointers (std::shared_ptr) Compilers allocate millions of small nodes. Arena allocation avoids heap fragmentation and allocates in nanoseconds. Rust guarantees arena lifetimes don't dangle at compile-time.

2. Where C++ Has an Advantage

While Rust leads in ergonomics and modern compiler safety, there are specific domains where C++ remains influential:

πŸ”Œ
Direct LLVM C++ API
LLVM itself is written in C++. If you write your compiler in C++, you link directly against native LLVM headers without needing a C-FFI wrapper like Rust's inkwell or llvm-sys.
πŸ›οΈ
Decades of Legacy VM Codebases
Projects like V8 (JavaScript) or the HotSpot JVM are written in C++. If you are embedding or forking an existing C++ runtime engine, staying in C++ avoids bridge overhead.
🎯
Unchecked Micro-optimizations
In C++, you can cast arbitrary memory, bypass type boundaries, and do raw pointer arithmetic anywhere. While this can yield micro-optimizations, in large codebases it frequently introduces subtle segfaults and memory corruption.

3. Industry Precedent: Why Modern Language Tooling Uses Rust

Over the last 5 years, high-performance compiler and language projects have almost universally chosen Rust over C++:

Frontend Compilers
SWC
Next-generation TypeScript and JavaScript compiler written in Rust. Replaced Babel across the JavaScript ecosystem and runs 20x faster.
Static Analysis
Ruff
An extremely fast Python linter and formatter written in Rust. Replaced Flake8, Black, and isort while running 100x faster.
Bundlers & Tooling
Turbopack & Biome
Vercel's successor to Webpack (Turbopack) and the Biome toolchain are written in Rust to deliver instantaneous HMR and AST parsing.
Language Runtimes
Deno & Bun
Modern runtimes built using modern memory-safe architectures (Rust and Zig) instead of traditional C++ glue code.
Modern Languages
Gleam & Typst
Fast modern languages whose entire compiler, type-checker, and document rendering pipelines are 100% Rust.

πŸ† Verdict for Mantra

Mantra's architecture — building the core language compiler, VM, and standard packages in Rust (crates/mantra, crates/mantrac, crates/mantra_codegen, etc.) — is the optimal choice:

⚑ Safety with Speed

You get pure native binary performance with zero garbage collection pauses and compile-time memory safety.

🧩 Maintainability

Pattern matching on AST tokens, types, and expressions in Rust is significantly cleaner and less error-prone than in C++.

πŸ“¦ Tooling & Packages

Cargo makes managing modular crates (like mantra_web, mantra_rest, mantra_sql_orm) seamless compared to CMake/Makefiles in C++.

Back to top ↑
Back to top ↑

Q&A: Why not just use Rust directly?

You can absolutely write applications directly in Rust. In fact, Mantra’s compiler itself is built in Rust. So why create and use Mantra instead of writing raw Rust?

The Short Answer:

Rust is a low-level systems language built for maximum control and engine-level infrastructure; Mantra is an application-level language built for developer velocity, full Object-Oriented architecture, and clean modeling without borrow-checker friction.

Here is the exact comparison of what makes Mantra fundamentally different from Rust:

1. No Borrow-Checker Friction vs. Lifetimes & Ownership

In Rust

You have to spend significant mental energy managing lifetimes ('a), borrow scopes, ownership moves, and interior mutability wrappers (Rc<RefCell<T>>, Arc<Mutex<T>>, Box<T>). Writing cyclic data graphs (like GUI widgets, tree nodes with parent pointers, game entities, or domain models) often turns into a battle against the borrow checker.

In Mantra

You have intuitive, natural reference semantics. You instantiate an object with class and pass it around naturally, just like in Python, Java, or C#, without fighting compiler lifetime errors.

2. First-Class Object-Oriented Programming (OOP)

In Rust: Rust is not an OOP language. It intentionally has no inheritance (extends), no abstract classes, no constructors, and no subclass polymorphism. Rust uses struct + trait composition. While traits are great for systems code, modeling enterprise business domains, hierarchical models, or classical design patterns (Template Method, Factory, Observer) in Rust requires complex trait boilerplate.

In Mantra: Complete, modern OOP is a core pillar:

shapes.mantra
abstract class Shape: abstract def area(self) -> Float class Circle(Shape): pub radius: Float def __init__(self, radius: Float): self.radius = radius override pub def area(self) -> Float: return 3.14159 * self.radius * self.radius

You get class, implements (multiple interfaces), extends (inheritance), super().__init__(), abstract class, override, and @property built directly into the language.

3. Syntax Ceremony & Developer Velocity

In Rust: Heavy visual noise. Rust code requires explicit type annotations, explicit error handling propagation (?, map_err), borrowing markers (&, &mut), lifetime annotations (<'a, T: 'static + Send>), semicolons, and curly braces everywhere:

rust_syntax.rs
// Rust pub fn get_user<'a>(&self, id: u64) -> Result<&'a User, Box<dyn std::error::Error + Send + Sync>> { self.users.iter().find(|u| u.id == id).ok_or_else(|| "Not found".into()) }

In Mantra: Clean, whitespace-sensitive, Python-like clarity:

mantra_syntax.mantra
# Mantra pub def get_user(self, id: Int) -> User: return self.users.find_by_id(id)

βœ“ You write clean, readable business logic 2x to 3x faster than in Rust.

4. Fast Compilation & Instant Feedback

In Rust

Compile times are a well-known pain point. Due to heavy macro expansions, monomorphization of generics, and large dependency trees, even medium-sized Rust projects can take 15–45 seconds for incremental rebuilds and minutes for full builds.

In Mantra

The Mantra compiler (mantrac) uses a lightweight, single-pass pipeline designed for instantaneous feedback. Running your app is as fast as:

mantrac app.mantra --run

5. AI and LLM Code Generation Friendly

In Rust

Large Language Models (LLMs) frequently struggle with Rust. Even advanced AI models frequently hallucinate types or produce code that fails to compile due to subtle borrow checker errors (E0382: use of moved value, E0597: borrowed value does not live long enough).

In Mantra

The syntax is minimal, unambiguous, and orthogonal. There are no confusing overload rules or borrow annotations. AI code generators produce syntactically correct, compiling Mantra code on the first prompt.

Summary: When to Use Rust vs. When to Use Mantra

Dimension Rust Mantra
Primary Domain Systems, compilers, OS kernels, game engines, embedded devices Application software, REST APIs, web backends, data modeling, tooling
Paradigm Functional + Trait composition (No OOP) Full Object-Oriented (Classes, Inheritance, Interfaces)
Memory Model Strict compile-time borrow checker & lifetimes Intuitive reference semantics with native speed
Syntax Style Explicit, verbose, systems-level Clean, minimal, Python-like indentation
Developer Speed Slower (meticulous safety & lifetime design) High velocity (focus on business logic)
Compiler Speed Heavy, slow compile times Lightweight, rapid edit-compile-run loop

πŸ’‘ The Engine & The Car Analogy

Rust is like the precision CNC machine used to build the high-performance engine.

Mantra is the luxury sports car built with that engine — delivering high speed with an effortless, ergonomic driving experience.

Back to top ↑
↑ Back to top