Metadata-Version: 2.4
Name: caelix-lang
Version: 2.1.0
Summary: Caelix: a small interpreted programming language written in C (display, ask, classes, modules, REPL).
License: MIT
Keywords: caelix programming-language interpreter repl
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: POSIX
Classifier: Programming Language :: C
Classifier: Topic :: Software Development :: Interpreters
Classifier: Topic :: Software Development :: Compilers
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: requires-python
Dynamic: summary

# Caelix 2.1.0

A small interpreted language written in C11: custom lexer, recursive-descent parser, AST, tree-walking
interpreter, mark-and-sweep garbage collector. No Python, no LLVM, no regex parsing.

    make                                  # build ./caelix (uses OpenSSL for HTTPS if it is installed)
    make test                             # all tests (also re-runs the suite with GC stress)
    make PREFIX=/your/prefix install      # caelix, clxpm and stdlib (Termux sets PREFIX already)
    ./caelix examples/hello.clx
    ./caelix                               # REPL with live syntax highlighting (exit() or Ctrl-D quits)
    ./caelix --highlight file.clx          # print a file in color

Builds with gcc or clang. Termux: `pkg install clang make openssl` (OpenSSL is optional; without it everything
works except `https://`). The build prints `HTTPS ENABLED` or `HTTPS disabled` so you can see which you got. Docs: `docs/LANGUAGE.md`. History: `CHANGELOG.md`.

## Install with pip

    pip install caelix-lang
    caelix --version            # Caelix 2.1.0
    caelix                      # REPL      (caelix file.clx runs a program)
    clxpm help                  # package manager

pip compiles the interpreter on your machine, so you need **Python 3.8+ and a C compiler**
(Termux: `pkg install python clang`; Debian/Ubuntu: `apt install build-essential`; macOS: `xcode-select --install`).
Windows is not supported natively (use WSL). If OpenSSL's development files are installed when you run pip
(Termux: `pkg install openssl`), `https://` is enabled; force it on or off with `CAELIX_TLS=1` / `CAELIX_TLS=0`.
`http.tls` in a program tells you which you got. The standard library is installed next to the commands
(`<prefix>/share/caelix/stdlib`) and found automatically. Remove with `pip uninstall caelix-lang`.
`python -m caelix_lang file.clx` also works.

The PyPI name is **caelix-lang**, not `caelix`: the name `caelix` on PyPI already belongs to someone else (a
0.0.1 placeholder). The commands you type are still `caelix` and `clxpm`. To use another PyPI name, change
`DIST_NAME` at the top of `setup.py`.

**Publishing a release (maintainer notes).** You need a PyPI account and an API token, and the name must still be free.

    python -m pip install build twine
    python -m build --sdist                          # dist/caelix_lang-X.Y.Z.tar.gz
    python -m twine check dist/*
    python -m twine upload --repository testpypi dist/*   # rehearse on TestPyPI first
    python -m twine upload dist/*

Every upload needs a new version number (edit `CAELIX_VERSION` in `include/caelix.h`, the single source of the
version). Only the source package is published, so every user needs a compiler; prebuilt wheels for Linux and macOS
would remove that, and need a CI job that builds them. The same wheel/sdist builds are exercised by `tests/pip_test.sh`.

## What exists

| Area | Status |
|---|---|
| Language (spec 0.1 to 0.4) | done: variables, types, conditions, all loops, functions, lists, maps, interpolation, classes, `use`, try/catch |
| REPL (live highlighting, history, `exit()`), errors with source line + caret | done |
| Garbage collector | done (see below) |
| Modules | `math`, `files`, `time`, `date`, `system`, `json`, `http` (HTTP and HTTPS), `core`, `network`, `database` |
| Classes | fields, methods, `init`, single inheritance (`extends`, `super`, `is_a`) |
| CLXPM | done: local packages and a static-file registry (see below) |
| Not implemented | UDP, SQL, multiple inheritance, lambdas, regex |

## Grammar decisions (please review)

1. **`elif` and `else if` both work** and mean the same thing (`else if` on one line; `else` followed by a newline and `if` is a nested `if` that needs its own `end`).
2. **Range comma ambiguity.** `for i in a, b[, step]` is a range; `for x in expr` (no top-level comma) iterates a
   list, string (bytes) or map (keys). Commas inside `[]`, `()`, `{}` belong to those. Range bounds are inclusive,
   must be Int, step defaults to 1. `for i in 10, 1` therefore runs zero times; reverse needs an explicit `-1`.
3. **`display a, b`** prints values separated by one space; add `sep = "-"` to choose another separator. So `display "Age: ", age` prints `Age:  14` (two spaces); use `display "Age:", age` or `sep = ""`.
4. **`self`** is required inside methods to reach fields (`self.health`). The spec did not define this.
   Optional `function init(...)` is the constructor.
5. **`/`** always returns Float (`10 / 2` is `5.0`). `%` is floor-modulo. `**` on Ints stays Int.
6. `"text" + 5` converts the non-string side to text. `+` on two Lists concatenates.
7. `and` / `or` / `not` return Bool. Truthy: not null/false/0/0.0/""/[]/{}.
8. Typed declarations (`age: Int = 14`) are checked **at declaration only**. `x: Float = 3` converts to 3.0.
9. Commands without parentheses: `display`, `ask`, `add`, `remove`, `read`, `fail`.
10. Interpolation: `"{expr}"` inserts a value **only when the text inside the braces parses as one expression**.
    Anything else stays literal, so `'{"a": 1}'` and `"{x: 1}"` need no escaping. `\{` still forces a literal brace
    (use it for something like `{name}` that you want printed as text). The expression cannot contain the string's
    own quote type (write `"{m['k']}"`).
11. `catch error` binds the error **message as a String**; raise your own with `fail("message")`.
12. Extra built-ins beyond the spec list: `keys`, `has`, `read`, `fail`, `exit`, `quit`.

## Garbage collector

Precise mark-and-sweep over strings, lists, maps, functions, classes and instances. Roots are all live scopes,
a temp-root stack for values held mid-expression, the return value and the module cache. It runs only at
statement boundaries (or on `system.gc()`, which returns the live object count), so native functions never see
an object disappear. The test suite is also run with `CAELIX_GC_STRESS=1` (collect before every statement) and was
checked under AddressSanitizer. `CAELIX_GC_STATS=1` prints collection counts at exit.
Measured: a 2,000,000-iteration string-building loop peaks around 11 MB.

Limits: scopes captured by a closure, and everything they reference, are never freed (a function that creates an
inner function leaks that call's scope). Instances are not freed while their class is reachable by name.

## http module (HTTP and HTTPS)

    use http
    r = http.get("http://127.0.0.1:8080/x")       // map: status (Int), body (String), headers (Map, lower-case keys)
    http.post(url, body [, content_type])
    http.request("PUT", url [, body [, content_type]])

HTTP/1.0 over sockets, 15 s timeout, 64 MB response cap, chunked responses decoded. A response shorter than its
`Content-Length` is an error. Redirects are not followed. Bodies with NUL bytes are truncated (strings are C strings).

**HTTPS** needs OpenSSL 1.1 or newer when you build (Termux: `pkg install openssl`, then `make clean && make`;
`http.tls` tells a script whether the running build has it). It checks the server certificate against the system's
trusted authorities and checks that the certificate matches the host name or IP address you asked for (TLS 1.2 or
newer, SNI sent). A bad certificate raises an error; there is no "ignore certificate errors" switch. To trust a
private certificate authority or a self-signed test certificate, point `SSL_CERT_FILE` at its PEM file. Without
OpenSSL, `https://` raises an error saying so. Tested here against local TLS servers (untrusted, trusted,
wrong-host, IP-address and chunked cases), not against the public internet.

## REPL and syntax highlighting

On a real terminal the REPL is a small line editor: your input is colored **as you type** (keywords, strings,
numbers, comments, `{interpolation}`, function calls, class names), blocks keep prompting with `...` until `end`,
and results are colored too.

- **Leave:** `exit()`, `quit()`, bare `exit` / `quit`, or Ctrl-D. `exit(3)` sets the exit code. `exit()` also works in scripts.
- **Keys:** Left/Right/Home/End, Backspace/Delete, Up/Down history (saved in `~/.caelix_history`), Ctrl-A/E start/end,
  Ctrl-U/K delete to start/end, Ctrl-W delete word, Ctrl-L clear screen, Tab inserts 4 spaces,
  Ctrl-C throws away the current line or block.
- **Plain mode:** piped input, a non-terminal, `TERM=dumb`, or `NO_COLOR=1` (colors only) fall back automatically.
- **Files:** `caelix --highlight file.clx` prints colored source (`| less -R` to page it). For editing, see
  `editor/README.md`: ready-made files for **nano** (`editor/nano/caelix.nanorc`), **vim** and **VS Code**.
  The editor files were written to each program's documented format and checked for valid syntax, but I could not
  run them inside nano/vim/VS Code here; the built-in `--highlight` and REPL highlighting are fully tested.
- The highlighter uses the real parser to decide what is interpolation, so `"{name}"` is marked but `'{"a": 1}'` is not.

## Classes and inheritance

    class Animal
        sound = "..."
        function init(name)
            self.name = name
        end
        function speak()
            display self.name, "says", self.sound
        end
    end
    class Dog extends Animal
        sound = "woof"
        function init(name, trick)
            super.init(name)                 // call the parent's version
            self.trick = trick
        end
    end
    d = Dog("Rex", "sit")     d.speak()     display is_a(d, Animal)     // true

A child inherits fields (and may override their defaults) and methods. `super.method(...)` calls the parent's
method on the same object; it works only inside methods and only for methods (not fields). `init` is inherited if
the child has none. `is_a(x, Class)` is true for the class and all its ancestors. One parent per class.

## Renamed from Veyra (2.0.0)

The language was called Veyra up to 1.4.0. Nothing about the language changed, but every name did:

| Veyra | Caelix |
|---|---|
| `veyra` command | `caelix` |
| `vpm` package manager | `clxpm` |
| `.vyr` files | `.clx` |
| `vpm_modules/`, `vpm.lock`, `veyra.json` | `clx_modules/`, `clxpm.lock`, `caelix.json` |
| `VPM_REGISTRY`, `VEYRA_STDLIB`, `VEYRA_GC_STRESS`, `VEYRA_GC_STATS`, `VEYRA_BIN` | `CLXPM_REGISTRY`, `CAELIX_STDLIB`, `CAELIX_GC_STRESS`, `CAELIX_GC_STATS`, `CAELIX_BIN` |
| `~/.veyra_history`, `share/veyra/stdlib` | `~/.caelix_history`, `share/caelix/stdlib` |
| `editor/vscode-veyra`, `veyra.nanorc` | `editor/vscode-caelix`, `caelix.nanorc` |

To move old programs over, rename the files (modules are now found as `name.clx`, not `name.vyr`) and, if you have
Veyra packages, rename `veyra.json` to `caelix.json` and `vpm_modules` to `clx_modules`:

    for f in *.vyr; do mv "$f" "${f%.vyr}.clx"; done
    sed -i 's/^\(\s*\)say\b/\1display/' *.clx        # only for files written before 1.3.1

The old `veyra` and `vpm` commands are not kept as aliases. Inside the C sources the internal helper prefix `vy_`
is unchanged (it is not visible to programs).

## Changes in 1.4.0: `ask` with a type

    name   = ask "Enter name: "            // String (default, unchanged)
    age    = ask (int) "Enter age: "       // Int
    price  = ask (float) "Enter price: "   // Float
    active = ask (bool) "Active? "         // Bool  (true/false, yes/no, y/n, 1/0, on/off)

Surrounding spaces are ignored for `int`, `float` and `bool`. Bad input raises a catchable error that quotes the text
(`ask (int): "forty" is not a whole number (for example 42 or -7)`); it does not re-prompt. At end of input a typed `ask`
is an error while a plain `ask` still returns `null`. `(str)` is accepted as an explicit spelling of the default.
Existing `ask "..."`, bare `ask` and `ask ("prompt")` are unchanged. Details and the exact rules: `docs/LANGUAGE.md`.

## Changes in 1.3.1

- **`say` is now `display`.** Same behavior, new name. `say` is no longer a keyword; using it gives a hint
  (`'say' was renamed to 'display'`). To convert old files: `sed -i 's/^\(\s*\)say\b/\1display/' file.clx`.
- **String operations** `uppercase` `lowercase` `capitalize` `shred` `reverse` `length` `ridiculous`:

      name = "pamu"
      display uppercase.{name}           // PAMU
      display capitalize."hello world"   // Hello world
      display shred."  hello  "          // hello
      display ridiculous."simple"        // SiMpLe

  Operand: a string, `{expression}`, or another operation. `capitalize` changes only the first character.
  `ridiculous` alternates over letters only (`"hello world"` -> `HeLlO wOrLd`). `reverse` is UTF-8 safe;
  `length` counts bytes and also takes lists and maps. Full rules in `docs/LANGUAGE.md`.
- **`sep`:** `display "Hello", "World" sep = "-"` prints `Hello-World`. `sep` is only special right after the values of a
  `display` and must be a String; as a variable name it still works.
- **`/n/` is a newline inside strings:** `display "hello/n/world"` prints two lines. `\n` still works too. To print the
  literal text `/n/`, write `\/n/`. Any existing string that contained `/n/` now has a newline there.

## Operators added in 1.3

- **`in` / `not in`:** `"a" in list`, `"ell" in "hello"`, `"key" in map` (keys), `x not in list`.
- **`x++` / `x--`:** statements only (not inside expressions), on variables, list items and fields: `count++`, `items[0]--`.
- **Error hints:** the interpreter now suggests fixes: a missing comma (`display "a" b`, `[1 2]`), words from other languages
  (`print`, `return`, `break`, `elseif`, `let`...), typos in keywords, and "did you mean" for misspelled variables,
  map keys, object fields and module functions.

## date module

Timestamps are whole seconds since 1970-01-01 UTC (`date.now()` returns a Float). Functions without a suffix use the
device's local time zone; the `_utc` twins use UTC. Month and weekday names are English.

    use date
    t = date.make(2024, 2, 29, 12, 30)              // local time -> timestamp   (make_utc for UTC)
    date.parts(t)        // {year, month, day, hour, minute, second, weekday (1=Mon..7=Sun), weekday_name, month_name, yday, timestamp}
    date.format(t, "%A, %d %B %Y %H:%M")            // strftime codes
    date.parse("2024-03-01 08:15", "%Y-%m-%d %H:%M")   // strptime codes -> timestamp
    date.add(t, "months", 1)     // units: seconds minutes hours days weeks months years (negative allowed)
    date.diff(a, b, "days")      // b - a; Float for seconds..weeks, whole Int for months/years
    date.today()   date.now()   date.is_leap(2024)   date.days_in_month(2024, 2)

`add` is calendar-aware: adding days keeps the wall-clock hour across daylight-saving changes, and Jan 31 + 1 month is
Feb 28/29. A local time that does not exist (the daylight-saving gap) is an error. `parse` rejects text that does not
match the format and impossible dates such as Feb 31.

## core module (text and list utilities)

    use core
    core.split("a,b", ",")   core.join(list, ", ")   core.replace(s, old, new)   core.trim(s)
    core.upper(s) core.lower(s) core.starts_with(s, p) core.ends_with(s, p) core.index_of(x, item)
    core.slice(x, start[, end])   core.chars(s)   core.ord("A")   core.chr(65)   core.pad_left(s, w[, fill])   core.pad_right
    core.sort(list)   core.sort_by(list_of_maps, "key")   core.reverse(x)   core.pop(list)   core.insert(list, i, v)
    core.sum(list)   core.range(a, b[, step])   core.unique(list)   core.min(list)   core.max(list)
    core.copy(x)   core.values(map)   core.assert(cond[, message])   core.version

`sort`, `reverse`, `slice`, `range` return new values; `pop` and `insert` change the list. `slice` ends are
exclusive and may be negative. `range` is inclusive, like `for i in a, b`. `chr` supports ASCII 1 to 127.

## network module (TCP sockets)

    use network
    c = network.connect("127.0.0.1", 8080 [, timeout_secs])      // handle (Int)
    network.send(c, "text\n")     network.recv(c [, max_bytes])     network.recv_line(c)   // null when closed
    srv = network.listen(0 [, "127.0.0.1"])   network.port(srv)   conn = network.accept(srv)
    network.timeout(h, secs)   network.close(h)   network.resolve("localhost")   network.hostname()

Handles are small Ints; at most 255 are open at once. Text only (a NUL byte ends received data). No TLS, no UDP.
Timeouts raise a catchable error.

## database module (embedded tables)

    use database
    db = database.open("app.db")             // or ":memory:"; the file is created on save/close
    database.create_table(db, "users")       // true if new, false if it already existed
    id = database.insert(db, "users", {name: "Amy", age: 25})     // rows get an automatic Int "id"
    database.get(db, "users", id)            // row, or null
    database.all(db, "users")   database.find(db, "users", {age: 25})   database.count(db, "users"[, {where}])
    database.update(db, "users", id, {age: 26})   database.delete(db, "users", id)     // true/false
    database.tables(db)   database.drop_table(db, "users")   database.save(db)   database.close(db)

Data is kept in memory and written (atomically, via a temp file and rename) by `database.save` and
`database.close`; **changes are lost if the script ends without saving**. The file is plain JSON. Values must be
JSON-encodable. `find` matches rows whose fields equal every key you give. Rows you get back are shallow
copies: editing one does nothing until you call `update`. Lookups scan the table, so it suits thousands of rows,
not millions. There is no SQL, no indexes and no transactions.

## clxpm (package manager)

    clxpm create name                 scaffold a package
    clxpm install ./dir               local package -> ./clx_modules/<name>, recorded in ./clxpm.lock
    clxpm install name[@version]      from the registry in $CLXPM_REGISTRY
    clxpm update [name]   clxpm remove name   clxpm list
    clxpm pack ./dir [outdir]         build registry files from a package

A package is a directory with `main.clx` and `caelix.json` (`{"name": "...", "version": "..."}`); `use name` loads it.
A **registry** is any static file host (`http://`, `https://` or `file://`) with `<name>/latest`,
`<name>/<version>.tar.gz` and `<name>/<version>.tar.gz.sha256`; `clxpm pack` writes exactly that layout, so
"publishing" means uploading its output directory yourself. Installs verify the checksum when published, reject
archives with absolute or `..` paths, and check the archive's declared name. Downloads use `curl` or `wget`
(that is how https registries work, independent of whether Caelix itself was built with TLS). There is no hosted public registry, no
dependency resolution between packages, and no signature verification beyond the checksum.

## Other limits

- Strings are bytes: `length("é")` is 2.
- Map keys must be Strings. Missing keys on `m.x` / `m["x"]` are errors.
- Recursion limit 2000 calls (a catchable error).
- No multiple inheritance, anonymous functions or `finally`.
- Module exports are a snapshot of the module's variables taken after it runs.
