forge-lang 0.3.2

Forge — Internet-native programming language with natural syntax, bytecode VM, and built-in HTTP/database/crypto
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
<p align="center">
  <h1 align="center">⚒️ Forge</h1>
  <p align="center"><strong>The internet-native programming language.</strong></p>
  <p align="center">Built-in HTTP, databases, crypto, AI, and a JIT compiler. Write less. Build more.</p>
</p>

<p align="center">
  <a href="https://github.com/humancto/forge-lang/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/humancto/forge-lang/actions/workflows/ci.yml/badge.svg"></a>
  <a href="https://github.com/humancto/forge-lang/releases"><img alt="Release" src="https://img.shields.io/github/v/release/humancto/forge-lang?style=flat-square&color=blue"></a>
  <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-green?style=flat-square"></a>
  <a href="https://www.rust-lang.org/"><img alt="Built with Rust" src="https://img.shields.io/badge/built_with-Rust-orange?style=flat-square"></a>
  <img alt="Tests" src="https://img.shields.io/badge/tests-822_passing-brightgreen?style=flat-square">
  <a href="https://github.com/humancto/forge-lang/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/humancto/forge-lang?style=flat-square"></a>
  <a href="https://crates.io/crates/forge-lang"><img alt="crates.io" src="https://img.shields.io/crates/v/forge-lang?style=flat-square"></a>
</p>

---

## Table of Contents

- [Quick Example]#quick-example
- [What Is Forge?]#what-is-forge
- [Installation]#installation
- [Why Forge?]#why-forge
- [Quick Tour]#quick-tour
- [Performance]#performance
- [Standard Library]#standard-library
- [CLI]#cli
- [Examples]#examples
- [Architecture]#architecture
- [Editor Support]#editor-support
- [Project Status]#project-status
- [Known Limitations]#known-limitations-v030
- [Roadmap]#roadmap
- [Contributing]#contributing
- [Community]#community
- [License]#license

---

## Quick Example

A REST API in Forge:

```forge
@server(port: 3000)

@get("/hello/:name")
fn hello(name: String) -> Json {
    return { greeting: "Hello, {name}!" }
}
```

```bash
forge run api.fg
curl http://localhost:3000/hello/World
# → {"greeting": "Hello, World!"}
```

No framework. No dependencies. No setup.

---

## What Is Forge?

Forge is a programming language where HTTP, databases, crypto, and terminal UI are **built into the runtime** — not added through packages.

```forge
say "Hello, World!"

let users = db.query("SELECT * FROM users")
term.table(users)

let hash = crypto.sha256("password")
say hash

let resp = fetch("https://api.example.com/data")
say resp.json.name
```

Every line above runs without a single import or install. 16 standard library modules, 230+ built-in functions, zero external dependencies needed.

It also reads like English — or like code. Both work:

```forge
// Natural syntax                        // Classic syntax
set name to "Forge"                      let name = "Forge"
say "Hello, {name}!"                     println("Hello, {name}!")
define greet(who) { }                    fn greet(who) { }
if ready { } otherwise { }              if ready { } else { }
repeat 3 times { }                       for i in range(0, 3) { }
```

---

## Installation

**Latest: v0.3.0** — install via any method below.

### Cargo (Rust)

```bash
cargo install forge-lang
```

Requires [Rust 1.85+](https://rustup.rs/). Published on [crates.io](https://crates.io/crates/forge-lang).

### Homebrew (macOS & Linux)

```bash
brew install humancto/tap/forge
```

### Install script

```bash
curl -fsSL https://raw.githubusercontent.com/humancto/forge-lang/main/install.sh | bash
```

### From source

```bash
git clone https://github.com/humancto/forge-lang.git
cd forge-lang
cargo install --path .
```

### Verify

```bash
forge version          # check installation
forge learn            # 30 interactive tutorials
forge                  # start REPL
```

---

## Why Forge?

Modern backend development requires installing dozens of packages before writing a single line of logic:

```bash
pip install flask requests sqlalchemy bcrypt python-dotenv pydantic ...
```

Forge:

```bash
forge run app.fg
```

| Problem                     | Forge                                                   |
| --------------------------- | ------------------------------------------------------- |
| HTTP requires a framework   | `@server` + `@get` — 3 lines                            |
| Database needs an ORM       | `db.query("SELECT * FROM users")` — built in            |
| Crypto needs a library      | `crypto.sha256("data")` — built in                      |
| JSON needs parsing          | `json.parse(text)` — built in                           |
| CSV needs pandas            | `csv.read("data.csv")` — built in                       |
| Shell scripts are fragile   | `sh("whoami")`, `shell("cmd \| grep x")` — built in     |
| Terminal UIs need ncurses   | `term.table(data)`, `term.sparkline(vals)` — built in   |
| Error handling is bolted on | `Result` types with `?` propagation — it's the language |
| Learning a language is slow | `forge learn` — 30 interactive lessons in your terminal |

---

## Quick Tour

### Variables

```forge
let name = "Forge"              // immutable
let mut count = 0               // mutable
count += 1

set language to "Forge"         // natural syntax
set mut score to 0
change score to score + 10
```

### Functions

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

define greet(name) {
    say "Hello, {name}!"
}

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

### Output — The Fun Trio

```forge
say "Normal volume"              // standard output
yell "LOUD AND PROUD!"          // UPPERCASE + !
whisper "quiet and gentle"       // lowercase + ...
```

### Control Flow

```forge
if score > 90 { say "A" }
otherwise if score > 80 { say "B" }
otherwise { say "C" }

let label = when temp {
    > 100 -> "Boiling"
    > 60  -> "Warm"
    else  -> "Cold"
}
```

### Loops

```forge
for item in [1, 2, 3] { say item }

for each color in ["red", "green", "blue"] {
    say color
}

repeat 5 times { say "hello" }

while count < 10 { count += 1 }
```

### Collections

```forge
let nums = [1, 2, 3, 4, 5]
let evens = nums.filter(fn(x) { x % 2 == 0 })
let doubled = evens.map(fn(x) { x * 2 })
say doubled   // [4, 8]

let user = { name: "Alice", age: 30, "Content-Type": "json" }
say user.name
say pick(user, ["name"])
say has_key(user, "email")
```

### Error Handling

```forge
fn safe_divide(a, b) {
    if b == 0 { return Err("division by zero") }
    return Ok(a / b)
}

let result = safe_divide(10, 0)
match result {
    Ok(val) => say "Got: {val}"
    Err(msg) => say "Error: {msg}"
}

// Propagate with ?
fn compute(input) {
    let n = parse_int(input)?
    return Ok(n * 2)
}
```

### Innovation Keywords

```forge
safe { risky_function() }                // returns null on error
let r = safe { might_fail() }           // safe as expression
must parse_config("app.toml")            // crash with clear message on error
check email is not empty                 // declarative validation
retry 3 times { fetch("https://api.example.com") }  // automatic retry
timeout 5 seconds { long_operation() }   // enforced time limit
wait 2 seconds                           // sleep with units
```

### Pattern Matching & ADTs

```forge
type Shape = Circle(Float) | Rect(Float, Float)

let s = Circle(5.0)
match s {
    Circle(r) => say "Area = {3.14 * r * r}"
    Rect(w, h) => say "Area = {w * h}"
}
```

---

## Performance

Forge has three execution tiers:

| Engine      | fib(30) | vs Python      | Best For                    |
| ----------- | ------- | -------------- | --------------------------- |
| `--jit`     | 10ms    | **11x faster** | Compute-heavy hot functions |
| `--vm`      | 252ms   | 2.2x slower    | General bytecode execution  |
| Interpreter | 2,300ms | 20x slower     | Full feature set + stdlib   |

The JIT compiles hot functions to native code via [Cranelift](https://cranelift.dev/), placing Forge alongside Node.js/V8 in recursive benchmarks.

<details>
<summary>Full cross-language benchmark (fib(30))</summary>

| Language                | Time     | Relative |
| ----------------------- | -------- | -------- |
| Rust 1.91 (-O)          | 1.46ms   | baseline |
| C (clang -O2)           | 1.57ms   | ~1.1x    |
| Go 1.23                 | 4.24ms   | ~2.9x    |
| Scala 2.12 (JVM)        | 4.33ms   | ~3.0x    |
| Java 1.8 (JVM)          | 5.77ms   | ~4.0x    |
| JavaScript (Node 22/V8) | 9.53ms   | ~6.5x    |
| **Forge (JIT)**         | **10ms** | **~7x**  |
| Python 3                | 114ms    | ~79x     |
| Forge (VM)              | 252ms    | ~173x    |
| Forge (interpreter)     | 2,300ms  | ~1,575x  |

</details>

---

## Standard Library

16 modules. No imports needed.

### HTTP Server

```forge
@server(port: 3000)

@get("/users/:id")
fn get_user(id: String) -> Json {
    return db.query("SELECT * FROM users WHERE id = " + id)
}

@post("/users")
fn create_user(body: Json) -> Json {
    db.execute("INSERT INTO users (name) VALUES (\"" + body.name + "\")")
    return { created: true }
}
```

### HTTP Client

```forge
let resp = fetch("https://api.github.com/repos/rust-lang/rust")
say resp.json.stargazers_count

let data = http.post("https://httpbin.org/post", { name: "Forge" })
say data.status
```

### Database (SQLite + PostgreSQL)

```forge
db.open(":memory:")
db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
db.execute("INSERT INTO users (name) VALUES (\"Alice\")")
let users = db.query("SELECT * FROM users")
term.table(users)
db.close()
```

### Shell Integration

```forge
say sh("whoami")                           // quick stdout
let files = sh_lines("ls /etc | head -5")  // stdout as array
if sh_ok("which docker") { say "Docker installed" }
let path = which("git")                    // find command path
let sorted = pipe_to(csv_data, "sort")     // pipe Forge data into commands
say cwd()                                  // working directory
```

### Crypto

```forge
say crypto.sha256("forge")
say crypto.base64_encode("secret")
say crypto.md5("data")
```

### File System

```forge
fs.write("config.json", json.stringify(data))
let content = fs.read("config.json")
say fs.exists("config.json")
say fs.list(".")
```

### Terminal UI

```forge
term.table(data)                   // formatted tables
term.sparkline([1, 5, 3, 8, 2])   // inline charts
term.bar("Progress", 75, 100)     // progress bars
say term.red("Error!")             // colored output
term.banner("FORGE")               // ASCII art
term.success("All tests passed!") // status messages
```

### All Modules

| Module   | What's In It                                                                                                                         |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `math`   | sqrt, pow, abs, sin, cos, tan, pi, e, random, random_int, clamp, floor, ceil, round                                                  |
| `fs`     | read, write, append, exists, list, mkdir, copy, rename, remove, size, lines, dirname, basename, join_path, is_dir, is_file, temp_dir |
| `crypto` | sha256, md5, base64_encode/decode, hex_encode/decode                                                                                 |
| `db`     | SQLite — open, query, execute, close                                                                                                 |
| `pg`     | PostgreSQL — connect, query, execute, close                                                                                          |
| `json`   | parse, stringify, pretty                                                                                                             |
| `csv`    | parse, stringify, read, write                                                                                                        |
| `regex`  | test, find, find_all, replace, split                                                                                                 |
| `env`    | get, set, has, keys                                                                                                                  |
| `log`    | info, warn, error, debug                                                                                                             |
| `term`   | colors, table, sparkline, bar, banner, box, gradient, countdown, confirm, menu                                                       |
| `http`   | get, post, put, delete, patch, head, download, crawl                                                                                 |
| `io`     | prompt, print, args_parse, args_get, args_has                                                                                        |
| `exec`   | run_command                                                                                                                          |
| `time`   | now, format, parse, sleep, elapsed                                                                                                   |
| `npc`    | name, email, username, phone, number, pick, bool, sentence, id, color, ip, url, company                                              |

---

## Object Helpers & Method Chaining

```forge
let user = { name: "Alice", age: 30, password: "secret" }

// Safe access with defaults
say get(user, "email", "N/A")                        // N/A
say get(resp, "json.user.profile.name", "unknown")   // deep dot-path, never crashes

// Transform objects
let public = pick(user, ["name", "age"])          // extract fields
let cleaned = omit(user, ["password"])             // remove fields
let config = merge({ port: 3000 }, { port: 8080 }) // merge (later wins)

// Search arrays
let admin = users.find(fn(u) { return u.role == "admin" })

// Chain operations
let names = users
    .filter(fn(u) { u.active })
    .map(fn(u) { u.name })
say names

// Check keys
say has_key(user, "email")
say contains(user, "name")
```

---

## CLI

| Command               | What It Does          |
| --------------------- | --------------------- |
| `forge run <file>`    | Run a program         |
| `forge`               | Start REPL            |
| `forge -e '<code>'`   | Evaluate inline       |
| `forge learn [n]`     | Interactive tutorials |
| `forge new <name>`    | Scaffold a project    |
| `forge test [dir]`    | Run tests             |
| `forge fmt [files]`   | Format code           |
| `forge build <file>`  | Compile to bytecode   |
| `forge install <src>` | Install a package     |
| `forge lsp`           | Language server       |
| `forge chat`          | AI assistant          |
| `forge version`       | Version info          |

---

## Examples

```bash
forge run examples/hello.fg        # basics
forge run examples/natural.fg      # natural syntax
forge run examples/api.fg          # REST API server
forge run examples/data.fg         # data processing + visualization
forge run examples/devops.fg       # system automation
forge run examples/showcase.fg     # everything in one file
forge run examples/functional.fg   # closures, recursion, higher-order
forge run examples/adt.fg          # algebraic data types + matching
forge run examples/result_try.fg   # error handling with ?
```

See [examples/](examples/) for the full list.

---

## Architecture

```
Source (.fg) → Lexer → Tokens → Parser → AST → Type Checker
                            ┌────────────────────────┼────────────────────────┐
                            ↓                        ↓                        ↓
                       Interpreter              Bytecode VM              JIT Compiler
                     (full features)           (--vm flag)             (--jit flag)
                            ↓                        ↓                        ↓
                     Runtime Bridge            Mark-Sweep GC          Cranelift Native
                  (axum, reqwest, tokio,       Green Threads              Code
                   rusqlite, postgres)
```

16,000+ lines of Rust. Zero `unsafe` blocks in application code. Built on:

| Crate                                              | Purpose         |
| -------------------------------------------------- | --------------- |
| [axum]https://github.com/tokio-rs/axum           | HTTP server     |
| [tokio]https://tokio.rs                          | Async runtime   |
| [reqwest]https://github.com/seanmonstar/reqwest  | HTTP client     |
| [cranelift]https://cranelift.dev/                | JIT compilation |
| [rusqlite]https://github.com/rusqlite/rusqlite   | SQLite          |
| [ariadne]https://github.com/zesterer/ariadne     | Error reporting |
| [rustyline]https://github.com/kkawakam/rustyline | REPL            |
| [clap]https://github.com/clap-rs/clap            | CLI             |

---

## Editor Support

### VS Code

Syntax highlighting is available in [editors/vscode/](editors/vscode/). To install locally:

```bash
cp -r editors/vscode ~/.vscode/extensions/forge-lang
```

### LSP

Forge ships with a built-in language server:

```bash
forge lsp
```

Configure your editor's LSP client to use `forge lsp` as the command.

---

## Project Status

Forge is v0.3.0. The language, interpreter, and standard library are stable and tested. The bytecode VM and JIT compiler are available via `--vm` and `--jit` flags.

| Metric                   | Value                |
| ------------------------ | -------------------- |
| Lines of Rust            | ~26,000              |
| Standard library modules | 16                   |
| Built-in functions       | 230+                 |
| Keywords                 | 80+                  |
| Tests                    | 488 Rust + 334 Forge |
| Interactive lessons      | 30                   |
| Example programs         | 12                   |
| Dependencies (CVEs)      | 280 crates (0 CVEs)  |

---

## Known Limitations (v0.3.0)

Forge is a young language. These are documented, not hidden:

- **No parameterized SQL queries** — use string concatenation for now. Be cautious with user input.
- **Three execution tiers with different trade-offs** — The interpreter supports all 230+ functions but is slower for compute-heavy recursion. Use `--jit` for hot-path performance (11x faster than Python) or `--vm` for bytecode execution. See [Performance]#performance for benchmarks.
- **VM/JIT feature gap** — The JIT and VM execute a subset of the language. Use the default interpreter for full stdlib, HTTP, database, and AI features.
- **`regex` functions** take `(text, pattern)` argument order, not `(pattern, text)`.

See [ROADMAP.md](ROADMAP.md) for what's coming next.

---

## Roadmap

| Version | Focus                                                                      |
| ------- | -------------------------------------------------------------------------- |
| v0.3    | 73 new functions, GenZ debug kit, NPC module, structured errors, 822 tests |
| v0.4    | Parameterized SQL, package registry, debugger                              |
| v0.5    | WASM target, expanded JIT coverage, LSP completions                        |
| v1.0    | Stable API, backwards compatibility guarantee                              |

See [ROADMAP.md](ROADMAP.md) for the full plan. Have ideas? [Open an issue](https://github.com/humancto/forge-lang/issues).

---

## Contributing

```bash
git clone https://github.com/humancto/forge-lang.git
cd forge-lang
cargo build && cargo test
forge run examples/showcase.fg
```

See [CONTRIBUTING.md](CONTRIBUTING.md) for the architecture guide, how to add features, and PR guidelines.

See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for community standards.

---

## Community

- [Issues]https://github.com/humancto/forge-lang/issues — Bug reports and feature requests
- [Discussions]https://github.com/humancto/forge-lang/discussions — Questions, ideas, show & tell
- [RFCs]rfcs/ — Language design proposals

---

## Security

To report a security vulnerability, please email the maintainers directly instead of opening a public issue. See [SECURITY.md](SECURITY.md) for details.

---

## License

[MIT](LICENSE)

---

<p align="center"><em>Stop installing. Start building.</em></p>