[System] You are a coding assistant for the Ling programming language.

[User] How do I declare a variable in ling-lang?

[Assistant]
Use `bind` to create a name-to-value binding:

```ling
bind x = 42
bind name = "Ling"
bind flag = true
```

There's no separate `let`/`var`/`const` — `bind` is the one binding form. Re-using `bind` on the same name in the same scope shadows the previous binding rather than mutating it:

```ling
bind i = 0
bind i = i + 1   # i is now 1, a new binding
```


[System] You are a coding assistant for the Ling programming language.

[User] What's the entry point of a ling-lang program supposed to look like?

[Assistant]
Every Ling program's entry point is a binding named `start` set to a `do` block:

```ling
bind start = do {
    bind x = 10
    bind y = 20
    print(x + y)
}
```

`do { ... }` evaluates each statement in order and the whole block evaluates to the value of its last expression — that's what gets assigned to `start`.


[System] You are a coding assistant for the Ling programming language.

[User] Explain what a `do` block is in Ling.

[Assistant]
`do { ... }` is a block *expression* — it runs its statements in order and evaluates to the value of the last one, so you can bind it directly:

```ling
bind result = do {
    bind a = 3
    bind b = 4
    a * b
}
# result == 12
```

The canonical use is the program entry point, `bind start = do { ... }`, but `do` blocks can appear anywhere an expression is expected, including as the arms of an `if`.


[System] You are a coding assistant for the Ling programming language.

[User] How does Ling write functions? Show me the basic form.

[Assistant]
With the `fn` keyword, a parameter list, and a `{ }` body whose last expression is the return value:

```ling
fn add(a, b) {
    a + b
}
```

You can also `return` explicitly:

```ling
fn add(a, b) {
    return a + b
}
```

Functions are values, so you can bind an anonymous one to a name:

```ling
bind square = fn (n) { n * n }
bind result = square(7)   # 49
```


[System] You are a coding assistant for the Ling programming language.

[User] Does Ling support typed function signatures?

[Assistant]
Yes — parameters can carry `: Type` annotations and the return type follows `->`:

```ling
fn fib_iter(n: number) -> number {
    bind a = 0
    bind b = 1
    bind i = 0
    while i < n {
        bind t = a + b
        bind a = b
        bind b = t
        bind i = i + 1
    }
    a
}
```

Types are optional — untyped `fn add(a, b) { a + b }` is just as valid — but annotating is common in performance-sensitive code and is required for `own`-style ownership parameters.


[System] You are a coding assistant for the Ling programming language.

[User] What does an `if`/`else` look like in ling-lang, and can I use it as an expression?

[Assistant]
Ordinary branch syntax, no parentheses required around the condition:

```ling
if x > 0 {
    print("positive")
} else {
    print("non-positive")
}
```

`if` is also an expression — the last line of whichever branch runs becomes the value, so it's idiomatic to write things like:

```ling
bind greeting = if hour < 12 {
    "Good morning"
} else {
    "Good evening"
}
```

This pattern (assigning the result of an `if`) shows up constantly in real Ling code.


[System] You are a coding assistant for the Ling programming language.

[User] How do while loops work in Ling?

[Assistant]
`while <condition> { ... }`, re-binding the loop variable each iteration since Ling has no in-place mutation operator like `i++`:

```ling
bind i = 0
while i < 10 {
    print(i)
    bind i = i + 1
}
```

This is the standard idiom seen throughout real Ling code — e.g. walking a query result:

```ling
bind rows = database_query("SELECT id, name FROM users")
bind i = 0
while i < rows.len {
    bind row = list_get(rows, i)
    print(row.name)
    bind i = i + 1
}
```


[System] You are a coding assistant for the Ling programming language.

[User] What's the syntax for a for loop over a range in ling-lang?

[Assistant]
`for <var> in <start>..<end> { ... }`. The range is exclusive of the end value:

```ling
for i in 0..10 {
    print(i)
}
```

This is exactly how the game-AI example trains a neural net for 2000 epochs:

```ling
for epoch in 0..2000 {
    nn_train(net, [0, 0], [0], 0.5)
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Can Ling's `for` loop iterate over something other than a numeric range?

[Assistant]
Yes — `for x in <list>` iterates elements directly, not just `a..b` ranges. From a real controller in production Ling code:

```ling
bind messages = ["Hello", "World", "from", "Ling"]
for msg in messages {
    print(msg)
}
```


[System] You are a coding assistant for the Ling programming language.

[User] What is `form` used for in Ling?

[Assistant]
`form` declares a record/struct type — a name plus a list of field names:

```ling
form Point { x, y }
```

You construct one by calling the form name like a function, and read fields with `.`:

```ling
bind start = do {
    bind p = Point(3, 4)
    print(p.x)   # 3
    print(p.y)   # 4
}
```

This is exactly the pattern used for HTTP response shapes in production Ling sites, e.g. `form Response { status, body, content_type, set_cookie, location }` in ling-lin.me's app.ling, constructed as `Response(status, body, content_type, "", "")`.


[System] You are a coding assistant for the Ling programming language.

[User] How do enums / tagged variants work in Ling — what's the `choose` keyword for?

[Assistant]
`choose` declares a set of named variants (like a Rust `enum`), and `match` destructures them. From a real animation state machine in the Ling examples:

```ling
choose AnimState { Idle, Walk, Run, Sit, Meditate, Swim }

fn state_name(state) {
    return match state {
        Idle()     => "IDLE",
        Walk()     => "WALK",
        Run()      => "RUN",
        Sit()      => "SIT",
        Meditate() => "MEDITATE",
        Swim()     => "SWIM",
        _          => "IDLE",
    }
}
```

Variants can also carry data, e.g. `choose Shape { Circle(r), Rect(w, h), Dot }`, matched as `Circle(r) => ...`. The `_` arm is the catch-all/default case.


[System] You are a coding assistant for the Ling programming language.

[User] What does the `use` keyword do in a .ling file?

[Assistant]
`use "path"` imports another Ling module/file by path (relative, no extension), bringing its top-level bindings and functions into scope. From ling-lin.me's app.ling:

```ling
use "controllers/home"
```

and a module can import several others, as fu.ling-lang.org's app.ling does:

```ling
use "models/schema"
use "models/users"
use "controllers/home"
use "controllers/auth"
```


[System] You are a coding assistant for the Ling programming language.

[User] What is `mod` for, and how do I call something inside one?

[Assistant]
`mod` groups related functions into a namespace, accessed with `::`:

```ling
mod timer {
    fn current_hour() {
        return 14
    }
}

bind start = do {
    bind hour = timer::current_hour()
    print(hour)
}
```

This mirrors the real `complex_hello.ling` example, which defines `mod safe_greet { fn try_print(msg) { ... } }` and calls it as `safe_greet::try_print("hi")`.


[System] You are a coding assistant for the Ling programming language.

[User] How do comments work in Ling — is it `#` or `//`?

[Assistant]
Both are valid comment markers in real Ling source. `#` line comments are used throughout the language reference docs and some examples (e.g. `examples/anim/animations/animation_map.ling`), while `//` line comments are the convention in most production `.ling` files (e.g. `ling-lin.me/app.ling`, `fu.ling-lang.org`'s controllers). Either works:

```ling
# this is a comment
bind x = 1   # inline comment

// this also works
bind y = 2   // inline too
```


[System] You are a coding assistant for the Ling programming language.

[User] What's this about Ling not having a unary minus operator?

[Assistant]
Correct — Ling has no prefix `-` operator. You can't write `-x`; instead subtract from zero:

```ling
bind negated = 0 - x
```

This is called out explicitly in the language's own syntax reference as a gotcha, since most languages let you write `-x` directly.


[System] You are a coding assistant for the Ling programming language.

[User] What operators does Ling support?

[Assistant]
Standard arithmetic and comparison operators, all spelled the same across every language lexicon:

- Arithmetic: `+ - * / %`
- Comparison: `== != < <= > >=`
- Logical: `&& || !`
- `=` binds/assigns in a `bind` statement
- `->` marks a function's return type: `fn f(n: number) -> number { ... }`
- `.` does field/method access: `p.x`, `s.len`, `row.contains("/")`
- `|>` is the pipe operator
- `::` accesses a name inside a `mod`, e.g. `timer::current_hour()`

Note there is no unary minus — write `0 - x`, not `-x`.


[System] You are a coding assistant for the Ling programming language.

[User] How do I write a list literal and index into it in Ling?

[Assistant]
Square brackets, comma-separated, and `[i]` to index (zero-based):

```ling
bind nums = [1, 2, 3]
bind first = nums[0]   # 1
```

Bracket indexing is also used for element assignment inside a loop, as in the vector-doubling example from `examples/basics/advanced.ling`:

```ling
bind result = [0, 0, 0, 0, 0]
for i in 0..5 {
    result[i] = data[i] * 2
}
```

For building lists up incrementally (rather than literal `[...]`), use the functional `list_new()` / `list_push(list, value)` / `list_get(list, i)` builtins instead.


[System] You are a coding assistant for the Ling programming language.

[User] What literal values does Ling recognize out of the box?

[Assistant]
- Booleans: `true` / `false`
- Result markers: `ok` / `bad`
- Absent value: `none`
- Numbers: `123`, `1.5`, `-7` (numeric literals may have a leading `-`, even though the `-` operator itself isn't unary-usable on a variable)
- Text: `"hello"`
- Lists: `[1, 2, 3]`
- Ranges: `0..10`, used with `for`

These spellings are identical no matter which keyword lexicon (English, Chinese, Thai, ...) the rest of the file uses.


[System] You are a coding assistant for the Ling programming language.

[User] What built-in types does Ling have?

[Assistant] Six built-in types: `number` (integer or float, always f64 under the hood for math builtins), `text` (string), `bool`, `list`, `map` (key/value), and `tuple` (fixed-size). Each has native spellings in every supported lexicon — e.g. `number` is `数` in Chinese, `숫자` in Korean, `จำนวน` in Thai.


[System] You are a coding assistant for the Ling programming language.

[User] I keep seeing this in Ling docs — what is the 'multilingual keyword aliasing' feature everyone talks about?

[Assistant] It's Ling's signature feature: essentially every keyword and builtin has native spellings in multiple human languages, and the lexer/parser accept all of them interchangeably — even mixed in the same file. `bind` / `令` (Chinese) / `束縛` (Japanese) / `바인드` (Korean) / `ผูก` (Thai) all mean the same thing, and `print`/`str_len`/`html_escape`-style builtins go further, with aliases documented (and implemented in the interpreter) across Chinese, Japanese, Korean, Thai, Persian, Arabic, Hebrew, Urdu, French, German, and Russian. For example `list_new` also accepts `รายการใหม่` (Thai), `新建列表` (Chinese), `فهرست_جدید` (Persian), `قائمة_جديدة` (Arabic), `רשימה_חדשה` (Hebrew), `نئی_فہرست` (Urdu), `nouvelle_liste` (French), `neue_liste` (German), and `новый_список` (Russian) — all calling the exact same builtin. A CLI tool, `lingfu normalize <lang>`, can even rewrite an entire project's keywords/builtins/filenames into one target language.


[System] You are a coding assistant for the Ling programming language.

[User] Show me the same tiny Ling program in two different keyword languages to prove this multilingual thing is real.

[Assistant]
Here's a minimal program in English and Chinese keywords — both are valid, runnable Ling:

```ling
# English
fn main() {
  bind x = 42
  print("Hello!")
}
```

```ling
# Chinese
函 主函数() {
  令 甲 = 42
  打印("你好！")
}
```

`函`=`fn`, `令`=`bind`, `打印`=`print`. They compile to the identical AST — you can even mix keyword languages within one file, since the interpreter accepts the union of every alias.


[System] You are a coding assistant for the Ling programming language.

[User] What does `p.x` mean when `p` is a `form` value — is `.` a general field-access operator?

[Assistant] Yes. `.` accesses a named field on a `form` (struct) value, e.g. `p.x` for a `form Point { x, y }`, and it also doubles as a lightweight method-call syntax on built-in types — `s.len` reads a string or list's length, and `name.contains("/")` calls the `contains` string builtin as a method. Both spellings (`contains(s, sub)` and `s.contains(sub)`) work; production Ling code uses the `.` form heavily for readability, e.g. `if name.contains("..") { return false }`.


[System] You are a coding assistant for the Ling programming language.

[User] What does `list_new()` do?

[Assistant]
Creates and returns a new, empty list. It's the starting point for building up a list incrementally with `list_push`:

```ling
bind items = list_new()
bind items = list_push(items, "first")
```


[System] You are a coding assistant for the Ling programming language.

[User] Explain `list_push` — does it mutate the list in place?

[Assistant]
No — `list_push(list, value)` returns a *new* list with `value` appended; it does not mutate its argument in place. That means you must rebind the result, or the push is lost:

```ling
bind lst = list_new()
bind lst = list_push(lst, 42)      # correct — lst now has [42]
list_push(lst, 99)                  # WRONG — result discarded, lst still just [42]
```


[System] You are a coding assistant for the Ling programming language.

[User] What does `list_get(lst, i)` do, and is it zero-indexed?

[Assistant]
`list_get(list, index)` returns the element at `index`, zero-indexed:

```ling
bind lst = list_new()
bind lst = list_push(lst, "a")
bind lst = list_push(lst, "b")
bind first = list_get(lst, 0)   # "a"
```


[System] You are a coding assistant for the Ling programming language.

[User] What's the difference between `.len` and `str_len`/`list_len` in Ling?

[Assistant] They return the same thing, just via different syntax. `str_len(s)` (or the shared `len`/`str_len` builtin) returns a string's length in characters, and the same `len` builtin returns a list's length in elements. `.len` is field-access sugar for the identical operation — `row.len` on a list, or `name.len` on a string — which is the form you'll see most in real Ling code, e.g. `if rows.len == 0 { return 0 }` in a database-model function.


[System] You are a coding assistant for the Ling programming language.

[User] What does `substr` do in Ling, and what are its arguments?

[Assistant]
`substr(s, start, len)` returns `len` characters of `s` starting at character index `start` (zero-based, clamped to the string's length if `len` runs past the end). `str_slice` is an exact alias for the same builtin. Example, pulling a function name out of a line of source:

```ling
bind trimmed = "fn add(a, b) {"
bind name = substr(trimmed, 3, 3)   # "add"
```

To grab "everything to the end", pass an oversized length — real Ling code does exactly this: `substr(result, pos + 1, 9999)`.


[System] You are a coding assistant for the Ling programming language.

[User] What does `trim` do?

[Assistant]
`trim(s)` returns `s` with leading and trailing whitespace stripped:

```ling
bind clean = trim("   hello   ")   # "hello"
```


[System] You are a coding assistant for the Ling programming language.

[User] What does `split` do in Ling?

[Assistant]
`split(s, separator)` breaks a string into a list of pieces on every occurrence of `separator` and returns that list. If you omit the separator it defaults to splitting on newlines:

```ling
bind parts = split("a,b,c", ",")   # ["a", "b", "c"]
bind lines = split(source_text)      # split on "\n"
```


[System] You are a coding assistant for the Ling programming language.

[User] What does `str_replace` do?

[Assistant]
`str_replace(s, from, to)` returns a copy of `s` with every occurrence of `from` replaced by `to`:

```ling
bind safe = str_replace("a(b)c", "(", "_")   # "a_b)c"
```

This is used in Ling's own example tooling to sanitize function names for filenames — a chain of `str_replace` calls strips out `( ) { } - .` and spaces one at a time.


[System] You are a coding assistant for the Ling programming language.

[User] What does `starts_with` check, and what does it return?

[Assistant]
`starts_with(s, prefix)` returns a boolean — `true` if `s` begins with `prefix`, `false` otherwise:

```ling
if starts_with(line, "fn ") {
    print("found a function definition")
}
```


[System] You are a coding assistant for the Ling programming language.

[User] What's `ends_with` for?

[Assistant]
`ends_with(s, suffix)` returns `true` if the string ends with `suffix`. Real usage from Ling's own visualization tool, classifying command-line arguments by file extension:

```ling
bind is_ling = ends_with(arg, ".ling")
bind is_svg  = ends_with(arg, ".svg")
```


[System] You are a coding assistant for the Ling programming language.

[User] What does `str_strip_prefix` do, and how is it different from `starts_with`?

[Assistant]
`starts_with(s, prefix)` only tests and returns a bool; `str_strip_prefix(s, prefix)` actually removes `prefix` from the front of `s` and returns the remainder (or the original string unchanged if it doesn't start with `prefix`). It's exactly what you want for parsing an `Authorization: Bearer <token>` header, as fu.ling-lang.org's publish controller does:

```ling
fn extract_key(request) {
    bind header = request.authorization
    if header == "" {
        return ""
    }
    return str_strip_prefix(header, "Bearer ")
}
```


[System] You are a coding assistant for the Ling programming language.

[User] What does `str_find` return?

[Assistant]
`str_find(s, needle)` returns the character index of the first occurrence of `needle` in `s`, or `-1` if it's not found — so it's typically checked with `>= 0`:

```ling
if str_find(body, "vtex_grid") >= 0 {
    print("uses the grid texture")
}
```


[System] You are a coding assistant for the Ling programming language.

[User] What does `html_escape` do and when would I use it?

[Assistant]
`html_escape(s)` escapes characters that are special in HTML (like `<`, `>`, `&`, quotes) so untrusted text can be safely embedded in an HTML response body — used constantly in Ling web controllers when interpolating user data into markup:

```ling
bind safe_name = html_escape(user.username)
bind html = "<span>" + safe_name + "</span>"
```


[System] You are a coding assistant for the Ling programming language.

[User] What is `json_escape` for?

[Assistant]
`json_escape(s)` escapes a string so it's safe to embed inside a JSON string literal (escaping quotes, backslashes, control characters, etc.) — used when hand-building JSON responses:

```ling
bind body = "{\"username\":\"" + json_escape(user.username) + "\"}"
```

This mirrors real code in fu.ling-lang.org's users controller, which builds a JSON array of user objects by hand with `json_escape` on every string field.


[System] You are a coding assistant for the Ling programming language.

[User] What does `format` do and what placeholder syntax does it use?

[Assistant]
`format(template, args...)` builds a string by substituting `{}` placeholders in `template` with the given arguments, in order — Rust-style formatting:

```ling
bind msg = format("{} v{}", "Ling", 2030)   # "Ling v2030"
```

It also supports precision specifiers like `{:.1}` for one decimal place:

```ling
bind line = format("rating: {:.1} / 5.0", 4.9)   # "rating: 4.9 / 5.0"
```


[System] You are a coding assistant for the Ling programming language.

[User] How do I convert a string to a number and back in Ling?

[Assistant]
`to_number(s)` parses a string into a number, and `to_str(n)` (also spelled `str`/`num_str`) converts a value to its string form:

```ling
bind port = to_number(cli_arg("port", "8420"))
bind label = to_str(port)   # "8420"
```

This exact pattern — pulling a numeric CLI/query argument out as text, then parsing it — is how ling-lin.me's `app.ling` reads its `--port` flag.


[System] You are a coding assistant for the Ling programming language.

[User] What print-related builtins does Ling have?

[Assistant]
`print` (aliased `println`) writes value(s) to stdout, accepting multiple comma-separated arguments that get concatenated:

```ling
print("epoch ", epoch, " loss = ", loss)
```

There's also `debug(v)` for inspecting a value while developing, and `panic(msg)` to abort with an error message.


[System] You are a coding assistant for the Ling programming language.

[User] What math builtins does Ling ship with?

[Assistant]
All the usual suspects, operating on `number` (f64) with angles in radians: `sin`, `cos`, `tan`, `asin`, `acos`, `atan2`, `sqrt`, `cbrt`, `pow(x, y)`, `abs`, `floor`, `ceil`, `round`, `trunc`, `min(a, b)`, `max(a, b)`, `clamp(x, lo, hi)`, and the constants `pi` and `tau`. Example:

```ling
bind d = sqrt(dx * dx + dy * dy)
bind capped = clamp(health, 0, 100)
```


[System] You are a coding assistant for the Ling programming language.

[User] What do `is_num`, `is_str`, `is_list`, and `is_bool` do?

[Assistant] None of those exist in ling-lang — there are no runtime type-checking predicates (`is_num`/`is_str`/`is_list`/`is_bool`/`typeof`/etc. are not real builtins, confirmed absent from the interpreter's builtin dispatch). If you need to convert or coerce a value, the real builtins are `to_number(s)` and `to_str(v)`. If you're unsure what shape a value is, structure your program so it doesn't need to ask — e.g. know from context whether a `db_query` column is numeric versus text, rather than probing a value's type at runtime.


[System] You are a coding assistant for the Ling programming language.

[User] What does `str_contains` (or the `.contains` method form) check?

[Assistant]
It tests whether a string contains a given substring anywhere, returning a boolean. Ling code commonly calls it as a method: `name.contains("/")`. It's used heavily for input validation — fu.ling-lang.org's publish controller rejects unsafe package names by chaining `.contains` checks:

```ling
fn is_safe_name(s) {
    if s == "" { return false }
    if s.contains("/") { return false }
    if s.contains("..") { return false }
    return true
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write a ling-lang function that returns the first 10 characters of a string.

[Assistant]
```ling
fn first_10(s) {
    return substr(s, 0, 10)
}
```

`substr(s, start, len)` takes a starting index and a length, so `substr(s, 0, 10)` grabs up to 10 characters from the beginning (fewer if the string is shorter).


[System] You are a coding assistant for the Ling programming language.

[User] Write a for loop that prints the numbers 0 through 9 in Ling.

[Assistant]
```ling
bind start = do {
    for i in 0..9 {
        print(i)
    }
}
```

`0..9` is exclusive of the end, so this prints 0 through 8. Use `0..10` if you want it to include 9 (i.e. print exactly ten numbers, 0 through 9).


[System] You are a coding assistant for the Ling programming language.

[User] I need a recursive Fibonacci function in Ling with type annotations.

[Assistant]
```ling
fn fibonacci(n: number) -> number {
    if n <= 1 {
        n
    } else {
        fibonacci(n - 1) + fibonacci(n - 2)
    }
}

bind start = do {
    for i in 0..10 {
        print("fibonacci(", i, ") = ", fibonacci(i))
    }
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write an iterative (non-recursive) Fibonacci function in Ling — I want it fast.

[Assistant]
```ling
fn fib_iter(n: number) -> number {
    bind a = 0
    bind b = 1
    bind i = 0
    while i < n {
        bind t = a + b
        bind a = b
        bind b = t
        bind i = i + 1
    }
    a
}
```

This mirrors the pattern used in Ling's own benchmark suite (`bench_opt1.ling` etc.) for testing interpreter performance — an accumulator loop instead of exponential recursion.


[System] You are a coding assistant for the Ling programming language.

[User] Define a Point struct in Ling with x and y fields, and write code that creates one and prints both fields.

[Assistant]
```ling
form Point { x, y }

bind start = do {
    bind p = Point(3, 4)
    print(p.x)
    print(p.y)
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write a function that builds a greeting string by concatenation, mixing a name and a count.

[Assistant]
```ling
fn greet(name, count) {
    return "Hello, " + name + "! This is visit number " + to_str(count) + "."
}
```

`+` concatenates strings directly; use `to_str()` to turn a number into text first if you're not using `format()`.


[System] You are a coding assistant for the Ling programming language.

[User] Same greeting, but using `format` instead of `+` concatenation.

[Assistant]
```ling
fn greet(name, count) {
    return format("Hello, {}! This is visit number {}.", name, count)
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write a function that builds a list of squares from 0 to 9 using the list builtins.

[Assistant]
```ling
fn squares() {
    bind result = list_new()
    for i in 0..10 {
        bind result = list_push(result, i * i)
    }
    return result
}
```

Remember `list_push` returns a *new* list, so each iteration rebinds `result` to the updated one.


[System] You are a coding assistant for the Ling programming language.

[User] Write a function that sums all the numbers in a list, walking it with a while loop.

[Assistant]
```ling
fn sum_list(nums) {
    bind total = 0
    bind i = 0
    while i < nums.len {
        bind total = total + list_get(nums, i)
        bind i = i + 1
    }
    return total
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write a function that checks whether a string is a safe filename — no slashes, no `..`, no spaces.

[Assistant]
```ling
fn is_safe_name(s) {
    if s == "" {
        return false
    }
    if s.contains("/") { return false }
    if s.contains("\\") { return false }
    if s.contains("..") { return false }
    if s.contains(" ") { return false }
    return true
}
```

This is the same defensive pattern fu.ling-lang.org uses before writing an uploaded package name to a file path — reject anything that could enable path traversal.


[System] You are a coding assistant for the Ling programming language.

[User] Write a function that extracts a Bearer token from an Authorization header string.

[Assistant]
```ling
fn extract_bearer_token(header) {
    if header == "" {
        return ""
    }
    return str_strip_prefix(header, "Bearer ")
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write a Ling function that builds an HTML unordered list from a list of strings, escaping each item.

[Assistant]
```ling
fn html_list(items) {
    bind body = ""
    bind i = 0
    while i < items.len {
        bind body = body + "<li>" + html_escape(list_get(items, i)) + "</li>"
        bind i = i + 1
    }
    return "<ul>" + body + "</ul>"
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write a Ling function that builds a minimal JSON array of objects from a list of package records with `name` and `description` fields.

[Assistant]
```ling
fn packages_json(pkgs) {
    bind i = 0
    bind parts = ""
    while i < pkgs.len {
        bind pkg = list_get(pkgs, i)
        if i > 0 {
            bind parts = parts + ","
        }
        bind parts = parts +
            "{\"name\":\"" + json_escape(pkg.name) + "\"," +
            "\"description\":\"" + json_escape(pkg.description) + "\"}"
        bind i = i + 1
    }
    return "[" + parts + "]"
}
```

This is the exact shape used by fu.ling-lang.org's `/api/organizations` and `/api/users` JSON endpoints — iterate with a while loop, comma-join, `json_escape` every string field.


[System] You are a coding assistant for the Ling programming language.

[User] Write a function `t(lang, en, th)` that picks between an English and a Thai string based on a language code.

[Assistant]
```ling
fn t(lang, en, th) {
    if lang == "th" {
        return th
    }
    return en
}
```

Real multilingual Ling sites extend this to more languages with the same shape — ling-lin.me's `t(lang, en, th, ko, ja, zh)` checks each code in turn and falls through to English as the default.


[System] You are a coding assistant for the Ling programming language.

[User] Write a state-machine enum in Ling for a traffic light, with a function that returns the next state.

[Assistant]
```ling
choose Light { Red, Yellow, Green }

fn next_light(state) {
    return match state {
        Red()    => Green(),
        Green()  => Yellow(),
        Yellow() => Red(),
        _        => Red(),
    }
}
```

Modeled on the real `AnimState` state machine (`choose AnimState { Idle, Walk, Run, Sit, Meditate, Swim }`) from `examples/anim/animations/animation_map.ling`.


[System] You are a coding assistant for the Ling programming language.

[User] Write a `mod` in Ling that wraps a couple of time-related helper functions, and call one from `start`.

[Assistant]
```ling
mod clock {
    fn current_hour() {
        return 14
    }

    fn is_morning(hour) {
        return hour < 12
    }
}

bind start = do {
    bind hour = clock::current_hour()
    print(clock::is_morning(hour))
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write a function that trims a line and checks if it starts with a function definition keyword, in either English or Thai.

[Assistant]
```ling
fn is_fn_def(line) {
    bind trimmed = trim(line)
    bind is_en = starts_with(trimmed, "fn ")
    bind is_th = starts_with(trimmed, "ฟังก์ชัน ")
    return is_en || is_th
}
```

This mirrors Ling's own `examples/tools/visualize.ling`, which scans source files for function definitions across multiple keyword languages this same way.


[System] You are a coding assistant for the Ling programming language.

[User] Write a function that splits a comma-separated string into a list and trims whitespace off each piece.

[Assistant]
```ling
fn split_trimmed(s, sep) {
    bind raw = split(s, sep)
    bind result = list_new()
    bind i = 0
    while i < raw.len {
        bind result = list_push(result, trim(list_get(raw, i)))
        bind i = i + 1
    }
    return result
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write a rate limiter helper: return true if `count` is below `max_allowed`, else false.

[Assistant]
```ling
fn under_limit(count, max_allowed) {
    if count > max_allowed {
        return false
    }
    return true
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write a small program that opens a window and draws a filled circle, using the `do` block entry point.

[Assistant]
```ling
bind start = do {
    open_window(800, 600)
    draw_disc(400.0, 300.0, 120.0)
    present()
}
```

This is Ling's own "first pixel in ~5 lines" showcase snippet — `open_window`, a draw call, then `present()` to flush the frame.


[System] You are a coding assistant for the Ling programming language.

[User] Write a function that safely divides two numbers, returning 0 instead of crashing on division by zero.

[Assistant]
```ling
fn safe_div(a, b) {
    if b == 0 {
        return 0
    }
    return a / b
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write a function that clamps a health value between 0 and 100 using a math builtin.

[Assistant]
```ling
fn clamp_health(hp) {
    return clamp(hp, 0, 100)
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write a function that builds a rate-limit key by combining an action name and client IP, falling back when the IP is empty.

[Assistant]
```ling
fn rate_limit_key(request, action, id) {
    bind ip = request.client_ip
    if ip == "" {
        return action + ": noip:" + id
    }
    return action + ":" + ip + ":" + id
}
```

Adapted from fu.ling-lang.org's `models/users.ling`, which builds rate-limit keys this exact way before checking a SQLite-backed counter.


[System] You are a coding assistant for the Ling programming language.

[User] Write a function that counts how many times a substring appears at the start of any line in a block of text.

[Assistant]
```ling
fn count_prefix_lines(text, prefix) {
    bind lines = split(text, "\n")
    bind count = 0
    bind i = 0
    while i < lines.len {
        if starts_with(trim(list_get(lines, i)), prefix) {
            bind count = count + 1
        }
        bind i = i + 1
    }
    return count
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write a function that strips a `.ling` file extension off a filename.

[Assistant]
```ling
fn strip_ling_ext(name) {
    return str_replace(name, ".ling", "")
}
```


[System] You are a coding assistant for the Ling programming language.

[User] Write a function that returns true only if a value is a non-empty string.

[Assistant]
```ling
fn is_nonempty_str(v) {
    if is_str(v) == false {
        return false
    }
    return v != ""
}
```


[System] You are a coding assistant for the Ling programming language.

[User] This crashes: `bind negative = -x`. What's wrong?

[Assistant]
Ling doesn't have a unary minus operator, so `-x` isn't valid syntax on its own — it only parses `-` as part of a numeric literal, not as a prefix operator on a variable. Subtract from zero instead:

```ling
bind negative = 0 - x
```


[System] You are a coding assistant for the Ling programming language.

[User]
Why doesn't my list have the item I pushed?

```ling
bind items = list_new()
list_push(items, "hello")
print(items.len)   # prints 0
```

[Assistant]
`list_push` doesn't mutate `items` in place — it returns a *new* list with the item appended, and you discarded that return value. Rebind `items` to the result:

```ling
bind items = list_new()
bind items = list_push(items, "hello")
print(items.len)   # prints 1
```


[System] You are a coding assistant for the Ling programming language.

[User]
Fix this — it won't parse:

```ling
fn add(a, b) {
    a + b
```

[Assistant]
The function body's closing brace is missing. It should be:

```ling
fn add(a, b) {
    a + b
}
```


[System] You are a coding assistant for the Ling programming language.

[User]
What's wrong with this for loop?

```ling
for i 0..10 {
    print(i)
}
```

[Assistant]
It's missing the `in` keyword between the loop variable and the range — Ling's `for` syntax is `for <var> in <range> { ... }`:

```ling
for i in 0..10 {
    print(i)
}
```


[System] You are a coding assistant for the Ling programming language.

[User]
This `match` never hits the `Idle` case — what's wrong?

```ling
return match state {
    Idle => "IDLE",
    Walk => "WALK",
    _    => "???",
}
```

[Assistant]
The `choose` variants need call-style parens in the match arms, even for variants with no data — `Idle()` and `Walk()`, not bare `Idle`/`Walk`:

```ling
return match state {
    Idle() => "IDLE",
    Walk() => "WALK",
    _      => "???",
}
```


[System] You are a coding assistant for the Ling programming language.

[User]
My `while` loop never terminates:

```ling
bind i = 0
while i < 10 {
    print(i)
    i = i + 1
}
```
What's wrong?

[Assistant]
`i = i + 1` alone isn't valid — Ling doesn't have a bare re-assignment operator; you must use `bind` again to rebind `i` in the same scope:

```ling
bind i = 0
while i < 10 {
    print(i)
    bind i = i + 1
}
```


[System] You are a coding assistant for the Ling programming language.

[User]
Why does field access fail here?

```ling
form Point { x, y }
bind start = do {
    bind p = Point(3, 4, 5)
    print(p.x)
}
```

[Assistant]
`Point` was declared with two fields (`x, y`) but constructed with three arguments (`3, 4, 5`) — that's a wrong-arity construction and will error. Fix it by matching the field count:

```ling
form Point { x, y }
bind start = do {
    bind p = Point(3, 4)
    print(p.x)
}
```


[System] You are a coding assistant for the Ling programming language.

[User]
Is this substr call correct if I want just the first 5 characters of `s`?

```ling
bind head = substr(s, 0, 5)
```

[Assistant] Yes, that's correct — `substr(s, start, len)` takes a length as its third argument, not an end index, so `substr(s, 0, 5)` returns the first 5 characters. A common mistake is treating the third argument as an end index (e.g. writing `substr(s, 2, 5)` expecting characters 2 through 5); it actually returns 5 characters starting at index 2.


[System] You are a coding assistant for the Ling programming language.

[User]
This is supposed to import a sibling module but nothing gets loaded:

```ling
load "controllers/home"
```

[Assistant]
`load` isn't a Ling keyword — the import keyword is `use`:

```ling
use "controllers/home"
```


[System] You are a coding assistant for the Ling programming language.

[User]
Why does this `if`-as-expression fail to bind a value?

```ling
bind label = if score > 90 {
    "A"
}
```

[Assistant]
An `if` used as an expression needs an `else` branch, since without one there's no value to produce when the condition is false. Add an `else`:

```ling
bind label = if score > 90 {
    "A"
} else {
    "B"
}
```


[System] You are a coding assistant for the Ling programming language.

[User]
What's wrong with this string check?

```ling
if name.equals("admin") {
    print("blocked")
}
```

[Assistant]
`equals` isn't a Ling string builtin — string equality uses the `==` operator directly:

```ling
if name == "admin" {
    print("blocked")
}
```


[System] You are a coding assistant for the Ling programming language.

[User]
This function never returns the right thing — help me spot the bug:

```ling
fn is_safe_name(s) {
    if s.contains("/") {
        false
    }
    return true
}
```

[Assistant]
The `if` branch's value (`false`) is just an expression sitting in the middle of the function — it's never returned, so execution always falls through to `return true` even for unsafe names. Use an explicit `return` inside the branch:

```ling
fn is_safe_name(s) {
    if s.contains("/") {
        return false
    }
    return true
}
```


[System] You are a coding assistant for the Ling programming language.

[User]
Why does this module call fail?

```ling
mod clock {
    fn current_hour() {
        return 14
    }
}

bind h = clock.current_hour()
```

[Assistant]
Namespaced functions inside a `mod` are called with `::`, not `.` — `.` is for field/method access on values, while `::` reaches into a module's namespace:

```ling
mod clock {
    fn current_hour() {
        return 14
    }
}

bind h = clock::current_hour()
```


[System] You are a coding assistant for the Ling programming language.

[User]
This range loop skips the last element I want — why?

```ling
bind items = [10, 20, 30]
for i in 0..items.len {
    print(list_get(items, i))
}
```
Is the range wrong?

[Assistant] Actually that's correct as written — `0..items.len` with a 3-element list is `0..3`, which is exclusive of the end, giving indices 0, 1, 2 — exactly the valid indices for a 3-element list. If you were seeing a missed element, the likely bug is using `0..(items.len - 1)` instead, which would stop one index too early and skip the last item.


[System] You are a coding assistant for the Ling programming language.

[User]
Fix this JSON-building snippet — the output has invalid quoting:

```ling
bind body = "{\"name\":\"" + user.name + "\"}"
```

[Assistant]
Raw user data is being spliced straight into the JSON string without escaping — if `user.name` contains a `"` or backslash, the JSON breaks (or worse, allows injection). Wrap it in `json_escape`:

```ling
bind body = "{\"name\":\"" + json_escape(user.name) + "\"}"
```


[System] You are a coding assistant for the Ling programming language.

[User]
Why doesn't this print anything useful?

```ling
bind start = do {
    bind msg = "hi"
}
print(msg)
```

[Assistant]
`msg` is bound *inside* the `do { ... }` block that makes up `start`, so it's scoped to that block and doesn't exist outside it — `print(msg)` at the top level references an undefined name. Either print from inside the block, or have the block's last expression produce the value you need:

```ling
bind start = do {
    bind msg = "hi"
    print(msg)
}
```


[System] You are a coding assistant for the Ling programming language.

[User]
This HTML output isn't escaped and I'm worried about XSS — what's the fix?

```ling
bind html = "<p>" + comment.body + "</p>"
```

[Assistant]
Untrusted text is being embedded directly into HTML. Run it through `html_escape` first:

```ling
bind html = "<p>" + html_escape(comment.body) + "</p>"
```

This is the standard pattern in every Ling web controller that renders user-supplied strings.


[System] You are a coding assistant for the Ling programming language.

[User]
Why does this comparison always evaluate as true?

```ling
if valid = true {
    print("ok")
}
```

[Assistant]
`=` is the bind/assignment operator, not equality — inside an `if` condition you need `==`:

```ling
if valid == true {
    print("ok")
}
```

(Or just `if valid { ... }` directly, since `valid` is already a boolean.)


[System] You are a coding assistant for the Ling programming language.

[User]
This `choose`/`match` is missing something the compiler complains about — what?

```ling
choose Light { Red, Yellow, Green }

fn next(state) {
    return match state {
        Red()   => Green(),
        Green() => Yellow(),
    }
}
```

[Assistant]
The match has no arm for `Yellow()` and no wildcard `_` fallback, so a `Yellow` value has nowhere to go. Add the missing case (and it's good practice to keep a `_` catch-all too):

```ling
choose Light { Red, Yellow, Green }

fn next(state) {
    return match state {
        Red()    => Green(),
        Green()  => Yellow(),
        Yellow() => Red(),
        _        => Red(),
    }
}
```