Moonlang
MoonLang is a lightweight static programming language built with C++ and LLVM, featuring dual syntax styles (`: end` and `{ }`). Supports Windows, Linux, macOS and embedded platforms (ARM/RISC-V/ESP32), compiles to only 15KB-300KB, build full-stack applications from MCU to desktop.
Install / Use
/learn @8dks/MoonlangREADME
MoonLang Compiler (C++ Source)
English | 中文 · Official site: moon-lang.com
MoonLang is a lightweight static programming language implemented in C++ with LLVM. It supports dual syntax styles (: end and { }), and runs on Windows, Linux, macOS, and embedded platforms (ARM/RISC-V/ESP32). Compiled binaries are 15KB–300KB, suitable for MCU to desktop applications.
This repository contains compiler source only (frontend + LLVM backend + runtime). It does not include the standard library .moon files, examples, or executables.
Contents
- Supported features
- Examples
- Syntax overview
- Deploying and using moonc
- Building this repository
- Build scripts
- Directory layout
- License and copyright
Supported features
The runtime provides a full set of built-in capabilities. Modules can be disabled at build time via MOON_NO_XXX or at compile time via moonc --no-xxx for smaller binaries.
Language & types
| Area | Description |
|------|-------------|
| Types | int, float, string, bool, null, list, dict, functions, classes, closures, BigInt (arbitrary precision) |
| Literals | Hex 0x, binary 0b, octal 0o; list/dict literals; multi-line strings |
| Operators | Arithmetic, comparison, logical, bitwise (& \| ^ ~ << >>), power ^, string concat |
| Control flow | if/elif/else, while, for-in, for-to, switch, break, continue |
| Functions | Named functions, lambdas, default args, closures, variadic-style via list |
| OOP | Classes, inheritance, super, self, constructors init |
| Modules | import "path" as name, from "path" import a, b |
| Errors | Try/catch/finally, throw, exception value |
I/O & filesystem
| Function / area | Description |
|-----------------|-------------|
| Console | print, input |
| Files | read_file, write_file, append_file (binary-safe) |
| Paths | exists, is_file, is_dir, list_dir, create_dir, file_size, getcwd, cd |
| Path utils | join_path, basename, dirname, extension, absolute_path, copy_file, move_file, remove_file, remove_dir |
Date & time
| Area | Description |
|------|-------------|
| Time | time, now (ms), unix_time, sleep |
| Format/parse | date_format, date_parse with format string and optional timezone |
| Components | year, month, day, hour, minute, second, millisecond, weekday, day_of_year, week_of_year, quarter |
| Arithmetic | make_time, add_seconds/minutes/hours/days/months/years, diff_seconds, diff_days |
| Ranges | start_of_day, end_of_day, start_of_month, end_of_month |
| Helpers | days_in_month, is_leap_year, is_weekend, is_today, is_same_day, timezone, utc_offset, set_timezone |
Math & numbers
| Area | Description |
|------|-------------|
| Basic | abs, min, max, pow, sqrt, floor, ceil, round, sign, clamp, lerp |
| Trig | sin, cos, tan, asin, acos, atan, atan2, degrees, radians |
| Log/exp | log, log10, log2, exp, sinh, cosh, tanh, hypot |
| Stats | mean, median (on list) |
| Random | random_int, random_float |
Strings & bytes
| Area | Description |
|------|-------------|
| String ops | len, substring, split, join, replace, trim, upper, lower, capitalize, title, contains, starts_with, ends_with, index_of, find, repeat, chr, ord |
| Predicates | is_alpha, is_digit, is_alnum, is_space, is_lower, is_upper |
| Padding | pad_left, pad_right, ltrim, rtrim |
| Binary | bytes_to_string (byte list → string), strings are binary-safe (length stored in header) |
| WebSocket | ws_parse_frame, ws_create_frame (low-level frame parse/create) |
Lists & dicts
| Area | Description |
|------|-------------|
| List | Index, set, append, insert, pop, remove, len, slice, contains, index_of, reverse, sort, sum, first, last, take, drop, shuffle, choice, unique, flatten, zip, count |
| Functional | list_map, list_filter, list_reduce (with callback) |
| Dict | get, set, has_key, keys, values, items, delete, merge |
| Range | range(n) or range(start, end) or range(start, end, step) |
Network
| Area | Description |
|------|-------------|
| TCP | tcp_connect, tcp_listen, tcp_accept, tcp_send, tcp_recv, tcp_close; non-blocking: tcp_set_nonblocking, tcp_has_data, tcp_select, tcp_accept_nonblocking, tcp_recv_nonblocking |
| UDP | udp_socket, udp_bind, udp_send, udp_recv, udp_close |
| TLS (OpenSSL) | tls_connect, tls_listen, tls_accept, tls_send, tls_recv, tls_recv_all, tls_close; verify/hostname, cert/key/CA load, tls_wrap_client / tls_wrap_server |
Controlled by MOON_HAS_NETWORK; TLS by MOON_HAS_TLS (optional OpenSSL). On Windows: IOCP/WSAPoll; on Linux: epoll.
GUI
| Area | Description |
|------|-------------|
| Basic | gui_init, gui_create, gui_show, gui_set_title, gui_set_size, gui_set_position, gui_close, gui_run, gui_quit, gui_alert, gui_confirm |
| Advanced | gui_create_advanced (options: frameless, transparent, topmost, resizable, etc.), WebView: gui_load_url, gui_load_html, gui_on_message (JS ↔ MoonLang bridge) |
| Tray | gui_tray_create, gui_tray_remove, gui_tray_set_menu, gui_tray_on_click, gui_show_window |
- Windows: WebView2 (embedded Chromium).
- Linux: WebKitGTK.
- macOS: WKWebView.
Controlled by MOON_HAS_GUI. Disabled in --target=embedded and --target=mcu.
Regular expressions
| Area | Description |
|------|-------------|
| Match | regex_match, regex_search, regex_test, regex_groups, regex_named, regex_find_all, regex_find_all_groups |
| Replace | regex_replace, regex_replace_all |
| Split | regex_split, regex_split_n |
| Compiled | regex_compile, then regex_match_compiled, regex_search_compiled, regex_find_all_compiled, regex_replace_compiled, regex_free |
| Utils | regex_escape, regex_error |
Uses PCRE2. Disable with --no-regex or MOON_NO_REGEX.
JSON
| Function | Description |
|----------|-------------|
| json_encode | Value → JSON string |
| json_decode | JSON string → value (list/dict/number/string/bool/null) |
Disable with --no-json or MOON_NO_JSON.
Async & concurrency
| Area | Description |
|------|-------------|
| Async | async(fn, ...args) — run on coroutine pool; yield; wait_all; num_goroutines, num_cpu |
| Channels | Go-style: chan() or chan(n) (buffered), chan_send, chan_recv, chan_close, chan_is_closed |
| Timers | set_timeout(callback, ms), set_interval(callback, ms), clear_timer(id) |
| Sync | mutex(), lock, unlock, trylock, mutex_free; Atomics: atomic_counter(initial), atomic_add, atomic_get, atomic_set, atomic_cas |
Controlled by MOON_HAS_ASYNC. Disabled in --target=mcu.
DLL & FFI
| Area | Description |
|------|-------------|
| DLL | dll_load(path), dll_close, dll_func(handle, name); call: dll_call_int, dll_call_double, dll_call_str, dll_call_void; alloc_str / free_str for C strings; ptr_to_str, read_ptr, read_int32, write_ptr, write_int32 |
| FFI | Declare C signatures in source; call C functions and pass/return values. |
Controlled by MOON_HAS_DLL / MOON_HAS_FFI. Disabled in --target=mcu.
System & misc
| Area | Description |
|------|-------------|
| Process | argv, env, set_env, exit, shell, shell_output, platform, getpid, system, exec |
| Format | format(fmt, ...) (sprintf-style) |
| Memory (MCU) | mem_stats, mem_reset, target_info |
| GC | Reference counting + cycle collection; gc_collect, gc_enable, gc_set_threshold, gc_stats |
Hardware (HAL, embedded)
When built with HAL (e.g. ESP32, Raspberry Pi Pico, STM32):
| Area | Description |
|------|-------------|
| GPIO | gpio_init(pin, mode), gpio_write, gpio_read, gpio_deinit; modes: INPUT, OUTPUT, INPUT_PULLUP, INPUT_PULLDOWN |
| PWM | pwm_init(pin, freq), pwm_write(pin, duty), pwm_deinit |
| ADC | adc_init, adc_read, adc_deinit |
| I2C | i2c_init(sda, scl, freq), i2c_write(addr, data), i2c_read(addr, length), i2c_deinit |
| SPI | spi_init(mosi, miso, sck, freq), spi_transfer(data), spi_deinit |
| UART | uart_init(tx, rx, baud), uart_write, uart_read, uart_available, uart_deinit |
| Time | delay_ms, delay_us, millis, micros |
| System | hal_init_runtime, hal_deinit_runtime, hal_platform_name, hal_debug_print |
Controlled by MOON_HAS_HAL (optional).
Build-time feature flags
| Flag / target | Effect |
|---------------|--------|
| Default | Full: GUI, network, TLS, regex, JSON, filesystem, float, DLL, async |
| --target=embedded | No GUI; network and rest available |
| `--target=m
