# Basics

URL: /docs/tour/basics
Markdown: /docs/tour/basics.md

> Variables, functions, if and match, strings, lambdas, loops and modules in Sakura Lang.

This page covers the everyday syntax: variables, functions, branches, loops and files. If you know TypeScript, Go or Rust, most of it will look familiar.

```sakura
/// Add up the positive numbers in a list.
fn total(xs: List<Int>) -> Int {
  var sum = 0
  for x in xs {
    if x > 0 { sum = sum + x }
  }
  sum
}

pub fn main() -> Unit ! {Console} {
  let numbers = [3, -1, 4]
  Console.print("total: {total(numbers)}")
}

test "skips negatives" { expect_eq(total([3, -1, 4]), 7) }
```

- `fn` declares a function. Parameter types and the return type are always written out.
- A block's value is its last expression, so `total` returns `sum` without `return`.
- `var` is a variable you can reassign. `let` is one you cannot.
- `main` is where the program starts. `! {Console}` says it prints; the [Effects](/docs/tour/effects) page explains this.
- `test` blocks live next to the code and run with `sakura test`.

You do not need semicolons. There is no `null`, no classes, no exceptions and no `async`/`await`.

## Bindings [#bindings]

`let` binds a name you cannot reassign. `var` binds one you can. You rarely write local types; the compiler works them out.

```sakura
fn bindings() -> Int {
  let big = 20_000          // underscores between digits
  let mask = 0xFF           // also 0b1010
  let ratio = 0.75          // Float needs a digit on both sides of the dot
  let primes = [2, 3, 5, 7] // List<Int>
  let pair = (1, "one")     // tuple; pair.0, pair.1
  var count = 0
  count = count + List.len(primes)
  count + big + mask
}
```

`()` is the `Unit` value, the "nothing" result of a function that only does something. Reassigning a `var` changes that name only, never a value someone else holds ([Memory model](/docs/tour/memory)). A top-level `let` is a constant; a `pub let` needs a type annotation.

## Functions [#functions]

Every top-level function has a full signature: parameter types, `-> ResultType`, and the effects it may perform after `!`.

```sakura
fn add(a: Int, b: Int) -> Int {
  a + b
}

fn clamp(n: Int, lo: Int, hi: Int) -> Int {
  if n < lo { return lo }
  if n > hi { return hi }
  n
}

pub fn greet(name: String) -> Unit ! {Console} {
  Console.print("hello, {name}")
}
```

- `return e` exits early. Usually you don't need it.
- A signature without `!` is **pure**: it only computes its result. [Effects](/docs/tour/effects) covers the rest.
- `-> Unit` is written out; there is no default return type.
- Items are private to their file unless marked `pub`.
- An expression whose value you ignore must be `Unit`. To throw a value away on purpose, write `let _ = e` (otherwise `V2040`).

## Branches: if and match [#branches-if-and-match]

`if` is an expression, so it returns a value. With `else`, both branches have the same type.

```sakura
fn label(score: Int) -> String {
  if score >= 90 { "excellent" } else if score >= 50 { "pass" } else { "keep going" }
}

fn can_vote(age: Int, registered: Bool, suspended: Bool) -> Bool {
  age >= 18 && registered && !suspended
}
```

`match` picks a branch by the shape of a value. It must cover every case; the compiler tells you which one is missing. Branches can have an `if` guard. See [Types](/docs/tour/types#pattern-matching) for every pattern.

```sakura
fn describe(n: Option<Int>) -> String {
  match n {
    Some(0) => "zero"
    Some(x) if x > 0 => "positive"
    Some(_) => "negative"
    None => "missing"
  }
}
```

## Strings [#strings]

Strings are UTF-8 and can span lines. `{expr}` inside a string inserts a value. Write `\{` for a literal brace.

```sakura
fn inbox(name: String, unread: List<String>) -> String {
  "Hello, {name}. You have {List.len(unread)} messages. \{not interpolated\}"
}
```

The other escapes are `\\ \" \n \r \t \0 \}` and `\u{…}`. A `Secret<T>` cannot be inserted into a string (`V2031`). Tagged strings such as `sql"…"` and `html"…"` pass inserted values safely, never as raw text; see [Types](/docs/tour/types#tagged-templates).

## Lambdas [#lambdas]

A lambda is an unnamed function: `fn(params) { body }`. Annotations on its parameters are optional.

```sakura
fn twice<e>(f: fn(Int) -> Int ! e, x: Int) -> Int ! e {
  f(f(x))
}

test "twice applies f two times" {
  let add3 = fn(x) { x + 3 }
  let mul2 = fn(x: Int) -> Int { x * 2 }
  expect_eq(twice(add3, 3), 9)
  expect_eq(twice(mul2, 3), 12)
}
```

A function type is written `fn(A, B) -> C`. The lowercase `e` stands for "whatever effects `f` has", so `twice` does whatever `f` does ([Effects](/docs/tour/effects)).

A lambda captures the values of the names it uses at the moment it is created. It cannot assign to an outer `var` (`V2041`), and it cannot call itself (`V1020`); use a top-level function for recursion.

## Dot calls [#dot-calls]

`x.f(a)` is short for `T.f(x, a)`, where `T` is the type of `x`. So `xs.map(f)` is `List.map(xs, f)` and `s.len()` is `String.len(s)`. There are no methods or `self`. A chain can continue on the next line with a leading `.`:

```sakura
type User = { name: String, active: Bool }

fn names(users: List<User>) -> List<String> {
  users
    .filter(fn(u) { u.active })
    .map(fn(u) { u.name })
}
```

The exact lookup rules are in [Types](/docs/tour/types#method-call-resolution).

## Loops [#loops]

`for x in xs { }` walks a `List`, `Range`, `Set` or `Map` (as `(key, value)` pairs). `while cond { }` loops while a condition holds. `break` and `continue` work in both. Loops produce no value: collect results in a `var`, or use `List.fold`.

```sakura
fn total(xs: List<Int>) -> Int {
  var sum = 0
  for x in xs {
    if x < 0 { continue }
    sum = sum + x
  }
  sum
}

fn total_fold(xs: List<Int>) -> Int {
  List.fold(xs, 0, fn(acc, x) { if x < 0 { acc } else { acc + x } })
}

fn countdown(n: Int) -> Unit ! {Console} {
  for i in 0..n {
    Console.print("{n - i}")
  }
}
```

`0..n` counts from `0` up to, but not including, `n`.

## Typed holes [#typed-holes]

A **typed hole** is a placeholder, `?name`, for code you have not written yet. `sakura check` accepts it and tells you what type fits there, which names are in scope and good candidates. `sakura build` and `sakura run` refuse to run code with holes (`V2050`). Agents use holes to ask the compiler what to write; see [Typed holes](/docs/agents/typed-holes).

```sakura holes
fn unfinished(x: Int) -> Int { ?result }
```

## Modules and imports [#modules-and-imports]

One file is one module. Its name is its path under `src/`: `src/users/repo.sak` is module `users/repo`. The program starts at `pub fn main()` in `src/main.sak`.

This is an excerpt of import lines, not a standalone program.

```sakura fragment
import std/http.{Http}                      // bind names directly
import std/request.{Request}
import std/response.{Response}
import std/sql                               // bind only the module name `sql`
import acme/billing/invoices as inv          // rename
```

- Only the prelude is in scope without an import. If you use a std name you did not import, the compiler offers the import as a fix (`V1002`).
- There are no wildcard imports, relative imports, re-exports or import cycles (`V1030`).
- `pub type` exports a type with its fields and constructors. `pub opaque type` exports only the name, so other modules cannot build or take apart its values (`V1006`).
- The prelude includes the built-in types (`Int`, `String`, `List`, `Map`, `Set`, `Secret`, `Untrusted`, …), `Option`, `Result`, `Duration`, `Instant`, `Uuid`, `Json`, `Level`, `Some None Ok Err`, the effects `Fail Console Clock Random Env Log Task Test`, `show`, the `expect…` test functions, and the tags `sql html url shell`.

## Comments and attributes [#comments-and-attributes]

```sakura
// A line comment. /* Block comments */ nest.

/// A doc comment. It attaches to the next item and is exported with its signature.
pub fn double(n: Int) -> Int {
  n * 2
}
```

An attribute such as `@deprecated` goes before an item. The full set is `@tool`, `@llm`, `@external`, `@total`, `@contract_test`, `@deprecated`, `@server` and `@test_only`; an unknown one is `V1010`. Arguments are positional or `name: value`, as in `@llm(system: "…")`. `@trust("reason")` is the one attribute written inside an expression.

## Reference [#reference]

### Keywords [#keywords]

```text
fn let var type error effect handler with try catch fail if else match for in while
return break continue import pub opaque as test property requires ensures where true false
```

`verify proof ghost control resume region spawn actor interface impl` are reserved for later and rejected today (`V0007`). A reserved word is still fine after `.` or `fn`, so `Task.spawn(s, body)` works. `it` is special only inside a `where` rule, and `result` only inside `ensures`.

### Names and casing [#names-and-casing]

Casing is part of the grammar. Values, functions, modules, fields and effect-row variables are `snake_case`. Types, variants, error tags, effects and type variables are `PascalCase`. A mismatch is `V1004`.

### Where a line ends [#where-a-line-ends]

There are no required semicolons. A line break ends a statement only when **both** hold:

1. The previous token can end an expression: a name, a hole, a literal, `)`, `]`, `}`, `>`, postfix `?`, `true`, `false`, `break`, `continue` or `return`.
2. The next token cannot continue one: it is not `.`, `else`, `catch`, `)`, `]`, `}`, `,`, `=>`, `=`, `->`, `|`, `..`, or a binary operator other than `-`.

In practice:

- A line ending in an operator other than `>`, or in `(`, `[`, `{` or `,`, continues. (`>` ends a line so that `type Ids = List<Int>` ends; put a continued `>` comparison at the start of the next line.)
- A line starting with `.`, `else` or `catch` continues the previous one.
- `foo` followed by `(bar)` on the next line is **two** statements. So is `foo` followed by `-1`.
- Newlines inside `(` and `[` never matter. `;` is always accepted; `sakura fmt` removes extra ones.

### Operators [#operators]

Tightest first:

| Level | Operators | Associativity |
| --- | --- | --- |
| 1 | call `f(x)`, field `.x`, tuple index `.0`, index `[i]`, raise `?` | postfix |
| 2 | `-` `!` | prefix |
| 3 | `*` `/` `%` | left |
| 4 | `+` `-` | left |
| 5 | `..` (range, end not included) | none |
| 6 | `==` `!=` `<` `<=` `>` `>=` | none |
| 7 | `&&` | left |
| 8 | `\|\|` | left |

- Both sides must have the same type. `Int + Float` is a type error; convert with `Int.to_float` or `Float.round`.
- `+` also joins `String`s. Nothing else is overloaded, and you cannot define operators.
- `Int` arithmetic is checked. Overflow (`D001`) and division by zero (`D002`) are **defects**: bugs that stop the program, not normal errors.
- `a < b < c` is `V0010`. `&&` and `||` short-circuit. There is no unary plus.
- `xs[i]` is `List.get(xs, i)` and returns an `Option`.

### Four parsing rules [#four-parsing-rules]

- In expressions, `<` is always "less than". You cannot write type arguments at a call: `List<Int>.empty()` is `V0011`. Annotate the binding instead: `let xs: List<Int> = List.empty()`.
- There are no named arguments: `f(name: v)` is `V0014`. Pass a record when there are many options.
- In the header of `if`, `while`, `for`, `match` and `with`, `Name {` starts the block, not a record. Put record literals there in parentheses.
- `if`, `match`, `with`, `try`, `fn`, `handler` and `fail` expressions need parentheses to be used as operands: `(match x { … }).len()` (`V0012`).

## What the compiler checks [#what-the-compiler-checks]

- Every top-level function has a complete signature (`V3001` lists effects a body performs beyond it).
- Casing matches the kind of name (`V1004`). Reserved words cannot be names (`V0007`).
- Unused non-`Unit` results are errors (`V2040`).
- Name conflicts within a module are errors (`V1001`). A local that hides an import is a warning (`W1002`).
- Every `match` covers every case (`V4001`). Unreachable branches are reported (`V4002`).
- `sakura fmt` has no options: 2-space indent, width 100, one layout.

## Next [#next]

[Types](/docs/tour/types): records, variants, `Option` instead of null, and types with rules.

Details for contributors: [design §2.4, §3.1, §3.2](https://github.com/icantcodefyi/sakuralang/blob/main/docs/design.md).
