FrontLang v1.0.0 Stable Production Release • 14 Milestones Complete • Independent Statically-Typed Language in Pure Rust Explore Docs →
Language & Compiler Toolchain • Milestones 1–14 Production-Ready

FrontLang

v0.1.0 • Designed & Owned by FrontTerrain

An independent, statically-typed, indentation-based programming language engineered completely from scratch in Rust. Featuring a Flutter-grade TrueType vector typography engine, 60 FPS hardware-accelerated dynamic GUI and animation kit, zero-dependency networking, and three versatile execution targets.

0 Dependencies (Pure Rust)
3 Execution Backends
60 FPS Dynamic GUI & Typography
AOT Native Binaries (.exe)
UNIFIED CLI TOOLCHAIN CARGO READY
$ frontlang run examples/hello.ft
Hello, FrontTerrain
• Executed via fast tree-walking AST interpreter with static type validation.
$ frontlang build src/main.ft
Compiled src/main.ft → target/main.ftbc (Magic: FTBC, 284 bytes)
$ frontlang run target/main.ftbc
Computed: fibonacci(10) = 55
• Executed on isolated FrontVM stack machine with cycle guard and frame stack.
$ frontlang compile src/main.ft -o app.exe
Emitted C99 IR → Invoked system toolchain → Built standalone binary app.exe
$ ./app.exe
High-performance native execution completed. Status: 0
$ frontlang run examples/animated_dashboard.ft
[std:gui] Initialized 960x640 Canvas • Locked 60 FPS Frame Pacing
[std:ui] TrueType rasterized: Inter.ttf (Quadratic Bézier, 8-bit alpha, 18px)
• Flutter/Cupertino component kit: elevated cards, spring switches, and typography.
$ frontlang fmt src/ --check
All 14 source files match canonical 4-space layout.
$ frontlang test tests/
Discovered 18 test_* functions: 18 passed, 0 failed.
Core Design Tenet

Zero dependencies on Python, JavaScript, Node.js, or external C runtimes. The entire lexer, parser, type checker, bytecode compiler, VM, and native emitter are written purely with Rust's standard library.

Compiler Architecture

From Source Code to Machine Execution

A modular, staged compilation and runtime pipeline built for determinism, speed, and safety.

Stage 01 Source (.ft)
→
Stage 02 Lexer
→
Stage 03 Parser & AST
→
Stage 04 Type Checker
→
Stage 05 3 Backends
→
Stage 06 Subsystems
Stage 01: Source Code (.ft / .ftl) — Clean UTF-8 source files enforcing the off-side rule for block scoping. Uses strict 4-space indentation; tabs (\t) are strictly forbidden to guarantee 100% deterministic parsing across all operating systems.
Interactive Code Playground

Experience FrontLang in Real Time

Select any preset snippet, test syntax with optional static type annotations, and simulate execution directly in your browser.

Presets:
Terminal Output — frontlang run ● Ready
Welcome to FrontLang, FrontTerrain Engine status: Operational (Year 2026) [Process completed with exit code: 0]
01 • Language Foundations

Overview & Philosophy

FrontLang is a modern general-purpose programming language designed by FrontTerrain for developers who demand both the aesthetic elegance of Python and the runtime safety and speed of modern systems languages.

Off-Side Indentation

Clean visual hierarchy without curly braces {} or semicolons ;. Exact 4-space indentation; tabs are forbidden for determinism.

Strong Static Typing

Static type verification catches errors before execution. Supports inference for local declarations alongside explicit function signatures.

Zero Dependencies

Built purely with Rust's standard library. No bloated third-party dependencies, guaranteeing rapid build times and long-term stability.

Three Execution Targets

Choose the optimal execution mode for your workflow: rapid AST interpretation, portable FrontVM bytecode, or native machine code binaries.

02 • Setup & Installation

Quickstart & Installation

FrontLang installs with a single command on Windows, Linux, and macOS, or can be compiled directly from source using any modern Rust toolchain (Rust 1.80+ or newer).

1. One-Command Automatic Installation (Recommended)

The automated installer detects your operating system and CPU architecture, downloads the latest precompiled release binary, configures your system PATH, and verifies the environment automatically:

PowerShell
irm https://raw.githubusercontent.com/FrontTerrain/FrontLang/main/install.ps1 | iex
Bash / Zsh
curl -fsSL https://raw.githubusercontent.com/FrontTerrain/FrontLang/main/install.sh | bash
Automated Binary & Source Fallback

The installer installs into ~/.frontlang/bin and appends it to your user PATH. If a precompiled binary is not yet published for your specific architecture, it automatically compiles from source if the Rust toolchain is present.

2. Building from Source (Cargo)

If you prefer building directly from source or contributing to the compiler toolchain:

Terminal — Cargo Build
# Clone the repository
git clone https://github.com/Front-Terrain/FrontLang.git
cd FrontLang

# Build optimized release binary (target/release/frontlang)
cargo build --release

# Run full compiler and runtime regression test suite
cargo test

3. Running Your First Program

Create a file named hello.ft with the following content:

FrontLang — hello.ft
# hello.ft — First FrontLang program
let greeting: String = "Hello, FrontTerrain"

fn main() -> Int:
    show(greeting)
    return 0

Execute it using the unified CLI:

Terminal
frontlang run hello.ft
# Output:
Hello, FrontTerrain
03 • Project Manifest

Project Configuration (frontlang.toml)

FrontLang projects can define a frontlang.toml manifest at their root directory. When this file is present, CLI commands infer entrypoints, dependencies, and compilation targets automatically without requiring explicit file paths.

TOML — frontlang.toml
[package]
name = "my_application"
version = "0.1.0"
entrypoint = "src/main.ft"
description = "A modern FrontLang application"

[dependencies]
vector_math = "^0.2.0"
my_physics = { git = "https://github.com/username/my_physics.git", tag = "v1.0.0" }
local_utils = { path = "../local_utils" }

Within a directory containing frontlang.toml, invoke commands directly:

Terminal
frontlang run          # Runs entry file specified in frontlang.toml
frontlang check        # Static type-checks the project entrypoint
frontlang build        # Compiles entrypoint into portable .ftbc bytecode
frontlang compile      # Compiles Ahead-of-Time to standalone native executable (.exe)
04 • Package Ecosystem

FrontLang Package Manager & Distribution

FrontLang features a complete, zero-external-dependency package management ecosystem powered by standard POSIX USTAR archives (.ftpkg), cryptographic SHA-256 verification, a full SemVer 2.0.0 constraint solver (^, ~, >=, <=, *), and a global shared cache (~/.frontlang/cache).

1. CLI Package Workflow

Terminal — Package Commands
# Initialize a new application project (src/main.ft)
frontlang init my_package

# Initialize a reusable library module (src/lib.ft)
frontlang init my_lib --lib

# Install a central registry package with SemVer resolution
frontlang add vector_math --version "^0.2.0"

# Add a decentralized Git package (pins exact commit in frontlang.lock)
frontlang add username/my_physics_engine

# Add a local path dependency
frontlang add ../local_utils --path

# Install all dependencies pinned in frontlang.lock into front_modules/
frontlang install

# Remove an installed dependency
frontlang remove vector_math

# Bundle project into an optimized, zero-dependency .ftpkg archive
frontlang pack

# Extract an archive for inspection
frontlang unpack dist/my_pkg-1.0.0.ftpkg -o inspected/

2. Deterministic Reproducibility (frontlang.lock)

When dependencies are resolved and installed, FrontLang automatically generates a lockfile (frontlang.lock) guaranteeing 100% deterministic, bite-for-byte reproducible builds across team members and CI/CD pipelines:

TOML — frontlang.lock
# frontlang.lock — Generated automatically by FrontLang
lockfile_version = 1

[[package]]
name = "vector_math"
version = "0.2.4"
source = "registry+https://fronthub.frontterrain.com"
checksum = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"

[[package]]
name = "my_physics"
source = "git+https://github.com/username/my_physics.git"
commit = "d3b07384d113edec49eaa6238ad5ff0012345678"
tag = "v1.0.0"

3. SemVer 2.0.0 Solver & Global Shared Cache

FrontLang includes a built-in semantic version constraint solver supporting caret ranges, tilde ranges, wildcards, and compound bounds:

  • ^1.2.3 — Compatible updates (>= 1.2.3, < 2.0.0)
  • ~1.2.3 — Patch-only updates (>= 1.2.3, < 1.3.0)
  • >= 1.0.0, < 2.0.0 — Multi-boundary range specifications
  • * — Any available version

Downloaded packages and archives are cached globally in ~/.frontlang/cache/. When adding or installing dependencies already cached on disk, FrontLang installs them instantly offline with zero network latency:

Terminal — Cache Management
# List cached packages, versions, and disk sizes
frontlang cache list

# Clean global cache to reclaim disk space
frontlang cache clean
05 • High-Efficiency Compression

Codrop™ Adaptive Compression & Dead-Code Tree-Shaking

FrontLang integrates FrontTerrain's Codrop (.cdp) universal adaptive lossless compression engine directly into its packaging and distribution pipeline:

70%–85% Payload Shrinkage

When running frontlang pack or frontlang publish, the archive is automatically compressed with Codrop, drastically reducing upload bandwidth, download latency, and registry storage.

Transparent Decompression

frontlang install and frontlang unpack detect Codrop container magic (cdp) and decompress on the fly while retaining 100% backward compatibility with uncompressed POSIX USTAR archives.

Dead-Code Tree-Shaking

Pass --tree-shake (-s) to prune dead code, unused helper scripts, and test suites. Only files transitively imported starting from your entrypoint are packaged.

Terminal — Codrop & Tree-Shaking
# Package with default Codrop adaptive compression
frontlang pack

# Package with Codrop compression AND dead-code tree-shaking
frontlang pack --tree-shake

# Publish with tree-shaking and Codrop compression to FrontHub
frontlang publish --tree-shake

# Produce an uncompressed legacy POSIX USTAR archive if needed
frontlang pack --no-compress
06 • Central Registry

FrontHub — The Official Package Registry Portal

FrontHub (https://fronthub.frontterrain.com) is the official web registry portal and HTTP API service for FrontLang packages.

Exploration & Live Search

Instant keyword, tag, and author filtering for modules. Search directly from CLI with frontlang search <query> or in browser.

Rich Package Pages

Interactive markdown README rendering, version history tables, dependency trees, and copyable install snippets (frontlang add <pkg>).

Cryptographic Provenance

Direct SHA-256 checksum verification, raw .ftpkg binary downloads, and developer token management (ft_live_...).

Central Registry CLI Workflow

Terminal — FrontHub Authentication & Publishing
# 1. Authenticate with your FrontHub developer token
frontlang login ft_live_your_secret_token

# 2. Search for packages in the registry
frontlang search vector

# 3. View metadata, description, and SHA-256 checksum
frontlang info vector_math

# 4. Publish your module (verifies syntax, types, bundles with Codrop)
frontlang publish

# 5. Clear saved credentials from ~/.frontlang/credentials.toml
frontlang logout

Complete FrontHub HTTP API (v1)

FrontHub provides an open, high-performance RESTful HTTP API:

Method & Endpoint Authentication Purpose & Response
GET /api/v1/packages/search?q=:query Public Searches package titles, tags, and descriptions. Returns JSON package list.
GET /api/v1/packages/:name Public Returns full package metadata, versions log, author info, and dependencies.
GET /api/v1/packages/:name/:version/download Public Streams binary .ftpkg distribution archive.
POST /api/v1/packages/publish Bearer Token (ft_live_...) Uploads package archive with cryptographic SHA-256 hash validation.
POST /api/v1/auth/token Developer Key Provisions developer API access token for automated CLI authentication.
04 • Syntax Foundations

Indentation & Lexical Conventions

FrontLang uses the off-side rule for block scoping. Block boundaries are determined exclusively by indentation levels, eliminating curly braces and semicolons.

4-Space Indentation Standard

FrontLang standardizes on exactly 4 spaces per indentation level. Hard tabs (\t) in indentation are strictly prohibited by the lexer and result in a compile error for deterministic cross-editor consistency.

Comments

Single-line comments begin with # and extend to the end of the line:

FrontLang
# This is a full-line comment in FrontLang
let max_connections: Int = 1000 # Trailing comment

Identifiers & Keywords

Identifiers start with an ASCII letter or underscore ([a-zA-Z_]) followed by alphanumeric characters or underscores.

Category Keywords / Tokens Notes
Declarations let, fn, return Variable declarations and function definitions
Control Flow if, elif, else, while, break, continue Branching and loop control primitives
Boolean Literals true, false Case-sensitive boolean values
Logical Operators and, or, not Short-circuiting boolean operations
05 • Language Specification

Formal Grammar (EBNF)

FrontLang is formally defined using an unambiguous Extended Backus-Naur Form (EBNF) grammar. The syntax combines an off-side rule indentation stack with recursive descent parsing for declarations and a high-performance Pratt parser for mathematical and logical operator precedence.

EBNF — FrontLang Grammar Specification v1.0.0
Program              ::= ( TopLevelItem )* EOF

TopLevelItem         ::= FunctionDecl
                       | ExternFunctionDecl
                       | StructDecl
                       | IncludeDecl
                       | Statement

IncludeDecl          ::= "include" StringLiteral Newline

StructDecl           ::= "struct" Identifier ":" Newline Indent ( StructField )+ Dedent
StructField          ::= Identifier ":" TypeAnnotation Newline

FunctionDecl         ::= "fn" Identifier "(" [ ParameterList ] ")" [ "->" TypeAnnotation ] ":" Suite
ExternFunctionDecl   ::= "extern" [ StringLiteral ] "fn" Identifier "(" [ ParameterList ] ")" [ "->" TypeAnnotation ] Newline

ParameterList        ::= Parameter ( "," Parameter )*
Parameter            ::= Identifier ":" TypeAnnotation

Suite                ::= Newline Indent Statement+ Dedent
                       | Statement

Statement            ::= LetStmt
                       | AssignStmt
                       | MemberAssignStmt
                       | IndexAssignStmt
                       | IfStmt
                       | WhileStmt
                       | ForStmt
                       | TryCatchStmt
                       | ThrowStmt
                       | ReturnStmt
                       | BreakStmt
                       | ContinueStmt
                       | ExprStmt

LetStmt              ::= "let" Identifier [ ":" TypeAnnotation ] "=" Expression Newline
AssignStmt           ::= Identifier "=" Expression Newline
MemberAssignStmt     ::= Expression "." Identifier "=" Expression Newline
IndexAssignStmt      ::= Expression "[" Expression "]" "=" Expression Newline

IfStmt               ::= "if" Expression ":" Suite 
                         ( "elif" Expression ":" Suite )* 
                         [ "else" ":" Suite ]

WhileStmt            ::= "while" Expression ":" Suite
ForStmt              ::= "for" Identifier "in" Expression ":" Suite

TryCatchStmt         ::= "try" ":" Suite "catch" [ Identifier ] ":" Suite
ThrowStmt            ::= "throw" Expression Newline

ReturnStmt           ::= "return" [ Expression ] Newline
BreakStmt            ::= "break" Newline
ContinueStmt         ::= "continue" Newline
ExprStmt             ::= Expression Newline

TypeAnnotation       ::= "Int" 
                       | "Float" 
                       | "Bool" 
                       | "String" 
                       | "Unit" 
                       | "[" TypeAnnotation "]"
                       | "Map" "[" TypeAnnotation "," TypeAnnotation "]"
                       | "(" TypeAnnotation ( "," TypeAnnotation )* ")"
                       | Identifier

Expression           ::= LogicalOrExpr

LogicalOrExpr        ::= LogicalAndExpr ( "or" LogicalAndExpr )*
LogicalAndExpr       ::= EqualityExpr ( "and" EqualityExpr )*
EqualityExpr         ::= RelationalExpr ( ( "==" | "!=" ) RelationalExpr )*
RelationalExpr       ::= AdditiveExpr ( ( "<" | "<=" | ">" | ">=" ) AdditiveExpr )*
AdditiveExpr         ::= MultiplicativeExpr ( ( "+" | "-" ) MultiplicativeExpr )*
MultiplicativeExpr   ::= UnaryExpr ( ( "*" | "/" | "%" ) UnaryExpr )*
UnaryExpr            ::= ( "-" | "not" ) UnaryExpr | PostfixExpr

PostfixExpr          ::= PrimaryExpr 
                         ( "(" [ ArgumentList ] ")" 
                         | "[" Expression "]" 
                         | "." Identifier 
                         )*

ArgumentList         ::= Expression ( "," Expression )*

PrimaryExpr          ::= IntegerLiteral
                       | FloatLiteral
                       | StringLiteral
                       | BooleanLiteral
                       | "null"
                       | ArrayLiteral
                       | MapLiteral
                       | TupleLiteral
                       | Identifier
                       | "(" Expression ")"

ArrayLiteral         ::= "[" [ Expression ( "," Expression )* ] "]"
MapLiteral           ::= "{" [ MapEntry ( "," MapEntry )* ] "}"
MapEntry             ::= Expression ":" Expression
TupleLiteral         ::= "(" Expression "," Expression ( "," Expression )* ")"

Indentation Stack

The lexer maintains an internal indentation stack (initialized to [0]). Dedents can pop multiple levels in a single token boundary.

Pratt Precedence

Operator expressions use Pratt parsing with explicit binding power, ensuring mathematically sound associativity with zero left-recursion issues.

05 • Static Semantics

Static Type System

FrontLang features strong, static typing. Every expression and variable has a known type verified by the semantic analyzer before execution.

Type Rust Representation Description & Example
Int i64 64-bit signed integer (e.g. 42, -10, 0)
Float f64 64-bit IEEE 754 floating point number (e.g. 3.14159, -0.5)
Bool bool Boolean truth value (true or false)
String String UTF-8 encoded string literal with escape sequence support
Unit () Represents the absence of a meaningful value (void return)
List[T] Vec<T> Generic homogeneous dynamic list collection
Map[K, V] HashMap<K, V> Generic key-value hash map collection
06 • State & Scoping

Variables & Reassignment

Variables are declared with the let keyword. Type annotations are optional when the initializing expression allows type inference:

FrontLang
# Explicit type annotations
let username: String = "rishi"
let port: Int = 8080
let timeout: Float = 30.5
let is_active: Bool = true

# Inferred type annotations
let count = 100          # Inferred as Int
let ratio = 1.618        # Inferred as Float
let msg = "FrontTerrain" # Inferred as String

# Variable Reassignment
count = count + 1
port = 9000

Reassigning to an undeclared variable or attempting to assign a value of an incompatible type causes a static type error.

07 • Modular Logic

Functions & Recursion

Functions are declared with fn, parameter lists with type annotations, an explicit return type arrow (-> Type:), and an indented block:

FrontLang
# Standard function declaration
fn add(a: Int, b: Int) -> Int:
    return a + b

# Recursive Fibonacci calculation
fn fibonacci(n: Int) -> Int:
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

# Main entrypoint
fn main() -> Int:
    show("Result of 15 + 27:", add(15, 27))
    show("Fibonacci(7):", fibonacci(7))
    return 0
Ahead-of-Time Signature Registration

FrontLang registers all function signatures before analyzing bodies. This enables mutual recursion and calling functions declared later in the same source file without forward declarations.

08 • Branching & Loops

Control Flow

FrontLang supports conditional evaluation via if, elif, and else, along with repetitive looping via while:

FrontLang
let score: Int = 88

if score >= 90:
    show("Grade: Distinction")
elif score >= 80:
    show("Grade: Honors")
elif score >= 50:
    show("Grade: Pass")
else:
    show("Grade: Retake required")

# While loop with break and continue
let i: Int = 0
while i < 10:
    i = i + 1
    if i == 3:
        continue # Skip 3
    if i == 7:
        break    # Exit loop
    show("Iteration:", i)
09 • Exception Safety

Structured Error Handling (try / catch / throw)

FrontLang provides robust, structured exception handling across all three execution tiers (AST Interpreter, FrontVM bytecode engine, and Native C99 AOT compiler). Unhandled errors and assertions can be captured gracefully without terminating the application process.

Explicit Exceptions (throw)

Raise user exceptions with throw <expression> supplying descriptive error messages or status payloads.

Catching Panics & Bounds

try: ... catch err: ... captures user exceptions alongside runtime panics, assertion failures, and out-of-bounds subscripts.

Anonymous Catch Blocks

Omit error variable identifier when payload is unused (try: ... catch: ...) for concise fallback execution.

FrontLang — try / catch / throw
fn safe_divide(a: Int, b: Int) -> Int:
    if b == 0:
        throw "Division by zero is undefined"
    return a / b

fn main() -> Int:
    # 1. Catching user-thrown exceptions with payload binding
    try:
        let result = safe_divide(10, 0)
        show(result)
    catch err:
        show("Handled gracefully:", err)

    # 2. Catching assertion failures and runtime panics
    try:
        assert(2 + 2 == 5, "Math verification failed")
    catch msg:
        show("Caught assertion failure:", msg)

    # 3. Anonymous catch (omitting error variable)
    try:
        throw "Silent internal fault"
    catch:
        show("An error occurred, but system recovered cleanly")

    return 0
10 • Runtime Built-ins

Built-in Functions, Terminal Input & Operators

FrontLang provides essential runtime functions, console stdin interaction, and operator overloads built into the core language primitives:

Built-in / Operator Signature & Example Behavior & Description
show(...) show("Value:", 42) Prints string representations of arguments separated by spaces, ending with a newline.
enter([prompt]) let name = enter("Enter name: ") Reads a line of user input from standard input (stdin) with an optional prompt, returning a trimmed String.
input([prompt]) let age = input("Age: ") Convenient alias for enter(...) for console user prompts.
len(coll) len(my_list), len(my_map) Returns element count of String, List, Map, or Tuple.
assert(cond, [msg]) assert(x > 0, "x must be positive") Verifies invariants. Incurs catchable exception or process panic on failure.
Arithmetic Operators +, -, *, /, % Operates on Int and Float. + also performs string concatenation.
Relational Operators ==, !=, <, <=, >, >= Evaluates comparisons producing a Bool.
Boolean Operators and, or, not Short-circuiting boolean logical operations.
11 • Data Structures & Collections

Lists, Maps & Rich Strings (DSA)

FrontLang features native high-performance data structures built for algorithmic problem solving (DSA / LeetCode) and structured applications:

1. Dynamic Lists (List[T] or [T])

Growable dynamic arrays with subscript indexing, element mutation, and length querying:

FrontLang — Lists
# Dynamic integer list
let nums: List[Int] = [10, 20, 30]
nums[1] = 99           # Element mutation

show(nums[1])        # 99
show(len(nums))      # 3

2. Dictionaries & Hash Maps (Map[K, V])

Associative key-value hash maps using curly-brace literals with constant-time lookup and rich dot-call methods:

FrontLang — Maps & Dot-Call Methods
let scores: Map[String, Int] = {"alice": 95, "bob": 80}
scores["charlie"] = 88

# Subscript access & length
show(scores["alice"])            # 95
show(len(scores))                # 3

# Expressive Map dot-call methods
show(scores.has("alice"))        # true
show(scores.get("dave", 0))      # 0 (fallback default)
show(scores.keys())              # ["alice", "bob", "charlie"]
show(scores.values())            # [95, 80, 88]

let removed = scores.remove("bob")
scores.clear()
show(len(scores))                # 0

3. Expressive String Dot-Call Methods

Strings in FrontLang support zero-overhead dot-call inspection and transformation methods:

FrontLang — String Operations
let s = "  FrontLang Core  "
show(s.trim())                          # "FrontLang Core"
show(s.to_lower())                      # "  frontlang core  "
show(s.to_upper())                      # "  FRONTLANG CORE  "
show(s.contains("Lang"))                # true
show(s.starts_with("  Front"))          # true
show(s.ends_with("Core  "))             # true
show(s.replace("Core", "Ecosystem"))    # "  FrontLang Ecosystem  "
show(s.split(" "))                      # ["", "", "FrontLang", "Core", "", ""]
show(s.sub(2, 11))                      # "FrontLang"

4. Heterogeneous Tuples ((T1, T2, ...))

Immutable, heterogeneous fixed-size groupings commonly used for multi-value returns from functions. Accessible via positional dot indices (.0, .1) or bracket indices ([0], [1]):

FrontLang — Tuples
fn get_user() -> (String, Int, Bool):
    return ("Rishi", 25, true)

let user = get_user()
show(user.0)         # "Rishi"
show(user.1)         # 25
show(user[2])        # true
11 • Recursive Data Structures

Null & Pointer-Based Structures

FrontLang supports null pointers and self-referential struct declarations, enabling developers to build recursive algorithmic data structures such as singly and doubly linked lists, binary search trees, and graphs:

FrontLang — Linked List Traversal
# Recursive Linked List Node
struct Node:
    val: Int
    next: Node

fn list_sum(head: Node) -> Int:
    let curr = head
    let total = 0
    while curr != null:
        total = total + curr.val
        curr = curr.next
    return total

# Construct 10 -> 20 -> 30 -> null
let list = Node(10, Node(20, Node(30, null)))
show("Linked list sum:", list_sum(list))  # 60
12 • Object-Oriented Programming

Structs & OOP Dot-Call Syntax

FrontLang combines data structures with object-oriented programming ergonomics. Functions defined with the signature {Struct}_{method}(self, ...) can be called directly on struct instances using familiar OOP dot-call syntax (instance.method(...)):

FrontLang — OOP Struct Methods
struct Point:
    x: Int
    y: Int

# Method definition for Point
fn Point_manhattan(self: Point, other: Point) -> Int:
    let dx = self.x - other.x
    if dx < 0:
        dx = -dx
    let dy = self.y - other.y
    if dy < 0:
        dy = -dy
    return dx + dy

fn main() -> Int:
    let p1 = Point(10, 20)
    let p2 = Point(15, 30)

    # Invoked via OOP dot-call syntax
    show("Manhattan distance:", p1.manhattan(p2))  # 15
    return 0
13 • Modular Architecture

Multi-File Modular System (include)

FrontLang delivers a clean, dependency-cycle-safe modular system. Modules are loaded at the top level using the include statement with string literal paths.

FrontLang — Module Inclusions
# Standard library inclusions
include "std:gui"
include "std:ui"
include "std:animation"
include "std:net"

# Project-relative modular inclusions
include "src/models/user.ft"
include "src/services/auth.ft"
Cycle Guard & Deduplication

The compiler enforces automatic cycle detection to prevent infinite recursive includes and performs #pragma once style deduplication so files included transitively multiple times are only parsed once without redefinition collisions.

14 • Standard Library

Standard Library Modules Reference

FrontLang includes battery-included standard modules that can be imported with include "std:<module>":

Module Domain Key Functions & Primitives
std:gui 2D Windowing & TrueType Typography gui_init_window, gui_set_font_size, gui_load_font, gui_set_font_family, gui_draw_text, gui_draw_box, gui_clear, gui_poll_events, gui_begin_frame, gui_end_frame
std:ui Flutter / Cupertino Component Kit ui_card, ui_button_styled, ui_slider_styled, ui_switch_animated, ui_badge, ui_navbar
std:animation Interpolation Curves & Spring Physics lerp_float, lerp_color, ease_in_quad, ease_out_quad, ease_in_out_cubic, ease_out_bounce, ease_out_elastic
std:net Zero-Dependency Sockets & HTTP tcp_connect, tcp_listen, udp_bind, http_get, TcpClient, TcpServer, UdpSocket, HttpResponse
std:concurrency OS Multithreading, CSP Channels & Mutexes thread_spawn, thread_join, mutex_new, mutex_lock, mutex_unlock, channel_new, channel_send, channel_recv, sleep_ms
std:math Mathematical Utilities & Clamping abs, min, max, sqrt, sin, cos, pow, clamp, floor, ceil
std:string String Operations str_len, str_concat, str_contains, str_split, str_to_lower, str_to_upper, str_trim
std:fs File System Read, Write, Append & Directories fs_read_file, fs_write_file, fs_append_file, fs_file_exists, fs_remove_file, fs_read_dir, fs_create_dir
std:time High-Precision Timers & Monotonic Clock time_now_ns, time_now_ms, time_sleep_ms
std:hw Bare-Metal Kernel & Hardware Layer hw_read8..64, hw_write8..64, hw_in8..32, hw_out8..32, hw_cli, hw_sti, hw_hlt, hw_invlpg
std:audio Audio Engine & Waveform Synthesis audio_init, audio_play_tone, audio_load_wav, audio_play_sound, audio_stop_all
std:game Game Loop, Sub-ms Pacing & Input game_init_window, game_poll_events, game_key_down, game_mouse_pos, game_frame_pacing
std:os / std:sys System Introspection & Process Environment sys_platform, sys_arch, os_get_env, os_set_env, os_cwd, os_exit
15 • Network & Sockets

Networking & Socket Layer (std:net)

FrontLang delivers a high-performance cross-platform networking library with zero external dependencies. Supported identically across all three execution tiers (AST Interpreter, FrontVM bytecode, and Native C99 AOT with Winsock2 / POSIX sockets).

FrontLang — HTTP, TCP & UDP
include "std:net"

fn main():
    # 1. High-Level HTTP Client
    let resp = http_get("http://127.0.0.1:8080/api/status")
    show(resp.status_code)
    show(resp.body)

    # 2. Object-Oriented TCP Client
    let client = tcp_connect("127.0.0.1", 8080)
    client.send("PING\n")
    let reply = client.recv(1024)
    show(reply)
    client.close()

    # 3. Object-Oriented TCP Server
    let srv = tcp_listen(9000)
    let conn = srv.accept()
    conn.send("HELLO CLIENT\n")
    conn.close()
    srv.close()

    # 4. UDP Sockets
    let sock = udp_bind(9001)
    sock.send_to("127.0.0.1", 9002, "UDP_PACKET")
    let packet = sock.recv_from(1024)
    show(packet.0) # Payload
    show(packet.1) # Sender IP
    show(packet.2) # Sender Port
    sock.close()

Low-Level Socket Primitives Reference

Built-in Signature Description
net_tcp_connect (String, Int) -> Int Connects to a remote TCP host:port, returns socket descriptor
net_tcp_listen (Int) -> Int Binds and listens on a local TCP port
net_tcp_accept (Int) -> Int Accepts an incoming TCP connection, returning client descriptor
net_send (Int, String) -> Int Transmits string payload over TCP socket
net_recv (Int, Int) -> String Reads up to max_len bytes from TCP socket
net_close (Int) -> Unit Gracefully closes socket descriptor
net_udp_bind (Int) -> Int Binds local UDP socket on specified port
net_udp_send_to (Int, String, Int, String) -> Int Sends datagram to host:port
net_udp_recv_from (Int, Int) -> (String, String, Int) Receives datagram, returning (data, sender_ip, sender_port)
net_http_get (String) -> String Synchronous HTTP/1.1 GET with automatic chunked transfer decoding
16 • Concurrency & Multithreading

Concurrency & Thread Synchronization (std:concurrency)

FrontLang delivers native, cross-platform OS multithreading, thread joining, CSP (Communicating Sequential Processes) message-passing channels, and Mutex locking across all three execution backends:

CSP Message Channels

Transfer payloads safely across thread boundaries without race conditions using channel_new(), channel_send(), and channel_recv().

Native OS Threads

Spawn background work on genuine OS threads with thread_spawn(fn, ...) and synchronize completion using thread_join(thread).

Mutual Exclusion (Mutex)

Protect critical sections and shared mutable data structures with mutex_new(), mutex_lock(), and mutex_unlock().

FrontLang — std:concurrency
include "std:concurrency"

fn worker_task(channel_id: Int, item_id: Int) -> Int:
    sleep_ms(50)
    channel_send(channel_id, item_id * 10)
    return 0

fn main() -> Int:
    # 1. Channels (Message-Passing Concurrency)
    let ch = channel_new()
    let t1 = thread_spawn(worker_task, ch, 1)
    let t2 = thread_spawn(worker_task, ch, 2)

    show(channel_recv(ch))  # 10
    show(channel_recv(ch))  # 20

    thread_join(t1)
    thread_join(t2)

    # 2. Mutexes (Shared State Protection)
    let mtx = mutex_new()
    mutex_lock(mtx)
    # Safe critical section
    mutex_unlock(mtx)
    return 0
17 • File System

File System Operations (std:fs)

FrontLang provides zero-dependency, cross-platform file reading, writing, appending, directory traversal, and existence checks:

FrontLang — std:fs
include "std:fs"

fn main() -> Int:
    let path = "logs/telemetry.txt"
    fs_create_dir("logs")
    fs_write_file(path, "FrontLang 2026 Engine\n")
    fs_append_file(path, "Build status: Verified OK\n")

    if fs_file_exists(path):
        let content = fs_read_file(path)
        show("File Contents:", content)

    let files = fs_read_dir("logs")
    show("Directory Listing:", files)
    return 0
Primitive Signature Description
fs_read_file (String) -> String Reads entire file contents as a UTF-8 string
fs_write_file (String, String) -> Unit Writes or overwrites file with given string content
fs_append_file (String, String) -> Unit Appends string content to the end of a file
fs_file_exists (String) -> Bool Checks whether a file or directory exists on disk
fs_read_dir (String) -> List[String] Returns filenames contained within directory
fs_create_dir (String) -> Unit Creates directory (and parents) if not already existing
fs_remove_file (String) -> Unit Deletes file from the file system
19 • Operating System & Hardware

Bare-Metal Kernel & Hardware Layer (std:hw)

FrontLang provides first-class bare-metal hardware primitives designed for operating system kernel development, embedded systems, and device driver implementations. By executing in --freestanding mode, FrontLang bypasses user-space standard libraries, generating pure machine code that interacts directly with physical CPU registers, ports, and memory.

Physical Memory (MMIO)

Direct pointer read and write access to physical hardware registers without user-space virtual memory translation overhead.

x86 Port-Mapped I/O

Native CPU port communication (inb, inw, inl, outb, outw, outl) for legacy bus peripherals and chipset controllers.

CPU Control Instructions

Direct architectural CPU state manipulation: interrupt enable/disable (cli, sti), halt (hlt), and TLB invalidation (invlpg).

1. Physical Memory Access Primitives (MMIO)

Primitive Type Signature Hardware Operation
hw_read8(addr) (Int) -> Int Reads an 8-bit unsigned byte from raw physical memory address addr
hw_read16(addr) (Int) -> Int Reads a 16-bit word from raw physical memory address addr
hw_read32(addr) (Int) -> Int Reads a 32-bit double-word from physical address addr
hw_read64(addr) (Int) -> Int Reads a 64-bit quad-word from physical address addr
hw_write8(addr, val) (Int, Int) -> Unit Writes an 8-bit byte val into physical memory address addr
hw_write16(addr, val) (Int, Int) -> Unit Writes a 16-bit word val into physical memory address addr
hw_write32(addr, val) (Int, Int) -> Unit Writes a 32-bit double-word val into physical memory address addr
hw_write64(addr, val) (Int, Int) -> Unit Writes a 64-bit quad-word val into physical memory address addr

2. Port-Mapped I/O & CPU Primitives

Primitive Hardware Assembly Operation Description
hw_in8(port) inb %dx, %al Reads 8-bit value from x86 hardware I/O port
hw_in16(port) inw %dx, %ax Reads 16-bit value from x86 hardware I/O port
hw_in32(port) inl %dx, %eax Reads 32-bit value from x86 hardware I/O port
hw_out8(port, val) outb %al, %dx Transmits 8-bit byte val to hardware I/O port
hw_out16(port, val) outw %ax, %dx Transmits 16-bit word val to hardware I/O port
hw_out32(port, val) outl %eax, %dx Transmits 32-bit double-word val to hardware I/O port
hw_cli() cli Clears the CPU interrupt flag (disables maskable interrupts)
hw_sti() sti Sets the CPU interrupt flag (enables maskable interrupts)
hw_hlt() hlt Halts CPU until next external hardware interrupt arrives
hw_invlpg(addr) invlpg (%rdi) Invalidates virtual address TLB cache page entry

3. Kernel Device Driver Implementations

FrontLang Kernel — VGA Text Mode Driver (0xB8000)
include "std:hw"

# Standard x86 VGA Video Buffer is mapped to physical 0xB8000
let VGA_BUFFER = 0xB8000

fn vga_write_char(col: Int, row: Int, ch: Int, color_attr: Int):
    let offset = (row * 80 + col) * 2
    hw_write8(VGA_BUFFER + offset, ch)
    hw_write8(VGA_BUFFER + offset + 1, color_attr)

fn vga_clear(color_attr: Int):
    let row = 0
    while row < 25:
        let col = 0
        while col < 80:
            vga_write_char(col, row, 32, color_attr)
            col = col + 1
        row = row + 1

fn kmain():
    hw_cli()             # Disable interrupts during driver initialization
    vga_clear(0x1F)      # Clear screen with Blue background, White text
    vga_write_char(0, 0, 70, 0x1F) # 'F'
    vga_write_char(1, 0, 84, 0x1F) # 'T'
    hw_sti()             # Re-enable interrupts
    while true:
        hw_hlt()         # Low-power idle state until next interrupt
FrontLang Kernel — Serial COM1 UART Driver (0x3F8)
include "std:hw"

let COM1_PORT = 0x3F8

fn com1_init():
    hw_out8(COM1_PORT + 1, 0x00)    # Disable all interrupts
    hw_out8(COM1_PORT + 3, 0x80)    # Enable DLAB (set baud rate divisor)
    hw_out8(COM1_PORT + 0, 0x03)    # Set divisor to 3 (38400 baud) lo-byte
    hw_out8(COM1_PORT + 1, 0x00)    #                                hi-byte
    hw_out8(COM1_PORT + 3, 0x03)    # 8 bits, no parity, one stop bit
    hw_out8(COM1_PORT + 2, 0xC7)    # Enable FIFO, clear them, 14-byte threshold
    hw_out8(COM1_PORT + 4, 0x0B)    # IRQs enabled, RTS/DSR set

fn com1_putc(c: Int):
    while (hw_in8(COM1_PORT + 5) & 0x20) == 0:
        hw_hlt()
    hw_out8(COM1_PORT, c)
Freestanding Kernel Compilation

Compile bare-metal kernels with the --freestanding flag to suppress all C runtime startup code (crt0) and standard library linkages:

frontlang compile --freestanding kernel.ft -o kernel.bin
frontlang compile --emit-freestanding-c kernel.ft -o kernel.c
16 • Typography Engine

Flutter-Style Vector Typography & TrueType (.ttf) Engine

Just like Flutter and Dart dynamically load vector fonts from asset directories (assets/fonts/*.ttf), FrontLang allows dynamically loading custom TrueType (.ttf) and OpenType (.otf) fonts at runtime with zero binary hardcoding:

FrontLang — TrueType Vector Typography
# Set vector font size dynamically in pixels (e.g. 14, 18, 24, 32, 48)
gui_set_font_size(20)

# Dynamically load external TrueType fonts from assets:
let font_inter    = gui_load_font("assets/fonts/inter.ttf")
let font_playfair = gui_load_font("assets/fonts/playfair.ttf")
let font_fira     = gui_load_font("assets/fonts/fira_code.ttf")

# Activate vector font globally:
gui_set_font_family(font_inter)

# Render with proportional kerning, baseline alignment, and smooth 8-bit alpha coverage:
gui_draw_text("Crisp Vector Typography", 100, 100, 1, Color(255, 255, 255, 255))
gui_draw_text_font("Luxury Editorial Serif", 100, 140, 1, font_playfair, Color(245, 158, 11, 255))
Inter Display • Variable Scale 28px
Modern Analytical Quadratic Bézier Splines
Playfair Luxury Serif • Font Family Dynamic Override
“Design is the silent ambassador of your brand.”
Fira Code • Fixed-Width Developer Monospace
fn render_pipeline(glyph: TrueTypeGlyph) -> RasterSurface

Key Typography Capabilities

TrueType Bézier Curves

Directly parses glyf contours and evaluates quadratic Bézier splines into analytical smooth curves.

Proportional Metrics

Applies variable advance_width and left_side_bearing from font hmtx tables.

True Baseline Alignment

Accurately computes ascents and descenders (letters like 'g', 'p', 'y' drop naturally below the baseline).

8-Bit Subpixel Alpha

Eliminates retro pixelation with continuous 0..255 area-coverage alpha compositing for smooth edges at any resolution.

17 • Graphical User Interface

Modern Dynamic GUI & Widget System (std:ui)

FrontLang includes a hardware-accelerated 2D graphics engine and component library designed with modern Flutter/Cupertino aesthetics, running at locked, jitter-free 60 FPS / 120 FPS frame pacing.

FrontLang — Dynamic Dashboard
include "std:animation"
include "std:ui"
include "std:gui"

fn main() -> Int:
    gui_init_window(960, 640, "FrontLang Modern GUI")
    gui_set_font_size(18)

    let active = true
    let progress = 1.0

    while not gui_window_should_close():
        gui_poll_events()
        gui_begin_frame()

        let dt = gui_get_delta_time()
        
        # Smooth spring animation
        let target = 0.0
        if active:
            target = 1.0
        progress = lerp_float(progress, target, dt * 10.0)

        # Clear background with dark slate
        gui_clear(Color(15, 23, 42, 255))

        # Elevated card with soft drop shadow
        ui_card(40, 40, 400, 260, 14, 4, Color(30, 41, 59, 255), Color(51, 65, 85, 255))

        # Dynamic interactive button with hover and click state
        let clicked = ui_button_styled(60, 180, 160, 36, 18, 1, Color(79, 70, 229, 255), Color(129, 140, 248, 255), Color(255, 255, 255, 255), "Launch")

        # Smooth animated toggle switch
        active = ui_switch_animated(300, 184, 52, 28, active, progress)

        gui_end_frame()
    return 0
● DIRECTDRAW 60 FPS PACING Raster Surface Active
Production Telemetry Dashboard
Sub-millisecond OS timers with fixed-point Porter-Duff alpha blending.
Dynamic Switch:
18 • Motion & Springs

Complete Animation Engine (std:animation)

The std:animation module provides mathematical interpolation curves, physics-based springs, and easing functions designed for fluid user interfaces:

Function Signature Description
lerp_float (Float, Float, Float) -> Float Linear interpolation between two scalars
lerp_color (Color, Color, Float) -> Color Per-channel 8-bit RGBA color blending
ease_in_quad (Float) -> Float Quadratic acceleration curve: $t^2$
ease_out_quad (Float) -> Float Quadratic deceleration curve: $t \times (2 - t)$
ease_in_out_cubic (Float) -> Float Smooth S-curve cubic acceleration and deceleration
ease_out_bounce (Float) -> Float Realistic physical bounce effect for dropdowns and dialogs
ease_out_elastic (Float) -> Float Oscillating damped spring motion for lively toggle switches
23 • Game Development & Audio

Game Loop, High-Precision Timing & Audio Engine

FrontLang combines high-frequency hardware-synchronized frame pacing, a monotonic sub-millisecond clock, multi-platform keyboard/mouse input listeners, and a zero-dependency audio waveform synthesis engine via include "std:game" and include "std:audio".

Nanosecond Monotonic Clock

Nanosecond-precision monotonic timing primitives (time_now_ns()) immunizing game physics against wall-clock system time drift.

Waveform Audio Synthesis

Real-time sinusoidal waveform tone generation, sound effect loading (WAV), polyphonic playback, and volume modulation without external sound daemons.

Hardware Input Polling

Instantaneous cross-platform keyboard and mouse telemetry capturing keypresses, mouse positions, and click events synchronously.

1. Monotonic Timing & Audio Built-ins

Function Module Signature Description
time_now_ns() std:time () -> Int Returns current high-resolution monotonic time in nanoseconds
time_now_ms() std:time () -> Float Returns high-resolution monotonic time in milliseconds as a float
audio_init() std:audio () -> Unit Initializes the native OS audio subsystem (WASAPI / ALSA / PulseAudio)
audio_play_tone(f, d, v) std:audio (Float, Int, Float) -> Unit Synthesizes a sinusoidal wave at frequency f (Hz) for duration d (ms) at volume v (0.0..1.0)
audio_load_wav(path) std:audio (String) -> Int Decodes a standard RIFF/WAV audio file and registers a sound handle ID
audio_play_sound(id) std:audio (Int) -> Unit Triggers non-blocking playback of loaded sound buffer id
game_frame_pacing(fps) std:game (Int) -> Float Enforces target frame rate lock, sleeping remaining budget and returning delta time (dt) in seconds

2. 60 FPS Interactive Game Loop

FrontLang — 60 FPS Asteroids Arcade Loop
include "std:game"
include "std:gui"
include "std:audio"

fn main() -> Int:
    game_init_window("FrontLang Arcade", 800, 600)
    audio_init()

    let player_x = 400.0
    let player_y = 500.0
    let speed = 350.0

    while true:
        # Lock frame rate to 60 FPS and obtain precise delta time
        let dt = game_frame_pacing(60)
        game_poll_events()

        # Arrow key inputs
        if game_key_down(37): # Left Arrow
            player_x = player_x - speed * dt
        if game_key_down(39): # Right Arrow
            player_x = player_x + speed * dt

        # Spacebar triggers audio tone
        if game_key_down(32):
            audio_play_tone(523.25, 40, 0.5) # Note C5

        # Render 2D Scene with Anti-Aliasing
        gui_clear(Color(15, 23, 42, 255))
        gui_draw_circle_aa(player_x, player_y, 18.0, Color(249, 115, 22, 255))
        gui_draw_text("Move: ← / → | Fire: SPACE", 240, 560, 0, Color(148, 163, 184, 255))

    return 0
19 • Execution Workflows

Backend 1: Tree-Walking AST Interpreter

The AST interpreter directly walks the abstract syntax tree in memory. It provides immediate feedback without compilation overhead, making it ideal for rapid prototyping, REPL interactions, and scripting.

Terminal
frontlang run script.ft
20 • Virtual Machine

Backend 2: FrontVM Bytecode Compiler

FrontLang compiles source files into portable .ftbc (FrontTerrain ByteCode) binaries. FrontVM is a high-performance stack-based virtual machine featuring constant pools, call frame stacks, cycle limits, and stack overflow guards.

Terminal
# Compile source file into portable .ftbc bytecode
frontlang build src/main.ft

# Directly execute compiled bytecode on FrontVM
frontlang run src/main.ftbc
21 • Native Ahead-of-Time

Backend 3: Native Compilation (AOT)

For production deployment and maximum hardware throughput, FrontLang compiles source code directly into standalone native executables (.exe on Windows, ELF on Linux, Mach-O on macOS) using an Ahead-of-Time C99 emission pipeline. Intermediate C files are automatically purged after compilation.

Terminal — Native Compilation
# 1. Compile to native standalone binary (.exe) with -O2 optimization
frontlang compile src/main.ft -o my_app.exe

# 2. Emit readable ANSI C99 source code without compiling
frontlang compile src/main.ft --emit-c

# 3. Freestanding bare-metal kernel object compilation (no libc / no crt0)
frontlang compile --freestanding kernel.ft -o kernel.bin

# 4. Emit clean freestanding C99 kernel source
frontlang compile --emit-freestanding-c kernel.ft -o kernel.c
Zero Intermediate Artifacts

When running frontlang compile, FrontLang automatically invokes the host C toolchain (gcc or clang) and deletes any intermediate .c translation artifacts, leaving only your finished production binary.

22 • Cross-Platform Deployment

Multi-Target Compilation & Packaging

FrontLang supports seamless cross-compilation across multiple operating systems and application distribution environments using --target <platform> and frontlang package:

Target Name Aliases Windowing / Runtime Backend Output Artifact
windows win, win32, win64 Win32 GDI / BitBlt / DirectDraw Standalone Windows executable (.exe)
linux unix, posix X11 / Framebuffer Native Linux ELF executable
android apk, ndk Android NDK ANativeWindow Native shared library (.so) + NativeActivity scaffold
web wasm, html5, browser HTML5 2D Canvas via Emscripten Standalone Web runner (index.html + app.js)

1. Multi-Target Compilation CLI

Terminal — Multi-Target Compilation
# Compile specifically for WebAssembly / HTML5 canvas
frontlang compile app.ft --target wasm

# Compile for Linux with custom output path
frontlang compile app.ft --target linux -o bin/app

# Emit portable ANSI C99 source for cross-compiling
frontlang compile app.ft --emit-c

2. Application Packaging CLI (frontlang package)

The package command bundles your code and assets into complete deployable app distributions:

Terminal — App Packaging
# Package an Android NDK NativeActivity project with AndroidManifest.xml and Gradle build scripts
frontlang package app.ft --target android

# Package a Web distribution with standalone index.html runner and Emscripten scripts
frontlang package app.ft --target web

# Package a Windows application bundle
frontlang package app.ft --target windows
23 • Systems Interoperability

Foreign Function Interface (FFI & C ABI)

FrontLang features native Foreign Function Interface (FFI) declarations with zero marshaling overhead. External C libraries, system DLLs, and shared objects can be declared with extern fn and linked directly during compilation:

FrontLang — extern fn Declarations
# Declare libc standard functions
extern fn puts(s: String) -> Int
extern fn abs(n: Int) -> Int
extern fn sqrt(x: Float) -> Float

# Explicit DLL specification for Windows Win32 API
extern "msvcrt.dll" fn printf(fmt: String) -> Int
extern "user32.dll" fn MessageBoxA(hwnd: Int, text: String, title: String, utype: Int) -> Int

fn main() -> Int:
    puts("Direct C ABI invocation from FrontLang")
    let root = sqrt(144.0)
    show(root)
    return 0

C ABI Type Mapping & Marshaling

FrontLang Type C ABI Equivalent Marshaling / Interop Behavior
Int int64_t / int / size_t Passed directly in integer registers across 32-bit and 64-bit platforms
Float double Passed in floating-point registers (SSE / IEEE 754)
Bool bool / int Passed as 0 (false) or 1 (true)
String const char* Passed automatically via internal buffer pointer without memory copy overhead
Unit void Represents void return in C declarations
Native Linker Integration

Link external libraries directly during compilation with standard -l linker flags:

frontlang compile app.ft -luser32 -lm -lraylib -o app.exe
24 • Unified Toolchain

Unified CLI Reference

FrontLang provides a single, unified, high-performance CLI binary covering execution, compilation, package management, distribution, formatting, and automated testing:

Category Command Arguments & Flags Purpose & Description
Execution & Checking frontlang run [file.ft | file.ftbc] Executes source code (via AST interpreter) or compiled bytecode (via FrontVM). Resolves frontlang.toml if path omitted.
frontlang check [file.ft] Runs static type checking, forward signature registration, and syntax validation without code execution.
Compilation Backends frontlang build [file.ft] Compiles source code into portable binary .ftbc bytecode for virtual machine execution.
frontlang compile [file.ft] [-o <output>] [--emit-c] Ahead-of-Time compiles to a native standalone machine executable (.exe / ELF) via C99 code generation.
Package Manager & FrontHub frontlang init [dir] [--lib] Initializes a new project (src/main.ft) or reusable library package (src/lib.ft) with frontlang.toml.
frontlang add <pkg> [--version <ver>] Installs a registry package with SemVer 2.0.0 constraint resolution and SHA-256 verification.
frontlang add <user/repo> [--tag <t>] Adds a decentralized Git dependency, pinning exact commit SHA into frontlang.lock.
frontlang add <path> --path Adds a local filesystem directory dependency.
frontlang install None Downloads and installs all dependencies pinned in frontlang.lock into front_modules/.
frontlang remove <pkg> Removes an installed dependency from frontlang.toml and front_modules/.
frontlang pack [dir] [--tree-shake] [--no-compress] Bundles project into a zero-dependency .ftpkg archive with Codrop compression and dead-code tree-shaking.
frontlang unpack <file.ftpkg> [-o <dest>] Extracts a distribution .ftpkg package archive.
frontlang login [token] Authenticates with the central registry (FrontHub), saving credentials in ~/.frontlang/credentials.toml.
frontlang logout None Clears saved FrontHub authentication credentials.
frontlang publish [dir] [--tree-shake] Verifies types, bundles with Codrop compression, and uploads package archive to FrontHub.
frontlang search <query> Searches package titles, tags, and authors in FrontHub registry.
Cache Management frontlang cache list None Lists all globally cached packages, versions, and disk usage in ~/.frontlang/cache/.
frontlang cache clean None Clears the global package cache to reclaim disk space.
Developer Tooling frontlang fmt [path] [--check] Formats source code to canonical 4-space layout. --check verifies formatting without modifying files.
frontlang test [path] Discovers and executes automated unit test suites (functions starting with test_*).
frontlang repl None Starts interactive REPL shell (:help, :globals, :reset, :clear, :exit).
Information frontlang --version None Displays FrontLang compiler version and active release target.
frontlang --help None Displays full CLI help documentation with available subcommands.
25 • Automated Verification

Built-in Test Runner (frontlang test)

FrontLang includes zero-configuration test discovery and automated test execution directly inside the unified CLI toolchain:

FrontLang — tests/test_math.ft
# tests/test_math.ft

fn test_addition():
    let sum = 10 + 20
    assert(sum == 30, "Addition arithmetic check")

fn test_string_prefix():
    let s = "FrontLang"
    assert(s.starts_with("Front"), "Prefix assertion failed")

fn test_boolean_logic():
    assert(true and not false, "Boolean logic check")

Execute tests across the entire project with automated discovery:

Terminal — Test Execution
frontlang test
# Output:
running 3 tests across project...
test test_addition ... ok
test test_string_prefix ... ok
test test_boolean_logic ... ok

test result: ok. 3 passed; 0 failed; 0 ignored (time: 0.8ms)
30 • Developer Tooling & IDE

Language Server Protocol (frontlang lsp)

FrontLang includes a built-in, zero-dependency Language Server Protocol (LSP) server conforming strictly to the JSON-RPC 2.0 standard over stdio. It brings immediate code intelligence to VS Code, Neovim, Helix, Sublime Text, and any LSP-compatible editor:

Live Diagnostics

On-the-fly syntax validation and static type checking with 1-indexed line and column ranges pointing directly at compiler diagnostics.

Hover & Definitions

Hover over identifiers to view full type signatures, docstrings, and struct field definitions, with instant jump-to-definition across modules.

Smart Auto-Complete

Context-aware keyword, function name, struct field, and standard library module suggestions with automatic parameter snippet insertion.

Terminal — Starting LSP Server
# Launch Language Server Protocol over standard I/O (JSON-RPC 2.0)
frontlang lsp
31 • Technical Specification

Bytecode & Virtual Machine Specification (.ftbc)

FrontLang bytecode binaries (.ftbc) use a compact, deterministic, big-endian binary serialization format designed for instant in-memory execution and zero-overhead distribution.

1. Binary File Format (.ftbc)

1.1 Header Structure

Offset Type Field Description Value / Format
0x00 [u8; 4] Magic Bytes Signature b"FTBC" (0x46, 0x54, 0x42, 0x43)
0x04 u16 Bytecode Format Version 1 (Big-Endian integer)
0x06 u16 Reserved Flags 0x0000

1.2 Constant Pool Encoding

Preceded by a u32 count N. Each constant entry is identified by a 1-byte type tag:

Tag Type Payload Encoding
0x00 Int(i64) 8 bytes, two's complement big-endian signed integer
0x01 Float(f64) 8 bytes, IEEE 754 double-precision float big-endian
0x02 String u32 byte count length L, followed by L raw UTF-8 bytes
0x03 Bool 1 byte: 0x01 for true, 0x00 for false
0x04 Unit 0 bytes payload (singleton value)
0x05 FunctionPrototype u32 name index, u16 arity, u32 code length, followed by bytecode payload

1.3 Entrypoint Header

Preceded by a u32 constant pool index pointing to the entrypoint name (e.g. main), or 0xFFFFFFFF if top-level script statements are evaluated directly.

2. Complete FrontVM Opcode Set (38 Opcodes)

FrontVM instructions consist of a 1-byte opcode followed by immediate operands:

Hex Mnemonic Operands Operational Semantics
0x00 OP_HALT None Terminates virtual machine execution cleanly
0x01 OP_CONSTANT u16 (index) Pushes constant from pool onto the evaluation stack
0x02 OP_UNIT None Pushes Unit literal onto the stack
0x03 OP_TRUE None Pushes boolean true onto the stack
0x04 OP_FALSE None Pushes boolean false onto the stack
0x05 OP_POP None Discards top value from the evaluation stack
0x06 OP_DUP None Duplicates top value on the stack
0x07 OP_NULL None Pushes null pointer onto evaluation stack
0x10 OP_GET_LOCAL u16 (slot) Pushes value from current call frame's local slot
0x11 OP_SET_LOCAL u16 (slot) Writes top of stack into local slot without popping
0x12 OP_GET_GLOBAL u16 (name index) Pushes value of global variable
0x13 OP_SET_GLOBAL u16 (name index) Updates existing global variable in environment
0x14 OP_DEFINE_GLOBAL u16 (name index) Defines new global variable with top of stack value
0x20 OP_ADD None Binary addition (Int, Float, or String concatenation)
0x21 OP_SUB None Binary subtraction (Int, Float)
0x22 OP_MUL None Binary multiplication (Int, Float)
0x23 OP_DIV None Binary division (checked for division by zero)
0x24 OP_MOD None Binary modulo (checked for modulo by zero)
0x25 OP_NEG None Unary arithmetic negation (-x)
0x26 OP_NOT None Unary boolean inversion (not b)
0x30 OP_EQ None Binary equality comparison (==)
0x31 OP_NOT_EQ None Binary inequality comparison (!=)
0x32 OP_LT None Binary less-than (<)
0x33 OP_LT_EQ None Binary less-than-or-equal (<=)
0x34 OP_GT None Binary greater-than (>)
0x35 OP_GT_EQ None Binary greater-than-or-equal (>=)
0x40 OP_JUMP u32 (target ip) Unconditional jump to instruction index
0x41 OP_JUMP_IF_FALSE u32 (target ip) Pops boolean and jumps if condition is false
0x42 OP_JUMP_IF_TRUE u32 (target ip) Pops boolean and jumps if condition is true
0x50 OP_CALL u8 (arity) Invokes function with N arguments popped from stack
0x51 OP_CALL_BUILTIN u16 (name idx), u8 (argc) Invokes native VM runtime built-in (e.g. show)
0x52 OP_RETURN None Returns from current call frame, pushing return value to caller
0x60 OP_NEW_STRUCT u16 (name idx), u16 (field count) Constructs new struct instance from stack field values
0x61 OP_GET_FIELD u16 (field name idx) Accesses named member field on struct instance
0x62 OP_SET_FIELD u16 (field name idx) Mutates named member field on struct instance
0x63 OP_NEW_ARRAY u16 (element count) Constructs dynamic array [T] from stack values
0x64 OP_GET_INDEX None Pops index and container, pushes element at index
0x65 OP_SET_INDEX None Pops value, index, and container, mutates element at index
0x66 OP_NEW_MAP u16 (entry count) Constructs key-value Map[K, V] from pairs on stack
0x67 OP_NEW_TUPLE u16 (element count) Constructs heterogeneous positional tuple from stack
0x70 OP_PUSH_TRY u32 (catch handler ip) Registers exception handler frame on exception stack
0x71 OP_POP_TRY None Unregisters the most recent active exception handler frame
0x72 OP_THROW None Throws exception value from stack and unwinds call frames

3. Virtual Machine Architecture (FrontVM)

Value Stack

Dynamically expanding evaluation stack with a configurable depth guard (default: 65,536 values) safeguarding against runtime stack overflow.

Call Stack

Nested activation records tracking caller return instruction pointers and base stack frames for localized variable access.

Exception Stack

Dedicated unwinding table tracking try/catch handlers, ensuring clean recovery and deterministic cleanup during throw.

100% In-Memory Execution Guarantee

When executing via frontlang run, source code is compiled directly into memory structures and executed immediately in FrontVM. No intermediate .c, .ftbc, or .exe files are written to disk, keeping your repository clean.

24 • Developer Environment

Official VS Code Extension

FrontTerrain provides an official VS Code extension delivering first-class editing support for FrontLang:

FrontLang Extension Icon

FrontLang Language Support for VS Code

Full TextMate syntax highlighting for keywords, types, strings, comments, and numbers, coupled with smart 4-space auto-indentation and the official document icon.

Version 1.0.0 Stable Zero Telemetry

Installing the Extension in VS Code

Install directly via the terminal using the code command:

Terminal
code --install-extension frontlang-0.1.0.vsix

Or inside VS Code: press Ctrl+Shift+P (or Cmd+Shift+P on macOS), type Extensions: Install from VSIX..., and select the downloaded file.

33 • Engineering History & Horizons

Milestone Roadmap (v1.0.0 Production)

FrontLang is engineered according to a disciplined milestone architecture. All 14 core milestones are fully implemented, verified by automated test suites, and deployed in the v1.0.0 Stable Production Release:

Milestone Status Delivered Architecture & Capabilities
M1: Foundation Completed Pure Rust standard library implementation, off-side lexer with indentation stack, recursive descent + Pratt parser, AST with spans, AST interpreter, CLI run/check
M2: Core Language Completed Control flow: if, elif, else, while, break, continue, variable reassignment (=), lexical block scopes, output builtin show(...)
M3: Static Type Checker Completed Static type inference & checking: Int, Float, Bool, String, Unit, generic collections [T], Map[K, V], ahead-of-time function registration, mutual recursion, forward calling
M4: Front IR & FrontVM Completed Binary bytecode format (.ftbc) with FTBC magic signature, constant pool encoding, AST-to-bytecode compiler with jump backpatching, stack-based FrontVM runner, CLI build
M5: Developer Tooling Completed Canonical 4-space code formatter (frontlang fmt), interactive REPL shell (frontlang repl), automated test runner (frontlang test), manifest resolution (frontlang.toml)
M6: Native Compilation (AOT) Completed Native Ahead-of-Time C99 compiler backend (frontlang compile), GCC/Clang host invocation, standalone binaries (.exe/ELF), freestanding kernel mode (--freestanding), intermediate C auto-cleanup
M7: Multi-File Modular System Completed Top-level include "file.ft" statement with relative path resolution, in-place recursive AST inclusion, flat scope merging, dependency cycle detection, duplicate inclusion deduplication
M8: Standard Library Modules Completed std:math, std:os, std:sys, std:fs, std:concurrency, std:net, std:hw bare-metal hardware abstraction layer
M9: Composite Records & Collections Completed User-defined struct declarations with constructor instantiation, dynamic arrays [T] with bounds checking, key-value dictionaries Map[K, V], heterogeneous positional tuples (T1, T2)
M10: Exception Handling Completed Stack-unwinding structured error handling across AST interpreter, FrontVM, and native AOT compiler: try: ... catch err: ... and throw <expr>
M11: 2D Graphics, Typography & UI Completed Zero-dependency TrueType (.ttf) vector font loader, quadratic Bézier evaluation, 8-bit subpixel rasterizer, immediate-mode widget kit (std:ui), easing physics engine (std:animation), waveform audio (std:audio)
M12: Package Manager & FrontHub Completed Zero-dependency package management (init, add, install, pack, publish, search, cache), cryptographic SHA-256 verification, SemVer 2.0.0 solver, central registry portal (FrontHub)
M13: Multi-Target Packaging Completed Multi-target compilation (frontlang compile --target <platform>) and packaging (frontlang package --target <web|android|windows|linux>) with Android NDK NativeActivity and WebAssembly HTML5 canvas
M14: Language Server Protocol (LSP) Completed Full standard JSON-RPC 2.0 LSP server (frontlang lsp), official VS Code extension on Visual Studio Marketplace, out-of-the-box F5 / Ctrl+F5 clean in-memory run configuration

Future Horizons (v1.1+)

Wasm-Native JIT Compiler

In-memory native machine code emission for hot FrontVM loops, accelerating numerical workloads and heavy data simulations.

GPU Compute & Shaders

Direct WebGPU / Vulkan compute shader interop for matrix math, tensor operations, and hardware-accelerated 3D graphics.

Automated iOS Bundler

frontlang package --target ios generating turnkey Xcode project bundles with Metal rendering pipelines.

Open Source Craft

Crafted from scratch for clarity, speed, and safety.

FrontLang is open source under the MIT License. Explore the implementation, build custom tools, or contribute to compiler development.

Download VS Code Extension GitHub Repository Explore Other Products →