# Autolang Language Skill — AI Reference

You are writing code in **Autolang**, a statically-typed, Kotlin/TypeScript-inspired scripting language with a lightweight VM. File extension: `.atl`. Code executes top-to-bottom at file scope. No semicolons needed.

---

## 1. Variables

```
val x = 10          // immutable (cannot reassign)
var y = 20          // mutable (can reassign)
val name: String = "John"   // explicit type
var age: Int = 25

// Nullable types
var child: Int?              // default null
val email? = "a@b.com"       // inferred nullable
val id! = 42                 // inferred non-null

// IMPORTANT: variables are references by default
var a = 5
var b = a       // b points to same object as a
b += 1          // a is also changed!
var c = +a      // use unary + to COPY a numeric value
```

### Primitive Types
| Type   | Description |
|--------|-------------|
| Int    | 64-bit integer. Char literals ('a') also resolve to Int. |
| Float  | 64-bit floating point |
| Bool   | true / false |
| String | Immutable character sequence |
| Any    | Accepts any type |

---

## 2. String Interpolation

```
val name = "World"
println("Hello $name")
println("Result: ${1 + 2}")
println("Name length: ${name.size()}")
```

Use `$variable` for simple references, `${expression}` for expressions.

---

## 3. Operators

```
// Arithmetic: +  -  *  /  %
// Comparison: ==  !=  >  <  >=  <=
// Logical: &&  ||  !  (also: and, or, not)
// Assignment: +=  -=  *=  /=
// Identity (pointer): ===  !==
// Null: ?.  ??  !.
// Type check: is
// Type cast: as  as?
```

### Type Casting

**Compile-time cast** — Use `Int()` and `Float()` as conversion functions. These are resolved at compile time.

```
val f = 3.14
val i = Int(f)       // 3 (truncates decimal)

val n = 42
val d = Float(n)     // 42.0
```

**Runtime cast** — Use `as` to cast an object to a specific type at runtime.
- `as` — throws an error if the cast fails
- `as?` — returns `null` if the cast fails (safe cast)

```
class Animal(val name: String)
class Cat extends Animal {
    constructor() { super("Cat") }
    func meow() { println("Meow!") }
}

val a: Animal = Cat()

val c = a as Cat       // OK, a is actually a Cat
c.meow()

val d = a as? Cat      // Safe: returns Cat? (null if fails)

val x: Animal = Animal("Dog")
val e = x as? Cat      // returns null (x is not a Cat)
// val f = x as Cat    // ERROR: cast fails at runtime
```

> **NOTE**: Smart cast is NOT supported yet. After an `is` check, you still need to explicitly cast with `as`.

---

## 4. Control Flow

### if / else (can be used as expression)
```
val result = if (x > 0) "positive" else "non-positive"

val value = if (condition) {
    println("branch a")
    42    // last expression is return value
} else {
    0
}
```

### when (replaces switch, no fall-through)
```
// Match a value
val name = when (dayIndex) {
    1 -> "Monday"
    2 -> "Tuesday"
    else -> "Other"
}

// Boolean conditions (no argument)
val grade = when {
    score >= 90 -> "A"
    score >= 80 -> "B"
    else -> "F"
}
```

### Loops
```
for (item in collection) { ... }
while (condition) { ... }
```

---

## 5. Functions

```
func greet(name: String) {
    println("Hello $name")
}

// With return type
func add(a: Int, b: Int): Int {
    return a + b
}

// Single-expression shorthand
func multiply(a: Int, b: Int): Int = a * b

// Default parameters
func connect(host: String = "localhost", port: Int = 8080): String {
    return "$host:$port"
}

// Function types & callbacks (higher-order functions)
func calculate(a: Int, b: Int, op: (Int, Int) -> Int): Int {
    return op(a, b)
}
func myAdd(x: Int, y: Int): Int = x + y
println(calculate(3, 4, myAdd))  // 7
```

---

## 6. Closures (Anonymous Functions)

**MANDATORY**: Always include `||` parameter delimiters.

```
// No params
val sayHi = {|| println("Hi") }
sayHi()

// With params (single expression)
val square = {|x: Int| x * x }
println(square(5))  // 25

// Block body with ->
val check = {|n: Int| -> {
    if (n % 2 == 0) println("Even")
    else println("Odd")
}}

// Used with Array methods
val nums = <Int>[1, 2, 3, 4, 5]
nums.forEach {|v| println(v) }
val evens = nums.filter {|v| v % 2 == 0 }
```

---

## 7. Classes & Inheritance

### Primary Constructor (RECOMMENDED — faster native init)
```
class Person(val name: String, var age: Int) {
    func greet() {
        println("I'm $name, age $age")
    }
}
val p = Person("Alice", 30)
```

### Secondary Constructor (required with extends)
```
class Animal(val name: String) {
    func sound() { }
}

class Cat extends Animal {
    constructor() {
        super("Cat")    // super() MUST be first statement
    }

    @override
    func sound() {
        println("Meow")
    }
}
```

### Access Modifiers
- `public` (default) — accessible everywhere
- `private` — same class only
- `protected` — class + subclasses

### Static Members
```
class Config {
    static val VERSION = 1
}
println(Config.VERSION)
```

### lateinit
```
class Engine {
    lateinit var config: String
    func init() { config = "loaded" }
}
```

### Index Operator Overloading
```
class Grid {
    func get(index: Int): Int { ... }
    func set(index: Int, value: Int) { ... }
}
val g = Grid()
val v = g[0]      // calls g.get(0)
g[0] = 42         // calls g.set(0, 42)
```

### Type Checking
```
val x = Cat()
println(x is Cat)     // true
println(x is Animal)  // true
```

### @no_override
```
class Base {
    @no_override
    func coreLogic() { ... }  // subclasses cannot override
}
```

---

## 8. Null Safety

```
var x: String? = null

// Safe call
x?.size()          // returns null if x is null

// Null coalescing
val len = x?.size() ?? 0

// Non-null assertion (crashes if null)
x!.size()

// Chaining
a?.child?.name?.size()
```

---

## 9. Enums

```
enum Color {
    RED, GREEN, BLUE;

    func label(): String = when (this) {
        RED -> "Red"
        GREEN -> "Green"
        BLUE -> "Blue"
        else -> "Unknown"
    }
}

val c = Color.RED
println(c.label())
println(c == Color.RED)  // true
```

---

## 10. Generics

```
// Generic function (must specify type explicitly when calling)
func identity<T>(item: T): T = item
println(identity<Int>(42))

// Generic class with type bounds
class Box<T extends Animal>(var value: T) {
    func getSound(): String = value.sound()
}

// LIMITATION: generic methods inside classes are NOT supported yet
```

### Static Members in Generic Classes
Each monomorphized (specialized) version of a generic class gets its **own independent copy** of static members. They are NOT shared across different type arguments.

```
class Counter<T> {
    static var count = 0
}

Counter<Int>.count = 5
Counter<Float>.count = 10

println(Counter<Int>.count)    // 5  (NOT 10)
println(Counter<Float>.count)  // 10
// Counter<Int> and Counter<Float> are distinct classes at runtime
```

### Type Inference for Generic Parameters
When there is enough context, you can **omit the `<>` type parameter**. The compiler will infer the type from the surrounding context (variable type annotation, function parameter type, etc.).

```
// Explicit — always works
val a = <Int>[1, 2, 3]

// Inferred from variable type annotation
val b: Array<Int> = [1, 2, 3]     // compiler knows it's Array<Int>
val c: Array<Int> = []             // empty array, type inferred from annotation

// Inferred from function parameter type
func process(data: Array<Int>) { ... }
process([1, 2, 3])                 // [] is inferred as Array<Int>
process([])                        // empty Array<Int>

// Same applies to Map
val m: Map<String, Int> = {"a": 1}
```

---

## 11. Exceptions

```
try {
    throw Exception("error message")
} catch (e) {
    println(e.message)
}

// Custom exceptions
class MyError extends Exception {
    constructor(msg: String) { super(msg) }
}

// Type-check in catch (no typed catch allowed)
try { throw MyError("oops") }
catch (e) {
    if (e is MyError) { println("MyError: ${e.message}") }
    else { throw e }  // rethrow
}
```

---

## 12. Array<T>

```
// Creation
val nums = <Int>[1, 2, 3]
val empty = Array<String>()

// Access & modify
nums[0]              // get
nums[1] = 99         // set
nums.add(4)          // append
nums.insert(0, 0)    // insert at index
nums.remove(0)       // remove at index
nums.pop()           // remove & return last

// Iteration
for (n in nums) { ... }
nums.forEach {|v| println(v) }

// Functional
val filtered = nums.filter {|v| v > 2 }
nums.sort {|a, b| -> {
    return when {
        a > b -> 1
        a == b -> 0
        else -> -1
    }
}}

// 2D arrays
val matrix = <Array<Int>>[[1,2],[3,4]]

// Methods: add, insert, remove, pop, clear, get, set,
//   size, isEmpty, contains, indexOf, forEach, filter,
//   sort, slice, reserve, toString
```

---

## 13. Map<K, V>

```
// Creation
val m = <String, Int>{"Apple": 10, "Banana": 20}
val empty = Map<String, Int>()

// Access
m["Apple"]             // get (returns V?)
m["Apple"] = 15        // set
m.remove("Apple")
m.containsKey("Banana")
m.getOrDefault("Cherry", 0)

// Iteration
m.forEach {|key, value| println("$key: $value") }

// Views
val keys = m.keys()       // Array<K>
val values = m.values()   // Array<V>

// Methods: set, remove, clear, get, getOrDefault,
//   containsKey, size, isEmpty, forEach, keys, values, toString
```

---

## 14. Set<T>

```
// Creation
val s = <Int>{1, 2, 3, 4, 5}
val empty = Set<String>()

// Duplicates are ignored automatically
val unique = <Int>{1, 2, 2, 3, 3}  // size = 3

// Add & remove
s.add(6)
s.add(1)               // ignored, already exists
s.remove(3)
s.clear()

// Membership check
s.contains(2)          // Bool
"Apple" in fruits      // alternative syntax (same as contains)

// Set operations (return new Set)
val a = <Int>{1, 2, 3}
val b = <Int>{2, 3, 4}
a.union(b)             // {1, 2, 3, 4}
a.intersect(b)         // {2, 3}
a.difference(b)        // {1}

// Iteration
s.forEach {|value| println(value) }

// Convert to Array
val arr = s.toArray()  // Array<T>

// Methods: add, remove, clear, contains, size, isEmpty,
//   union, intersect, difference, forEach, toArray, toString
```

---

## 15. String Methods

```
val s = "Hello World"

// Query
s.size()                  // 11
s.isEmpty()               // false
s.get(0)                  // "H" (returns String)
s.charAt(0)               // 72 (returns Int/ASCII)
s.contains("World")       // true
s.indexOf("World")        // 6  (-1 if not found)

// Manipulation (returns NEW string)
s.substr(6)               // "World"
s.substr(0, 5)            // "Hello"
s.trim()
s.replace("World", "Autolang")
s.split(" ")              // Array<String>

// Conversion
"42".toInt()              // 42
"3.14".toFloat()          // 3.14

// Constructors
String()                  // ""
String("Ha", 3)           // "HaHaHa"
```

---

## 16. Annotations

Annotations provide metadata for classes, functions, and members. They start with `@`.

### @override
Marks a function as overriding a base class method. Compile error if no matching base method.

```
class Cat extends Animal {
    constructor() { super() }

    @override
    func sound() { println("Meow") }
}
```

### @no_override
Prevents subclasses from overriding a method (makes it "final").

```
class Base {
    @no_override
    func coreLogic() { println("Cannot be changed") }
}
```

### @native
Marks a function as implemented in external native code (C/C++, JS). No body needed.

```
class Math {
    @native("std_math_pow")
    func pow(base: Float, exp: Float): Float
}
```

### @no_extends
Seals a class — prevents any class from inheriting it.

```
@no_extends
class CoreSystem {
    func boot() { println("Booting...") }
}
```

### @no_constructor
Prevents the compiler from generating a default constructor. Class cannot be instantiated.
Often combined with `@no_extends` to create utility classes with only static members.

```
@no_extends
@no_constructor
class Utils {
    static func log(msg: String) { println(msg) }
}
Utils.log("Hello")
// Utils() → ERROR: no constructor
```

### @import
Imports a module/standard library. Must be at the top level of the file.

```
@import("std/math")
@import("std/date")
```

---

## 17. Constructor Optimization

### Primary vs Secondary Performance
- **Primary Constructor** triggers a **single native bulk-copy** — the VM fills the entire object in one pass (O(1)).
- **Secondary Constructor** executes multiple `SET_FIELD` instructions sequentially — slower.

**ALWAYS prefer Primary Constructors** for performance.

### Pseudo-constructors (Static Factory Pattern)
A `static func ClassName()` inside a class acts as a constructor when you call `ClassName()`.
Use this to combine complex logic with fast primary constructor storage.

```
class Player(val id: Int, val health: Float, val name: String) {
    // Pseudo-constructor: complex logic + fast primary storage
    static func Player(name: String): Player {
        val generatedId = 0
        val defaultHealth = 100.0
        return Player(generatedId, defaultHealth, name)  // calls primary
    }
}

val p = Player("Alice")       // calls static pseudo-constructor
println(p.name)               // "Alice"
```

### Factory Methods via Primary Constructor
```
class Vector(val x: Float, val y: Float) {
    static func Zero() = Vector(0.0, 0.0)
    static func Unit() = Vector(1.0, 1.0)
}
val v = Vector.Zero()
```

### __CLASS__ Magic for Generics
For native generic classes, use `__CLASS__` as a function name — the compiler replaces it with the class name at compile time. Combined with `getClassId()` for type-safe native interop.

```
@no_extends
@no_constructor
class Map<K, V> {
    // __CLASS__ becomes "Map" at compile time
    @native("map_constructor")
    static func __CLASS__(classId: Int = getClassId(Map<K, V>), keyId: Int = getClassId(K))
}
val myMap = Map<String, Int>()   // calls the native pseudo-constructor
```

---

## 18. Standard Library Modules

### Import syntax
```
@import("std/math")
@import("std/date")
```

### std/math
```
Math.PI, Math.E
Math.abs(-5), Math.min(a, b), Math.max(a, b)
Math.round(3.6), Math.floor(3.8), Math.ceil(3.1), Math.trunc(3.9)
Math.pow(2, 10), Math.sqrt(16), Math.exp(1.0), Math.log(2.0)
Math.sin(x), Math.cos(x), Math.tan(x)    // radians
Math.random()                              // 0.0..1.0
Math.random(1, 6)                          // Int in range
Math.random(0.0, 1.0)                     // Float in range
Math.fmod(num1, num2)
```

---

## 19. Built-in Functions

**IMPORTANT**: `print()` and `println()` are the **only way** the program produces output. Whatever is printed is the data sent back to the host application or user. When a task asks you to "return" or "output" a result, you MUST use `println()` to send it.
 
```
print("no newline")
println("with newline")
```

---

## 20. Magic Constants

```
__FILE__    // current filename (String)
__LINE__    // current line number (Int)
```

---

## 21. Comments

```
// single line comment
/* multi-line
   comment */
```

---

## Quick Examples

### Fibonacci
```
func fib(n: Int): Int {
    if (n <= 1) return n
    return fib(n - 1) + fib(n - 2)
}
println(fib(10))
```

### FizzBuzz
```
for (i in <Int>[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) {
    val result = when {
        i % 15 == 0 -> "FizzBuzz"
        i % 3 == 0 -> "Fizz"
        i % 5 == 0 -> "Buzz"
        else -> "" + i
    }
    println(result)
}
```

### Class Hierarchy
```
class Shape {
    func area(): Float = 0.0
}

class Circle extends Shape {
    var radius: Float?
    constructor(r: Float) {
        super()
        this.radius = r
    }
    @override
    func area(): Float = 3.14159 * radius! * radius!
}

val c = Circle(5.0)
println("Area: ${c.area()}")
```

### Map + Filter Pipeline
```
val scores = <String, Int>{"Alice": 92, "Bob": 45, "Charlie": 78}
scores.forEach {|name, score| -> {
    val status = if (score >= 50) "PASS" else "FAIL"
    println("$name: $score ($status)")
}}
```
