# NIV-LANG: FULL GUIDE FOR AI ASSISTANTS You are reading the guide of Niv-Lang, a new programming language (command `niv`, compiler `nivc`). It is not in your training data. Read this whole file before writing any code. HARD RULES FOR YOU 1. Write Niv-Lang only with constructs shown below. If a needed feature is not shown, tell the user it is not documented here. Do not invent syntax, functions or library names, and do not fall back to Rust, Python or C++ syntax. 2. A new variable is made only with `let`. Blocks always use `{ }`; indentation means nothing. 3. Logic words are `and`, `or` (not `&&`, `||`). Else-if is `elif`. The default arm of `match` is `err { }`. 4. Text interpolation is `"Hello {name}"`. 5. Give the user a command to run the code, with the full path of the folder, e.g. `cd /path/to/project && niv run`. 6. This guide is written in simple Hinglish (Hindi in English letters). Answer the user in the language they write in. 7. Status: some samples were taken from tests and the spec but each has not yet been run alone. If something fails, show the user the exact error text; Niv-Lang errors are written to be clear. ---------------------------------------------------------------------- # NIV_GUIDE.md - Niv seekhne ki guide (Rust Book jaisi, simple Hinglish) Ye guide SPEC.md, STDLIB.md aur UI ke asli check files (pkg/tests/os/gui/*.niv) se bani hai (28 Nov 2026, Manager). **Dhyan:** is guide ke code ke tukde tests aur SPEC se liye gaye hain, par har tukda abhi alag se chalaya nahi gaya hai. Pakka karne ka kaam S46 me hai. Jahan `(UI, Mac par chalta hai)` likha hai wahan window chahiye. Poore niyam: SPEC.md. Library ki list: STDLIB.md. UI ke shabd: UI_WORDS.md. --- ## 1. Pehla program ``` fn double(x) -> x * 2 let name = "Karan" print("Hello {name}", double(21)) ``` - File ke upar ki "khuli" lines upar se neeche chalti hain. Function kahin bhi likho. - `print` kai cheezein comma se leta hai. Text ke andar `{name}` me variable ya koi expression. - Chalane ke liye: `niv run` (package folder me) ya `nivc run file.niv`. - Comment: `# ...`, `// ...`, `/* ... */`. - Block hamesha `{ }` se banta hai. Indent (spaces) ka koi matlab nahi. ## 2. Variable ``` let x = 5 # naya variable sirf let se x = 6 # badalna (har let variable badal sakta hai) x += 1 let a, b = 1, 2 # do variable let (lo, hi) = (1, 9) # tuple kholna let karan mehta = 26.0 # naam me space chalta hai (= karan_mehta) const PI = 3.14159 # sirf file ke upar, kabhi nahi badalta ``` - Bina `let` ke `x = 6` sirf pehle se bane x ko badalta hai. x bana hi nahi to error: `'x' is not made yet - a new variable is made with let`. - `let x = 5` ke baad `let x = "six"` = naya x (shadowing, Rust jaisa). - `var` / `val` / `mut` jaise shabd nahi hain. ## 3. Types (kinds) | Likho | Matlab | |---|---| | `Int` | poora number (i64) | | `Float` | dashamlav wala | | `String` | text, `"..."` | | `Bool` | `true` / `false` | | `Char` | ek akshar, `'a'` | | `u8 i16 i32 u64 i128 ...` | alag size ke number | | `List of Int` | `[1, 2, 3]` | | `Map of String to Int` | `{"a": 1}` | | `Set of Int`, `Deque of Int`, `Heap of Int` | `set([1,2])`, `deque([..])`, `heap([..])` | | `Option of Int` | `some(5)` ya `none` | | `Result of Int` | `ok(5)` ya `fail("kaaran")` | | `(Int, String)` | tuple `(1, "a")` | ``` let age: u8 = 30 let names: List of String = [] # khaali list ka kind likhna zaroori let stock: Map of String to Int = {} ``` - `7 / 2` = 3 (Int/Int Int hi rehta hai). `7.0 / 2` = 3.5. Int + Float = Float. - Int ka overflow chupke nahi ghumta, program ruk jata hai. ## 4. Type badalna (S44, 28 Nov) Chhote, ek jaise shabd: `float` `int` `uint` `string`. Teen roop, teeno ka matlab ek: | Kya banana hai | method | call | as | |---|---|---|---| | Float | `x.float()` | `float(x)` | `x as float` | | Int | `x.int()` | `int(x)` | `x as Int` | | unsigned (u64) | `x.uint()` | `uint(x)` | `x as uint` | | text | `x.string()` | `string(x)` | `x as String` | ``` let n = "42".int() # 42 let f = "2.5".float() # 2.5 let t = 7.string() # "7" let k = 65 as Char # 'A' print("ans: " + string(n + 1)) # String + Int mana hai, string() lagao ``` - Text number nahi hai (`"abc".float()`): program ruk jata hai: `abc is not a number (line N)`. Chupke 0 kabhi nahi. - `"1.5".int()` mana (decimal hai), `"1e3".float()` chalta hai. Float -> Int dashamlav kaat deta hai (`3.9` -> 3). - Galat text par rukne ki jagah jawab chahiye: `"zz".parse_int().otherwise(-1)`. - `as` ke baad bracket nahi: `"7" as float(7)` galat, `"7" as float` sahi. - Purane naam: `text(x)`, `parse_int`, `parse_float`, `u8(x)` waise hi chalte hain. ## 5. Function ``` fn double(x) -> x * 2 # ek line fn area(w, h) { return w * h } # block fn circle(r: Float) -> Float { 3.14 * r * r } fn twice(x) { x + x } # bina kind ke: Int, Float, String sab par ``` - Block ki aakhri cheez ki value wapas aati hai, `return` zaroori nahi. - Function ke andar function nahi; sirf file ke upar. - **`&` = jo badalna ho**: `fn inc(&n: Int, by: Int) { n += by }`, bulana `inc(&count, 3)`. `&` ke bina value ki copy jati hai. - `x.function()` = `function(x)`: `"hi".shout()` agar tune `fn shout(t: String)` likha ho. ## 6. if, loop, match ``` if marks >= 90 { print("A") } elif marks >= 60 { print("B") } else { print("C") } let bigger = if a > b { a } else { b } ``` - Condition Bool hona chahiye. `and` `or` `not` words hain. `==` barabar, `!=` nahi. | Loop | Matlab | |---|---| | `while cond { }` | jab tak | | `forever { }` | `break` se nikalo | | `repeat 3 { }` | 3 baar | | `for i in 0..5 { }` | 0 se 4 | | `for n in 1..=5 { }` | 1 se 5 | | `for x in list { }` | har item | | `for i, x in list { }` | index aur item | | `for k, v in map { }` | key aur value | ``` match shape { Circle(r) if r > 5.0 { print("big") } Circle(r) { print("small") } Empty { print("nothing") } } match marks { 90..100 { "A" } 80..89 { "B" } err { "C" } } ``` - Match ka baaki-sab case `err { }`, sabse aakhir me (`else` match me nahi). - Range `90..100` me dono aakhir shamil. ## 7. Option aur Result (galti ka sahi tareeka) ``` let a = "42".parse_int().otherwise(0) # galat text par 0 match find_user(7) { some u { print(u.name) } none { print("nahi mila") } } fn half(a: Int) -> Result of Int { let q = safe_div(a, 2)? # fail ho to function wahin se fail laut jata hai ok(q + 1) } ``` - `.is_some() .is_none() .is_ok() .is_fail() .message() .unwrap()`. - `panic("kaaran")` program rokta hai (exit code 101). `assert cond, "msg"`. ## 8. struct, enum, trait ``` struct Point { x: Int, y: Int } struct Cat { lives: Int is 9 fn speak() { print("meow {lives}") } # fields bina self. ke } let p = Point(3, 4) p.x += 1 Cat().speak() enum Shape { Circle(r: Float) Rect(w: Float, h: Float) Empty } let s = Circle(2.0) trait Named { fn name() -> String } fn greet(x: Named) { print("hi {x.name()}") } # jis struct me name() ho wahi Named hai ``` - Struct ke andar dusra function bulana ho to `self.dusra()`. - Apne `+ - * ==` ke liye struct me naam ke functions: `plus minus times divide equals less text`. - `struct Box of T { items: List of T }` generics: `Box of Int()`. ## 9. Closure (chhote function) ``` let double = x => x * 2 let add = (a, b) => a + b print(nums.map(double), nums.filter(x => x > 1), nums.fold(0, (acc, x) => acc + x)) ``` - List ke methods: `map filter any all find position each fold sort_by`. ## 10. List, Map, Text ke kaam (bina import) | Cheez | Kaam | |---|---| | List | `add pop remove(i) clear contains is_empty join sort sorted unique reversed take skip chunks zip enumerate min max sum count index_of first last len` | | Text | `upper lower trim split replace starts_with ends_with contains find count repeat reverse first last slice parse_int parse_float` | | Set | `add remove has union both minus is_subset` | | Map | `get has remove keys values len` | | Math | `abs min max sqrt pow floor ceil round` | - Rust se alag: list me daalna `.add(x)` hai (`.push` nahi), text jodna `s += "ab"`, text ke andar dekhna `s.contains("an")`, list me dekhna `nums.contains(3)`, map me `m.has(k)`. ## 11. Text ka formatting `{x:...}` ``` print("{pi:.2}") # 3.14 (point ke baad 2 digit) print("{x:~.9}") # aakhir ke zero hata do: 0.3, 12 print("{n:05}") # 00042 print("{n:b} {n:x}") # binary, hex print("{name:>10}") # right align ``` ## 12. Import aur libraries ``` import { files, json, time } let t = files.read("a.txt").otherwise("") ``` - 20 libraries: `files path time random math args env stdin process json hash base64 regex url http net threads db compress encrypt`. Import optional hai, par likhna saaf rakhta hai. - Files ke kaam Result dete hain: `files.read/write/append/lines/list/delete/...`. - Keyboard se: `ask_int("Age: ")`, `ask_float`, `ask_char`, `ask_bool`, `ask("naam: ")`. ## 13. Threads ``` import { threads } let t = threads.spawn(work, "bob", 7) print(t.wait()) # Result let all = threads.parallel(list, func) let total = threads.shared(0) total.add(1) ``` ## 14. Warnings aur error - Warning (program chalta rehta hai): `variable x is never used` (naam `_x` karo), `function x is never used`, `this line can never run`, `x is imported but never used`. - `niv fmt` code sajata hai. `niv test` me `test "naam" { assert ... }`. - Package: `pack.kind` me `name = "Cal"`, `version = "1.0.0"`; chalne wali file `src/main.niv`. --- ## 15. UI: window, Panel, Button (Mac par chalta hai) Sabse chhota app: ``` window { title "Hello" size 400 300 } nivui { let clicks = 0 Panel(center).show { Layout(top to bottom, center x, top 40, gap 10).show { Text("Clicked {clicks} times") let b = Button(size (140, 36), color "0A84FF", radius 10, text(Text("Dabao"), color "FFFFFF", size 13, bold high)) if b.clicked { clicks += 1 } } } } ``` - `window { }` window ka setup: `title`, `size w h`, `min size`, `max size`, `!titlebar`, `drag`, `blur`, `theme`. - `nivui { }` me widgets. `let` ka variable har frame par nahi mitta, state rehta hai. - `Panel(left, fixed size 340)`, `Panel(center)`; andar `.show { ... }`. Panel ke andar `Layout(top to bottom, top 12, left 12, gap 10).show { }`. - Widgets: `Button`, `Text`, `Rect`, `Circle`, `Ellipse`, `Line`, `Triangle`, `Star`, `Image`, `TextBox`, `Scroll`, `List`, `Tree`, `Table`, `Grid`, `Terminal`, `Split`, `Tabs`, `Toolbar`, `Alert`. - Har widget par `.clicked .right_clicked .double_clicked .pressed .released .dragged .hovered`: `let r = Rect(size (120, 40), color "FF0000"); if r.clicked { ... }`. - Rang `"RRGGBB"` hex; `color invert`; `opacity 0..100`; `radius 10`; `stroke 1.2`; `stroke color "..."`; `blur 80`; `hover(pop 1.4 px, color invert, opacity 40)`; `clicked(push 2 px)`. - Default rang (Light / Dark): text 121213 / FFFFFF. Panel aur button ka fill FFFFFF / 121213. - **S39 (abhi ban raha hai, Manager ka faisla):** `stroke color default` bhi text ke default jaisa hoga (Light me 121213, Dark me FFFFFF), taaki ring hamesha dikhe. Abhi Light me safed dikhta hai. - **S40 (abhi ban raha hai):** 0.1 / 0.2 px ki patli stroke Figma jaisi saaf; `stroke inside | center | outside`. ### TextBox ``` let name = "" let t = TextBox(&name, hint "Aapka naam", width 300, frame(true)) if t.changed { print("{name}") } if t.entered { print("Enter dabaya") } let code = "fn main() {}" TextBox(&code, lines fill, line numbers, mono, syntax niv, find bar, frame(true), width 700) TextBox(&secret, password, eye) ``` ### Keyboard ``` Key(Cmd and Shift and F).pressed { print("Cmd+Shift+F") } Key(Num5).pressed { } # upar wali row ka 5 Key(Shift and Num5).pressed { } # % wali key Key(Space).held { } ``` - Events: `.pressed .released .held`. Modifier: `Cmd Shift Alt Ctrl` (exact match). - Key ke naam: `A..Z Num0..Num9 Pad0..Pad9 F1..F20 Up Down Left Right Space Enter Tab Escape Backspace Delete ...`. - Text jo type hua: `typed_text()`. ### List (bahut saari rows) ``` let names: List of String = [] for i in 0..3000 { names.add("File " + string(i)) } Panel(left, fixed size 340).show { List("files", row height 28, selection many, reorder, rename, menu "Delete" "Copy").show { Section("Today", badge 3) for i in 0..len(names) { let r = Row(names[i], icon "dot.svg", extra string(i * 4) + " KB") if r.double_clicked { print("open " + names[i]) } } } } ``` - List, Tree, Table, Grid poora panel bharte hain; aur widget alag panel me rakho. - Tree: `Tree("t").show { Fold("src").show { Row("main.niv") } }`. Table: `Table("t", column "Naam", column "Size").show { Row(a, b) }`. ### Mac ke special shabd (S se shuru: sirf Mac) `SButton`, `SMenuItem("File/Save", shortcut "Cmd+S")`, `SOpenPanel`, `SSavePanel`, `SShare`, `Toast("text")`, `SNotify`, `Document`. Inke Mac-only hone ka matlab: Windows/Linux par ye shabd nahi chalenge, baaki (bina S ke) shabd chalenge. --- ## 16. Poora example: Calculator ki logic (S44 ke shabdon ke saath) ``` struct Box => self { digit: String is "0" left: Float is 0.0 op: String is "" fresh: Bool is false fn press(k: String) { if fresh { digit = k } elif digit == "0" { digit = k } else { digit += k } fresh = false } fn choose(o: String) { if op != "" { if !fresh { self.equals() } } left = digit.float() op = o fresh = true } fn equals() { if op != "" { let b = digit.float() if op == "/" { if b == 0.0 { digit = "Error" op = "" fresh = true return } } let r = apply(left, b, op) digit = "{r:~.9}" op = "" fresh = true } } } fn apply(a: Float, b: Float, op: String) -> Float { if op == "+" { return a + b } if op == "-" { return a - b } if op == "*" { return a * b } if op == "/" { return a / b } return b } ``` - Dhyan: `digit = "Error"` ke baad `digit.float()` ruk jata hai (text number nahi hai). Isliye "Error" ke baad AC dabana zaroori, ya `parse_float().otherwise(0.0)` use karo. - UI me: `if Whitebtn(Num7).clicked { self.press("7") }`, `if Orangebtn(Plus).clicked { self.choose("+") }`. --- ## 17. Rust / C++ / Python se kya alag hai | Aap likhoge | Niv me | |---|---| | `v.push(x)` | `v.add(x)` | | `s.push_str("ab")` / `s.push('7')` | `s += "ab"` | | `x.to_string()` | `x.string()` ya `string(x)` ya `text(x)` | | `s.parse::()` | `s.float()` (ruk jata hai) ya `s.parse_float()` (Result) | | `x as f64` | `x as float` | | `let mut x = 5` | `let x = 5` (sab badal sakte hain) | | `self.digit` | `digit` (struct ke andar; `self.` bhi chalta hai) | | `match x { _ => .. }` | `match x { err { .. } }` | | `if x == 3 { } else if` | `if x == 3 { } elif ..` (else if bhi chalta hai) | | `fn main() { }` | zaroori nahi: file ki khuli lines chalti hain | | `a && b`, `a || b` | `a and b`, `a or b` | | `!x` ya `x ^ y` | `not x`; bits ke liye `bit_and bit_or bit_xor shift_left shift_right` | | `&mut x` | `&x` (bulate waqt bhi `&` likho) | | kuch bhi galat | saaf error message, kabhi chupke nahi | ## 18. Aam galtiyan aur matlab - `'x' is not made yet - a new variable is made with let` -> `let` bhool gaye. - `cannot use '+' between String and Int (use text(x) ...)` -> `string(x)` lagao. - `cannot compare String with Int` -> dono ko same kind me badlo. - `an empty list needs its kind written` -> `names: List of String = []`. - `the match must cover every value` -> sab choices likho ya `err { }`. - `'x' holds String but this value is Int` -> variable ka kind badal ke daalna mana hai. - `abc is not a number` -> text ko number banane se pehle check karo ya `.parse_float()` use karo. - `this is a bug of nivc, not of your program` -> nivc ka bug hai, report karo (BOARD S43). --- **Aage:** isme har naya shabd (B10 ke controls, S42 ke warnings, S40 ki stroke align, B23 ke dot-shabd) apne worker ke report ke baad jodna hai. Isse chhoti, tested roop me `NIV_FOR_AI.md` banti hai (BOARD S46).