Linea LogoLinea

Linea Language Guide

Comprehensive guide to Linea programming language syntax, types, and features.

1. Getting Started

Installation

git clone https://github.com/gauthamnair2005/Linea.git
cd Linea
./install.sh

Hello World

// hello.ln
func main() -> any {
    display "Hello, Linea!"
    return 0
}

Compile and Run

linea compile hello.ln -o hello
./hello

Linea automatically detects available system threads and compiles using matching parallel build jobs for faster native builds.

2. Variables and Types

Variable Declaration (v4.0 Syntax)

// New: type annotation syntax (v4.0+)
var x @ int = 42
var name @ str = "Linea"
var value @ float = 3.14
var flag @ bool = True

// Collections
var scores @ [int] = [85, 90, 95]
var temps @ [float] = [72.5, 75.3]

// Type inference still works
var implicit = 100          // Inferred as int
var explicit @ int = 100    // Explicit

Type Alias Reference

Linea Type Rust Type Usage
int int var x @ int = 42
float float var pi @ float = 3.14
str String var s @ str = "hello"
bool bool var b @ bool = True
[T] Vec<T> var arr @ [int]
v4.0 Update: Linea now uses the @ operator for cleaner type annotations. Use @ syntax consistently in modern Linea code examples.

3. Functions

Basic Functions

// Function with return value
func add(a: int, b: int) -> int {
    var result @ int = a + b
    result
}

// Function without return
func greet(name: string) -> any {
    display "Hello, " + name + "!"
    return 0
}

// Main entry point
func main() -> any {
    var sum @ int = add(10, 20)
    greet("Linea")
    return sum
}

Generic Functions (Preview)

func first(arr: [int]) -> int {
    return arr[0]
}

// Usage
first([1, 2, 3])     // 1

Native User Input (Built-in)

var name @ str = input("Enter your name: ")
display "Hello, " + name

3.1 Lambdas, Macros, and Model Formats (v4.6.0)

Lambda Expressions

var add = |a, b| => a + b
display add(10, 32)

Rust-Style Macros

macro_rules! square(x) => x * x
display square!(12)

Model Format APIs

import ml

var ok = ml::saveGGUF("examples/demo.gguf", "mini-metadata")
display ok
display ml::loadGGUF("examples/demo.gguf")
display ml::loadONNX("model.onnx")
display ml::loadPTH("model.pth")
display ml::loadMLX("model.mlx")

3.2 GUI Toolkit (Compiled Runtime) (v4.14.3)

Native Windows

import gui

var ok = gui::window("Linea GUI", "Hello from GUI", 640, 420)
display ok

Window with Button

import gui

var ok = gui::buttonWindow(
  "Linea GUI Toolkit",
  "Hello from Linea compiled GUI!",
  "Click me",
  640,
  420
)
display ok

Compiled runtime backend order: zenity > kdialog > xmessage. If no display or backend exists, GUI calls return false with explicit diagnostics.

3.3 Security + Systems Expansion (v4.8.0)

Hashing & Security

import hash
import security

display hash::sha256("linea")
display security::randomToken(24)
var stored = security::passwordHash("Linea#2026Secure")
display security::passwordVerify("Linea#2026Secure", stored)

DB + File I/O + Low-Level

import db
import fileio
import lowlevel

var h = db::open("demo.db")
db::execute(h, "CREATE TABLE IF NOT EXISTS logs(id INTEGER PRIMARY KEY, msg TEXT)", [])
display db::query(h, "SELECT id, msg FROM logs", [])
db::close(h)

fileio::writeText("demo.txt", "hello")
display fileio::sizeBytes("demo.txt")
display lowlevel::toBytesLE(1337)

3.4 Git + Fun + UUID Libraries (v4.9.0)

Git Actions

import git

display git::isRepo(".")
display git::currentBranch(".")
display git::status(".")
display git::log(".", 5)

Fun + UUID Helpers

import fun
import uuid

display fun::coinFlip()
display fun::rollDice(20)
display fun::randomEmoji()
display uuid::v4()
display uuid::short()

3.5 Web + Framework + Blockchain + GPU + Memory (v4.10.0)

Web + Framework

import framework

framework::newProject("myapp")
framework::addRoute("myapp", "/", "Hello from Linea")
framework::runDevServer("myapp", "127.0.0.1", 8080, 1)

Blockchain + GPU + Memory

import blockchain
import gpu_tools
import memory

display blockchain::merkleRoot(["a", "b", "c"])
display gpu_tools::bestAdapter()
var h = memory::alloc(16)
memory::writeU8(h, 0, 255)
display memory::readU8(h, 0)
memory::free(h)

3.6 Easy OOPS with class + obj (v4.11.0)

Class, Constructor, Object

class Person {
    var name @ str = "unknown"
    var age @ int = 0

    func Constructor(name: string, age: int) -> any {
        this.name = name
        this.age = age
        return this
    }

    func describe() -> string {
        return "Person(" + this.name + ", age=" + this.age + ")"
    }
}

obj p @ Person = Constructor("Ada", 42)
display p.describe()

this, super, and assignment

func birthday() -> int {
    this.age = this.age + 1
    return this.age
}

func superDescribe() -> string {
    return "super view => " + super.describe()
}
OOPS Type Rules:
  • var can only be used with built-in datatypes/collections.
  • obj can only be used with classes.
  • var x @ ClassName = ... produces a type error.
  • obj x @ int = ... produces a type error.

3.7 Media + CV + Camera Libraries

Video + Audio

import video
import audio

display video::info("sample.mp4")
display video::durationMs("sample.mp4")
display video::probe("sample.mp4")
video::extractAudio("sample.mp4", "sample.aac")

audio::generateTone("tone.wav", 440, 2, 44100)
display audio::durationMs("tone.wav")
display audio::sampleRate("tone.wav")
display audio::waveform("tone.wav", 16)

Image + OpenCV-like + Camera

import image
import opencv
import camera

camera::snapshot(0, "snap.ppm")
display image::dimensions("snap.ppm")
image::convertToGray("snap.ppm", "snap_gray.ppm")
image::resizeNearest("snap_gray.ppm", "snap_small.ppm", 128, 96)

opencv::cannyMock("snap.ppm", "edges.ppm", 80)
opencv::blurBox("snap.ppm", "blur.ppm", 3)
display opencv::detectFacesMock("snap.ppm")
display camera::listDevices()

3.8 Control Flow Upgrades + DSA

Switch / Case / Default

var day @ int = 3
switch day {
  case 1:
    display "Mon"
  case 3:
    display "Wed"
  default:
    display "Other"
}

Ternary + One-Line Conditionals

var score @ int = 82
var grade @ str = score >= 50 ? "pass" : "fail"
var parity @ str = if score % 2 == 0 { "even" } else { "odd" }

if score > 90 display "Top tier" else display "Keep going"

DSA Library

import dsa

var nums @ [int] = [5, 1, 9, 3, 7]
display dsa::array_sum(nums)
display dsa::array_max(nums)
display dsa::linear_search(nums, 9)
display dsa::bubble_sort(nums)

3.9 Compute Priority for ML (v4.14.3)

Compute-backed ML and tensor operations now use a strict adapter priority:

GPU > iGPU > CPU

This policy applies in both interpreted and compiled Linea execution paths, with automatic CPU fallback when GPU compute is unavailable.

import compute
display compute::device()
display compute::type()

4. Control Flow

If/Else

var x @ int = 10
if x > 5 {
    display "x is greater than 5"
} else if x == 5 {
    display "x equals 5"
} else {
    display "x is less than 5"
}

Loops (v4.1 Syntax)

// For loop with range operator ~
for i from 1~10 {
    display i
}

// For loop with step
for i from 0~20 step 2 {
    display i
}

// Reverse iteration
for i from 10~1 step -1 {
    display i
}

// While loop
var count @ int = 0
while count < 5 {
    display count
    var count = count + 1
}

Pointers (v4.1 New)

Ptr Datatype (Simplified Pointer Syntax)

// Using ptr datatype - simplified syntax
var x @ int = 42
var ptr_to_x @ ptr = x      // Automatically captures address

var y @ int = 100
var ptr_to_y @ ptr = y      // Multiple pointers are safe

// ptr type stores memory addresses as 64-bit integers
display "Pointers created successfully"

Pointer Handles with `ptr`

// Pointer handles using ptr type
var x @ int = 42
var ptr @ ptr = x

var arr @ [int] = [1, 2, 3, 4, 5]
var arr_ptr @ ptr = arr[0]
display "Pointer handles created"

Pattern Matching

var value @ int = 42
var result @ str = match value {
    0 => "zero",
    1 | 2 | 3 => "one to three",
    42 => "the answer",
    _ => "something else"
}

5. Collections

Vectors (Dynamic Arrays)

// Create vector
var v @ Vector = [1, 2, 3, 4, 5]

// Access elements
var first @ int = v[0]
var last @ int = v[len(v) - 1]

// Modify
v.push(6)
v[0] = 10

Matrices (2D Arrays)

// Create matrix
var m @ Matrix = [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]

// Access element
var val @ float = m[0][1]  // 2.0

// Slicing
var row @ Vector = m[0, :]     // first row
var col @ Vector = m[:, 1]     // second column
var region @ Matrix = m[0:2, 1:3]   // submatrix

Tensors (N-Dimensional)

// Create 3D tensor
var t @ Tensor = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

// Access
var val @ int = t[0][1][0]  // 3

// Shape
var shape @ Vector = t.shape()  // [2, 2, 2]

6. Module System

Importing Modules

// Import module
import ml
import datasets
import http
import system
import greeter

// Use functions
var data = datasets::load_csv("data.csv")
var model = ml::Sequential([...])
var response = http::get("https://api.example.com")
var pwd = system::cwd()
greeter::hello("Linea")

Using Local Project Modules

// Keep reusable modules in libs/
import greeter

Available Modules

Module Purpose
arl Adaptive Reasoning Layer
ml Machine learning (layers, optimizers, losses)
compute GPU tensor operations
datasets Data loading and preprocessing
csv CSV file I/O
excel Excel file handling
http HTTP client
graphics Data visualization
sql SQLite queries with secure locking support
password Masked password prompts and secure hashing helpers
system System operations: files, env vars, process exec, timing, and thread metadata

System Programming Example

import system

system::mkdir("tmp_build")
system::writeText("tmp_build/log.txt", "build started\n")
var status = system::exec("echo", ["ok"])
display status[1]
system::removeDir("tmp_build")

7. Advanced Features

GPU Acceleration

// Mark function for accelerated execution
func matrix_multiply(a: any, b: any) -> any {
    return compute::matmul(a, b)
}

Inference Mode (No Gradients)

// Inference mode
func predict(model: any, input: any) -> any {
    var predictions = model.forward(input)
    return predictions
}

Async Functions (Preview)

func fetch_data(url: string) -> string {
    var response = http::get(url)
    return response
}

// Usage
// data = await fetch_data("https://...")

8. Example: Neural Network Training

import ml
import datasets

func main() -> any {
    // Load data
    data = datasets::load_csv("iris.csv")
    X_train = data::features
    y_train = data::labels
    
    // Create model
    model = ml::Sequential([
        ml::Dense(4, 16),
        ml::ReLU(),
        ml::Dense(16, 8),
        ml::ReLU(),
        ml::Dense(8, 3)
    ])
    
    // Training loop
    optimizer = ml::Adam(0.001)
    for epoch from 0~100 {
        loss = model.train_step(X_train, y_train, optimizer)
        
        if epoch % 10 == 0 {
            display "Epoch " + epoch + ": loss = " + loss
        }
    }
    
    // Inference
    predictions = model.forward(X_test)
    return predictions
}

Next Steps