clarity-lang 0.4.0
Clarity — A simple yet powerful programming language
Requires Python: >=3.8
Keywords: programming-language, interpreter, clarity, language, scripting

# Clarity

**Simple code. Real power.**

Clarity is a modern programming language that combines the readability of Python with the expressiveness of functional languages. It features immutable-by-default variables, a pipe operator, pattern matching, classes, async/await, and a full bytecode compiler — all in a clean, minimal syntax.

```
-- Hello World in Clarity
let name = "World"
show "Hello {name}!"

-- Pipes make data flow visible
let result = [1, 2, 3, 4, 5]
    |> filter(x => x % 2 == 0)
    |> map(x => x * x)
show result  -- [4, 16]
```

## Install

```bash
pip install clarity-lang
```

Or install from source:

```bash
git clone https://github.com/monkdim/Clarity.git
cd Clarity
pip install -e .
```

After install, the `clarity` command is available globally:

```bash
clarity run hello.clarity    # Run a program
clarity repl                 # Interactive REPL
clarity check file.clarity   # Syntax check
clarity compile file.clarity # Show bytecode disassembly
```

## Quick Start

Create a file called `hello.clarity`:

```
let name = "Clarity"
show "Hello from {name}!"

let nums = [1, 2, 3, 4, 5]
let squares = nums |> map(x => x * x)
show "Squares: {squares}"

fn greet(person) {
    show "Hey {person}, welcome!"
}
greet("Developer")
```

Run it:

```bash
clarity run hello.clarity
```

## Language Features

### Variables

```
let x = 42          -- immutable (default)
mut counter = 0     -- mutable (opt-in)
counter += 1

-- Type annotations (runtime checked)
let name: string = "Alice"
let age: int = 30
```

### Functions

```
fn add(a, b) {
    return a + b
}

-- Lambda shorthand
let double = x => x * 2
let multiply = (a, b) => a * b

-- Rest parameters
fn first(head, ...tail) {
    return head
}

-- Type-annotated functions
fn divide(a: float, b: float) -> float {
    return a / b
}
```

### Pipes

The pipe operator `|>` passes the result as the first argument to the next function:

```
let result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    |> filter(x => x % 2 == 0)
    |> map(x => x * x)
    |> reduce((a, b) => a + b, 0)
show result  -- 220
```

### Control Flow

```
if age >= 18 {
    show "adult"
} elif age >= 13 {
    show "teen"
} else {
    show "child"
}

-- If expressions (ternary)
let label = if age >= 18 { "adult" } else { "minor" }

-- For loops
for item in [1, 2, 3] {
    show item
}
for i in 0..10 {
    show i
}

-- While loops
mut n = 10
while n > 0 {
    n -= 1
}
```

### Pattern Matching

```
fn describe(value) {
    match value {
        when 0 { show "zero" }
        when 1 { show "one" }
        when "hello" { show "greeting" }
        else { show "something else: {value}" }
    }
}
```

### Classes & Inheritance

```
class Animal {
    fn init(name, sound) {
        this.name = name
        this.sound = sound
    }
    fn speak() {
        show "{this.name} says {this.sound}!"
    }
}

class Dog < Animal {
    fn init(name) {
        this.name = name
        this.sound = "woof"
    }
    fn fetch(item) {
        show "{this.name} fetches the {item}"
    }
}

let dog = Dog("Rex")
dog.speak()       -- Rex says woof!
dog.fetch("ball") -- Rex fetches the ball
```

### Interfaces

```
interface Drawable {
    fn draw()
    fn area() -> float
}

class Circle impl Drawable {
    fn init(r) { this.r = r }
    fn draw() { show "Drawing circle r={this.r}" }
    fn area() { return 3.14159 * this.r * this.r }
}
```

### Enums

```
enum Color { Red, Green, Blue }
show Color.Red     -- 0
show Color.names() -- ["Red", "Green", "Blue"]

enum Status {
    OK = 200
    NotFound = 404
    Error = 500
}
```

### Destructuring & Spread

```
let [first, second, ...rest] = [1, 2, 3, 4, 5]
let {name, age} = {name: "Alice", age: 30}

let merged = [...list1, ...list2]
let combined = {...map1, ...map2}
```

### Async/Await

```
async fn fetch_data() {
    return 42
}

let result = await fetch_data()
show result
```

### Generators

```
fn fibonacci() {
    mut a = 0
    mut b = 1
    for i in 0..10 {
        yield a
        a, b = b, a + b
    }
}

let fibs = fibonacci()
show fibs  -- [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
```

### Comprehensions

```
-- List comprehension
let squares = [x * x for x in 0..10 if x > 3]

-- Map comprehension
let lengths = {name: len(name) for name in ["alice", "bob", "charlie"]}
```

### Error Handling

```
try {
    let result = risky_operation()
} catch e {
    show "Error: {e}"
} finally {
    show "Cleanup done"
}

throw "something went wrong"
```

### Decorators

```
fn log(wrapped) {
    return fn(...args) {
        show "calling function"
        let result = wrapped(...args)
        show "done"
        return result
    }
}

@log
fn add(a, b) {
    return a + b
}
```

### Raw Strings

```
let path = r"C:\Users\test\new"    -- no escape processing
let regex = r"^\d{3}-\d{4}$"      -- no escape processing
```

### Modules

```
import math
show math.sqrt(16)

from math import sqrt, pi
show sqrt(2)

import "utils.clarity"              -- file import
from "helpers" import process_data  -- named import
```

**Built-in modules:** math, json, os, path, random, time, crypto, regex

### Null Safety

```
let value = maybe_null ?? "default"   -- null coalescing
let name = user?.profile?.name        -- optional chaining
```

## Built-in Functions

| Function | Description |
|----------|-------------|
| `show` | Print values |
| `len(x)` | Length of string, list, or map |
| `type(x)` | Get type name |
| `str(x)`, `int(x)`, `float(x)`, `bool(x)` | Type conversion |
| `range(n)`, `range(start, end)` | Number sequences |
| `map(list, fn)`, `filter(list, fn)`, `reduce(list, fn, init)` | Collection transforms |
| `sort(list)`, `reverse(list)`, `unique(list)`, `flat(list)` | List operations |
| `push(list, item)`, `pop(list)` | List mutation |
| `keys(map)`, `values(map)`, `entries(map)` | Map access |
| `join(list, sep)`, `split(str, sep)` | String operations |
| `upper(s)`, `lower(s)`, `trim(s)`, `replace(s, a, b)` | String transforms |
| `abs(n)`, `round(n)`, `floor(n)`, `ceil(n)`, `sqrt(n)` | Math |
| `min(list)`, `max(list)`, `sum(list)` | Aggregation |
| `read(path)`, `write(path, data)` | File I/O |

## Tools

### REPL

```bash
clarity repl
```

Features: command history (up/down arrows), tab completion, multi-line input, dot-commands:

```
clarity> .help     -- show help
clarity> .clear    -- clear screen
clarity> .reset    -- reset interpreter state
clarity> .env      -- show defined variables
```

### Bytecode Compiler

Clarity includes a stack-based bytecode compiler and VM:

```bash
clarity compile program.clarity
```

Shows disassembled bytecode with 48 opcodes.

### Package Manager

```bash
clarity init                         # Create clarity.toml
clarity install                      # Install dependencies
clarity install mylib --path ./libs  # Add local dependency
```

### Language Server (LSP)

For editor integration (VS Code, etc.):

```bash
clarity lsp
```

Provides real-time diagnostics, hover info, and code completion via JSON-RPC 2.0.

### Syntax Checking

```bash
clarity check program.clarity   # Validate without running
clarity tokens program.clarity  # Show lexer output
clarity ast program.clarity     # Show parse tree
```

## Project Structure

```
clarity/
  __init__.py       # Version info
  tokens.py         # Token types and keywords
  lexer.py          # Tokenizer (source -> tokens)
  parser.py         # Recursive descent parser (tokens -> AST)
  ast_nodes.py      # AST node definitions
  interpreter.py    # Tree-walking interpreter
  runtime.py        # 60+ built-in functions and 8 modules
  bytecode.py       # Bytecode compiler + stack VM
  package.py        # Package manager (clarity.toml)
  lsp.py            # Language server protocol
  cli.py            # Command-line interface
  errors.py         # Error types
```

## Running Tests

```bash
python tests/test_lexer.py
python tests/test_parser.py
python tests/test_interpreter.py
python tests/test_v2_features.py
python tests/test_v3_features.py
python tests/test_v4_features.py
```

164 tests across 6 test files.

## License

GPL-3.0 — see [LICENSE](LICENSE) for details.