Metadata-Version: 2.4
Name: samlang
Version: 0.1.0
Summary: SamLang — A modern, high-performance programming language blending Python simplicity with C# elegance.
Author: Samrane Ahmed
License-Expression: LicenseRef-Proprietary
Project-URL: Homepage, https://github.com/samrane-ahmed/samlang
Project-URL: Repository, https://github.com/samrane-ahmed/samlang
Project-URL: Issues, https://github.com/samrane-ahmed/samlang/issues
Keywords: programming-language,interpreter,samlang,compiler,oop
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Compilers
Classifier: Topic :: Software Development :: Interpreters
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# 🚀 SamLang (`.sl`)

A modern, high-performance, general-purpose programming language.
**Author:** Samrane Ahmed

---

## 📁 Project Architecture

```
nova/
├── src/
│   └── samlang/
│       ├── __init__.py        # Package metadata
│       ├── tokens.py          # Token types, Position tracking
│       ├── errors.py          # Error diagnostics with visual arrows (^)
│       ├── ast_nodes.py       # AST Node definitions (Number, BinOp, Assign, etc.)
│       ├── lexer.py           # Lexical analyzer / Tokenizer
│       ├── parser.py          # Recursive descent parser (BODMAS/Precedence)
│       ├── environment.py     # Scopes and symbol table bindings
│       ├── interpreter.py     # AST Tree-Walk evaluator
│       ├── runner.py          # Execution pipeline
│       └── cli.py             # CLI runner and interactive REPL
├── examples/
│   └── hello.sl               # Example SamLang script
├── tests/
│   └── test_samlang.py        # Automated test suite
└── main.py                    # Root CLI entry point
```

---

## ⚡ Quick Start

### 1. Run a SamLang Script (`.sl`)
```bash
py main.py examples/hello.sl
```

### 2. Launch the Interactive REPL
```bash
py main.py
```
```text
==================================================
  SamLang 0.1.0 Interactive REPL
  Created by Samrane Ahmed
  Type 'exit' or 'quit' to exit.
==================================================
samlang> x = 4;
samlang> y = 10;
samlang> println "Sum is:", x + y;
Sum is: 14
samlang> echo "Testing: "; println "Done!"
Testing: Done!
```

### 3. Run Tests
```bash
py tests/test_samlang.py
```

---

## 🎯 Language Features

### Phase 1: Foundation & Arithmetic
- [x] **Dynamic Variable Declaration:** Direct assignment `x = 4;` (no mandatory `let` required)
- [x] **Semicolons Support:** Semicolon `;` support for clean statement termination & multiple statements on one line
- [x] **Output Statements:**
  - `println expr1, expr2...` (prints with newline)
  - `print expr1, expr2...` (prints inline without newline)
  - `echo expr1, expr2...` (alias to `print`, inline output)
- [x] **Numbers & Types:** Integers (`10`, `-5`), Floats (`3.14`), Strings with escapes
- [x] **Arithmetic:** `+`, `-`, `*`, `/`, `%`, `^` (power) with mathematical precedence
- [x] **Parentheses:** For grouping expressions `(a + b) * c`
- [x] **Comments:** Single-line comments starting with `#`
- [x] **Precision Diagnostics:** Line & column tracking with visual pointer arrows (`^`)

### Phase 2: Environment, Types & Scoping
- [x] **Booleans & Null:** `true`, `false`, and `null` literals
- [x] **Comparison Operators:** `==`, `!=`, `<`, `>`, `<=`, `>=`
- [x] **Logical Operators:** `and`, `or`, `not` as well as C-style `&&`, `||`, `!`
- [x] **Lexical Scoping & Code Blocks:** `{ ... }` blocks with local scope isolation and outer variable mutability

### Phase 3: Functions, Dual Blocks & Control Flow
- [x] **Functions (`func`):** Definition with `func name(a, b) ...`, parameter binding, call stack
- [x] **Return Statement (`return`):** Early returns, returning values or null
- [x] **Dual Block Styles:**
  - **C/JS Style:** Using braces `{ statement1; statement2; }`
  - **Python Style:** Using colon and indentation `: \n statement1 \n statement2`
- [x] **Conditional Branches:** `if`, `elif`, `else` (supports both brace and colon syntax)
- [x] **Loops (`while`):** While loops (supports both brace and colon syntax)
- [x] **Recursion:** Full recursive calls and closures supported

### Phase 4: Advanced Loops & Unique Superpowers
- [x] **C-Style For Loop:** `for (init; cond; step) { ... }` with optional components (`for (;;)`)
- [x] **Python-Style For Loop:** `for i in range(stop)` and `for i in range(start, stop, step)`
- [x] **Do-While Loop:** `do { ... } while (cond);` (executes at least once)
- [x] **Real Constants (`const`):** Immutable constants with strict runtime reassign prevention
- [x] **Increment & Decrement (`++` / `--`):** Prefix and postfix increment/decrement (`x++`, `++x`, `x--`, `--x`)
- [x] **Compound Assignments:** `+=`, `-=`, `*=`, `/=`, `%=` (numbers and string operations)
- [x] **Repeat Loop:** `repeat count { ... }` or `repeat count: ...` for clean, simple repetitions

### Phase 5: Data Structures, String Interpolation & Built-ins
- [x] **Arrays / Lists:** `[1, 2, "three"]`, indexing `arr[0]`, negative indexing `arr[-1]`, mutation `arr[0] = 99;`
- [x] **Array Looping:**
  - Parcours par élément: `for x in list { ... }`
  - Parcours par index et élément: `for i, x in list { ... }`
  - Parcours par index pur: `for i in range(len(list)) { ... }`
- [x] **Dictionaries / HashMaps:** `{ name: "Ahmed", age: 22 }`, dot access `d.name`, bracket access `d["age"]`
- [x] **Dictionary Iteration:** `for key, val in dict { ... }`
- [x] **Ternary Operator:** `condition ? val1 : val2` (supports chaining)
- [x] **Direct String Interpolation:** `"Salam ${name}, next year: ${year + 1}!"` with nested expressions
- [x] **String Built-in Functions & Methods:**
  - `clean(s)` / `s.clean()` (strip / trim)
  - `upper(s)` / `s.upper()`
  - `lower(s)` / `s.lower()`
  - `mirror(s)` / `s.mirror()` (reverse)
  - `begin(s, prefix)` / `s.begin(prefix)` (startswith)
  - `end(s, suffix)` / `s.end(suffix)` (endswith)
  - `find(s, sub)` / `s.find(sub)`
  - `clip(s, start, end)` / `clp` / `s.clip(...)` (slice / substring)
  - `divide(s, sep)` / `s.divide(sep)` (split)
  - `merge(arr, sep)` / `arr.merge(sep)` / `sep.merge(arr)` (join)
  - `swap(s, old, new)` / `s.swap(old, new)` (replace)
- [x] **SQL-Style Array Built-in Functions & Methods:**
  - `order(arr)` / `arr.order()` (ORDER BY ASC)
  - `order_desc(arr)` / `arr.order_desc()` (ORDER BY DESC)
  - `distinct(arr)` / `arr.distinct()` (DISTINCT)
  - `limit(arr, n)` / `arr.limit(n)` (LIMIT)
  - `offset(arr, n)` / `arr.offset(n)` (OFFSET)
  - `count(arr)` / `arr.count()` (COUNT(*))
  - `sum(arr)` / `arr.sum()` (SUM)
  - `avg(arr)` / `arr.avg()` (AVG)
  - `min(arr)` / `max(arr)` (MIN / MAX)
  - `union(arr1, arr2)` (UNION)
  - `exists(arr, val)` / `arr.exists(val)` (EXISTS)
  - `insert(arr, item, idx)` / `arr.insert(...)` (INSERT)
  - `delete(arr, val)` / `arr.delete(val)` (DELETE)

### Phase 6: Modules & Import System (Ready for `spm`)
- [x] **File Module Imports:**
  - Namespace import: `import "./utils.sl";` -> `utils.func()`
  - Alias import: `import "./utils.sl" as u;` -> `u.func()`
  - Named items: `import { add, sub } from "./math.sl";`
  - Renamed items: `import { add as plus } from "./math.sl";`
  - Wildcard import: `import * from "./utils.sl";`
  - Python-style import: `from "./utils.sl" import add, sub;`
- [x] **Standard Library Modules:**
  - `import math;` (`pi`, `sqrt`, `floor`, `ceil`, `sin`, `cos`, `random`, `randint`, etc.)
  - `import json;` (`stringify`, `parse`)
  - `import time;` (`now`, `date`, `sleep`, `clock`)
  - `import os;` (`cwd`, `exists`, `is_file`, `is_dir`, `read_file`, `write_file`, `env`)
- [x] **Modular Architecture:**
  - Package lookup in `spm_modules/` (prepared for SamLang Package Manager `spm`)
  - Cyclic import protection & module caching
  - Private symbol convention (`_private` ignored in wildcard imports)

### Phase 7: Advanced Syntax & Modern Functional Superpowers
- [x] **Loop Controls (`break` & `continue`):** Works in `while`, `for (;;) `, `for-in`, `repeat`.
- [x] **Exception Handling (`try / catch / finally`):**
  - Safe error trapping: `try { ... } catch (err) { ... } finally { ... }`
  - Dual syntax support (braces `{}` and colons `:`)
  - Rich error object `err.message`, `err.details`, `err.type`.
- [x] **Arrow Functions / Lambdas (`=>`):**
  - Multi-arg: `(x, y) => x + y`
  - Single-arg shorthand: `x => x * 2`
  - Block body: `(x) => { return x + 1; }`
- [x] **Functional Array Methods:**
  - `arr.map(fn)`: Map transformation over elements
  - `arr.filter(fn)`: Filter elements matching predicate
  - `arr.reduce(fn, initial)`: Fold/reduce elements to single value
  - `arr.for_each(fn)`: Execute action per element

### Phase 8: Object-Oriented Programming (POO / OOP)
- [x] **Classes (`class`):** Full class declarations supporting both `{}` and `:` blocks.
- [x] **C#-Style Auto-Properties:**
  - Read/Write: `let Name { get; set; }`
  - Default values: `let Age { get; set; } = 18`
  - Read-only: `let Id { get; } = "XYZ"` (reassignment raises runtime error)
- [x] **Constructors:**
  - C# style constructors named after the class `Person(name, age) { ... }` or `func init(...)`.
  - Chaining / parent constructor delegation via `base(...)`.
- [x] **Inheritance (`:`):** Single class inheritance: `class Student : Person`.
- [x] **Explicit Polymorphism:**
  - Parent methods marked `func virtuel display()`
  - Child methods marked `func override display()`
  - Enforced runtime safety: derived classes cannot override non-virtual methods, preventing accidental method hiding.
- [x] **Parent Delegation (`base`):** `base(...)` for constructor delegation and `base.method()` for parent methods.
- [x] **Self-Reference:** Both `this` (C# style) and `self` (Python style) are fully supported.
- [x] **Flexible Instantiation Styles:**
  - Untyped dynamic assignment: `s = new Student("Ahmed", 22)`
  - Standard declaration: `let s = new Student("Ahmed", 22)`
  - Polymorphic typed declaration: `Person s = new Student("Ahmed", 22)` (verifies subclass relationship at runtime)
  - Exact typed declaration: `Student s = new Student("Ahmed", 22)`
  - Instantiation without `new`: `Student("Ahmed", 22)`
- [x] **Static Methods (`static`):** `static func add(a, b)` called directly on the class (`MathHelper.add(a, b)`).

---

## 🌐 Universal IDE Support & SamLang LSP (`samlang-lsp`)

SamLang implements the standard **Language Server Protocol (LSP 3.17)**, giving any modern editor first-class IDE capabilities:

| Feature | Description |
| :--- | :--- |
| **Live Diagnostics (Red Squiggles)** | Instant syntax error reporting as you type with precise line & column markers. |
| **Smart Autocomplete** | Keywords, built-in functions, array methods (`.map`, `.filter`), stdlib modules (`math.`, `os.`), and user symbols. |
| **Hover Tooltips** | Full signatures, markdown documentation, and parameter details when hovering code. |
| **Go to Definition (`F12`)** | Jump directly to where functions or variables are declared. |
| **Document Outline / Symbols** | Breadcrumbs and outline hierarchy showing all functions and variables. |

---

### 1. VS Code & Antigravity IDE
Run the automated installer:
```bash
py install_extension.py
```
Then reload window (`Ctrl + Shift + P` -> `Developer: Reload Window`). The extension automatically starts the LSP server!

---

### 2. Neovim (nvim-lspconfig)
Add to your `init.lua`:
```lua
local lspconfig = require('lspconfig')
local configs = require('lspconfig.configs')

if not configs.samlang then
  configs.samlang = {
    default_config = {
      cmd = { "samlang", "--lsp" }, -- or {"py", "-3", "-m", "samlang.lsp"}
      filetypes = { "samlang" },
      root_dir = lspconfig.util.root_pattern(".git", "."),
      settings = {},
    },
  }
end
lspconfig.samlang.setup{}
```

---

### 3. Sublime Text (LSP Package)
In Sublime Text, open `Preferences > Package Settings > LSP > Settings` and add:
```json
{
  "clients": {
    "samlang": {
      "enabled": true,
      "command": ["samlang", "--lsp"],
      "selector": "source.samlang"
    }
  }
}
```

---

### 4. Helix / Zed Editor
In Helix (`languages.toml`):
```toml
[[language]]
name = "samlang"
scope = "source.samlang"
file-types = ["sl"]
roots = [".git"]
language-servers = [ "samlang-lsp" ]

[language-server.samlang-lsp]
command = "samlang"
args = ["--lsp"]
```


