Metadata-Version: 2.4
Name: mo-language
Version: 0.2.0
Summary: Mo - Modern, Expressive, Fast Programming Language
Author-email: Qinghua <qinghua@example.com>
License: MIT
Project-URL: Homepage, https://github.com/qinghua/mo
Project-URL: Documentation, https://github.com/qinghua/mo#readme
Project-URL: Repository, https://github.com/qinghua/mo
Project-URL: Issues, https://github.com/qinghua/mo/issues
Project-URL: Changelog, https://github.com/qinghua/mo/blob/main/CHANGELOG.md
Keywords: programming-language,language,compiler,interpreter,scripting,mo,bytecode,llvm,webassembly
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Compilers
Classifier: Topic :: Software Development :: Interpreters
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Provides-Extra: llvm
Requires-Dist: llvmlite>=0.40.0; extra == "llvm"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio; extra == "dev"
Requires-Dist: black; extra == "dev"
Requires-Dist: flake8; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Provides-Extra: all
Requires-Dist: llvmlite>=0.40.0; extra == "all"

# Mo Language

Mo is a lightweight, dynamically-typed scripting language with a clean syntax, a bytecode compiler, and a growing standard library.

```mo
fn greet(name) {
    print("Hello, " + name + "!")
}

greet("world")
```

## Installation

```bash
pip install mo-language
```

After installing, use the `mo` command:

```bash
mo program.mo
```

> **Windows users:** If `mo` is not found after install, add Python's Scripts folder to your PATH.  
> **Mac/Linux users:** If `mo` is not found, run the command the installer prints.

## Language Guide

### Variables

```mo
let x = 42
let name = "Mo"
let flag = true
let nothing = null
```

Reassign with `=` (no `let`):

```mo
x = x + 1
```

### Types

| Type | Example |
|------|---------|
| Number | `3.14`, `100` |
| String | `"hello"` |
| Bool | `true`, `false` |
| Null | `null` |
| List | `[1, 2, 3]` |
| Dict | `{"key": "value"}` |

### Operators

```mo
1 + 2        # arithmetic: + - * /
x == y       # equality: == !=
x < y        # comparison: < > <= >=
true && false  # logical: && ||
!true          # not
```

String concatenation uses `+`:

```mo
let msg = "Hello, " + "world"
```

### Control Flow

```mo
if x > 0 {
    print("positive")
} else if x < 0 {
    print("negative")
} else {
    print("zero")
}
```

```mo
let i = 0
while i < 5 {
    print(i)
    i = i + 1
}
```

```mo
for item in [1, 2, 3] {
    print(item)
}
```

### Functions

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

let result = add(3, 4)   # 7
```

Functions are first-class values:

```mo
let double = fn(x) { return x * 2 }
```

### Lists

```mo
let nums = [10, 20, 30]
print(nums[0])          # 10
push(nums, 40)          # append
let last = pop(nums)    # remove last
print(len(nums))        # 3
```

### Dicts

```mo
let user = {"name": "Alice", "age": 30}
print(user["name"])     # Alice
user["age"] = 31

for k in keys(user) {
    print(k + ": " + str(user[k]))
}
```

Dict keys can also be accessed with `.`:

```mo
print(user.name)
user.age = 32
```

### Classes

```mo
class Animal {
    fn init(name) {
        self.name = name
    }
    fn speak() {
        print(self.name + " makes a sound")
    }
}

class Dog extends Animal {
    fn speak() {
        print(self.name + " barks")
    }
}

let d = Dog("Rex")
d.speak()   # Rex barks
```

### Error Handling

```mo
try {
    throw "something went wrong"
} catch e {
    print("Caught: " + e)
}
```

### Imports

```mo
import "std/math"
print(math_sqrt(16))   # 4.0
```

---

## Standard Library

All stdlib modules are imported with `import "std/<name>"`.

### `std/math`

```mo
import "std/math"

math_sqrt(x)      # square root
math_pow(x, n)    # power
math_abs(x)       # absolute value
math_floor(x)     # floor
math_ceil(x)      # ceiling
math_round(x)     # round
math_min(a, b)    # minimum
math_max(a, b)    # maximum
math_log(x)       # natural log
math_sin(x)       # sine (radians)
math_cos(x)       # cosine
math_tan(x)       # tangent
math_pi()         # π ≈ 3.14159
```

### `std/random`

```mo
import "std/random"

random_int(1, 10)      # random integer in [min, max]
random_float()         # random float in [0, 1)
random_pick([1,2,3])   # random element from list
```

### `std/time`

```mo
import "std/time"

time_now()              # Unix timestamp (float)
time_ms()               # milliseconds since epoch
time_sleep(1.5)         # sleep for N seconds
time_format(ts, fmt)    # format timestamp, e.g. "%Y-%m-%d"
time_str(ts)            # ISO date string
```

### `std/json`

```mo
import "std/json"

json_parse('{"a": 1}')      # string → dict/list
json_stringify(obj)          # dict/list → string
json_pretty(obj)             # pretty-printed string
```

### `std/file`

```mo
import "std/file"

read("file.txt")             # read file as string
write("file.txt", content)   # write string to file (overwrite)
append("file.txt", content)  # append to file
exists("file.txt")           # true/false
delete_file("file.txt")      # delete file
list_dir(".")                # list directory → list of names
```

### `std/http`

Requires no extra packages (uses Python's built-in `http.server`).

```mo
import "std/http"

serve(8080, fn(req) {
    return text("Hello, " + req.path)
})
```

Helper response builders:

```mo
text(body)           # 200 text/plain
html(body)           # 200 text/html
json_resp(data)      # 200 application/json
redirect(url)        # 302
not_found()          # 404
bad_request(msg)     # 400
error(msg)           # 500
```

HTTP client:

```mo
let res = fetch("https://example.com/api")
let res = fetch_post("https://example.com/api", json_stringify(data))
```

### `std/os`

```mo
import "std/os"

os_name()        # "posix" or "nt"
os_cwd()         # current working directory
os_home()        # home directory
os_env("PATH")   # environment variable value
os_cpus()        # number of CPU cores
```

### `std/path`

```mo
import "std/path"

path_join("dir", "file.txt")   # join path segments
path_dir("/a/b/c.txt")         # "/a/b"
path_base("/a/b/c.txt")        # "c.txt"
path_ext("/a/b/c.txt")         # ".txt"
path_abs("relative.txt")       # absolute path
```

### `std/url`

```mo
import "std/url"

url_parse("https://example.com/p?q=1")   # dict with host, path, query, …
url_encode("hello world")                 # "hello+world"
url_decode("hello+world")                 # "hello world"
```

### `std/process`

```mo
import "std/process"

proc_args()        # list of command-line arguments
proc_pid()         # current process ID
proc_exit(0)       # exit with code
proc_env("HOME")   # environment variable (alias for os_env)
```

### `std/crypto`

```mo
import "std/crypto"

crypto_md5("hello")      # hex digest string
crypto_sha1("hello")     # hex digest string
crypto_sha256("hello")   # hex digest string
```

---

## Built-in Functions

| Function | Description |
|----------|-------------|
| `print(x)` | Print value |
| `len(x)` | Length of string/list/dict |
| `str(x)` | Convert to string |
| `num(x)` | Convert to number |
| `type(x)` | Type name string |
| `range(n)` / `range(a,b)` | List of integers |
| `push(list, val)` | Append to list |
| `pop(list)` | Remove and return last element |
| `keys(dict)` | List of dict keys |
| `has(dict, key)` | True if key exists |
| `delete(dict, key)` | Remove key from dict |
| `input(prompt)` | Read line from stdin |
| `floor(x)` | Floor |
| `ceil(x)` | Ceil |
| `round(x)` | Round |
| `abs(x)` | Absolute value |

---

## Testing

### Run pytest Suite (Recommended)

```bash
pip install pytest
pytest tests/test_basic.py -v
```

The pytest suite covers core language features:
- Variables, operators, functions
- Lists, control flow (if/while/for)
- Exceptions (try/catch/throw)
- Built-in functions

### Run Python Test Runner

```bash
python tests/test_runner.py          # run all tests
python tests/test_runner.py -v       # verbose mode
python tests/test_runner.py test.mo   # run specific file
```

The test runner discovers `.mo` test files in `tests/`, runs them with `mo`, and checks exit code.

### Run Mo Test Files Directly

```bash
mo tests/run_tests.mo
```

Note: Some test files may have parser compatibility issues with newer language features.

Example test metadata file (`tests/foo.mo.meta.json`):
```json
{
  "exit_code": 0,
  "output": "42"
}
```

---

## CLI Reference

```bash
mo program.mo           # run with bytecode VM (default)
mo --interp program.mo  # run with tree-walk interpreter
mo --dis program.mo     # disassemble bytecode
mo                      # interactive REPL
```

---

## Requirements

- Python 3.9+
- No external dependencies (stdlib only)

`std/http` fetch functions use `urllib` (built-in). For advanced HTTP needs, install `requests` separately.

---

## Advanced Features

### Type System

```mo
let x: int = 42          # type annotation
let y = 10  # int         # type comment

is_number(x)              # check type
is_string(x)
is_bool(x)
is_list(x)
is_dict(x)

cast(x, "string")         # type cast
```

### `std/regex`

```mo
import "std/regex"

regex_match("^[a-z]+", "hello")   # true/false
regex_replace("cat", "the cat sat", "dog")  # "the dog sat"
regex_split("\\s+", "a b c")    # ["a", "b", "c"]
```

### `std/sqlite`

```mo
import "std/sqlite"

let db = sqlite_open("data.db")
let rows = sqlite_exec(db, "SELECT * FROM users WHERE age > ?", [18])

for row in rows {
    print(row["name"])
}

sqlite_close(db)
```

### `std/yaml`

```mo
import "std/yaml"

yaml_parse("key: value")       # string → dict
yaml_stringify({"key": "val"}) # dict → string
```

### `std/xml`

```mo
import "std/xml"

xml_parse("<root><item>text</item></root>")  # string → element
xml_to_string(elem)                     # element → string
```

### `std/csv`

```mo
import "std/csv"

csv_read("data.csv")                  # list of dicts
csv_write("output.csv", [{"a": "1"}])  # write list of dicts
```

### `std/net`

```mo
import "std/net"

let sock = net_listen(8080)

while true {
    let conn = net_accept(sock)
    let data = net_recv(conn)
    net_send(conn, "HTTP/1.0 200 OK\r\n\r\nHello")
    net_close(conn)
}
```

### `std/gui`

GUI module using Python's tkinter (requires `pip install pillow` for images).

```mo
import "std/gui"

let win = window("My Game", 800, 600)

rectangle(100, 100, 50, 50, "#00ff00")
circle(300, 200, 30, "#ff0000")
text(100, 160, "Player", 16, "#ffffff")
line(0, 0, 800, 600, "#888888")

on_click(fn(pos) {
    print("Clicked at: " + str(pos))
})

on_key(fn(key) {
    print("Pressed: " + key)
})

loop()
```

### `std/audio`

```mo
import "std/audio"

audio_play("sound.mp3")
```

---

## Package Manager

Mo has a package ecosystem for sharing reusable modules.

### Search packages

```bash
mo search redis
mo search http
```

### Install packages

```bash
mo install user/repo           # from GitHub
mo install user/repo@v1.0.0    # specific version
mo install https://example.com/foo.mo  # direct URL
```

### List installed packages

```bash
mo list
```

### Remove a package

```bash
mo remove <package-name>
```

### Publish a package

```bash
mo publish
```

See `mo publish` for detailed publishing instructions.

---

## LSP (Language Server Protocol)

Mo includes an LSP server for IDE editor support (hover, completion, diagnostics).

### Start LSP Server

```bash
mo lsp                    # Start via stdio
mo lsp --stdio            # Explicit stdio mode
mo lsp --tcp --port 8765  # TCP mode on port 8765
```

### VS Code Extension

A VS Code extension scaffold is provided in `mo-vlang/`:

- `package.json` - VS Code extension configuration
- `syntaxes/mo.tmLanguage.json` - Syntax highlighting
- `src/extension.ts` - LSP client

To install the extension:

```bash
cd mo-vlang
npm install
code .
# Press F5 to run the extension in development mode
```

### Supported Features

- **Hover**: Hover over variables to see their type
- **Completion**: Auto-complete keywords and symbols
- **Diagnostics**: Real-time syntax error reporting
