1
0
Fork 0
forked from fun/fun

Added base64 example. Lot of refactoring. (0.37.49)

This commit is contained in:
Johannes Findeisen 2026-01-14 01:57:57 +01:00
commit 75538e6142
17 changed files with 439 additions and 45 deletions

View file

@ -0,0 +1,31 @@
#!/usr/bin/env fun
/*
* This file is part of the Fun programming language.
* https://fun-lang.xyz/
*
* Copyright 2025 Johannes Findeisen <you@hanez.org>
* Licensed under the terms of the Apache-2.0 license.
* https://opensource.org/license/apache-2-0
*
* Added: 2025-11-25
*/
/*
* Demonstrates curl_get and JSON.parse working together.
*/
url = "https://httpbin.org/json"
resp = curl_get(url)
print("Raw length: " + to_string(len(resp)))
// If JSON support is enabled, parse it
obj = json_parse(resp)
if obj != nil
print("Title: " + obj["slideshow"]["title"])
/* Expected output:
Raw length: 429
Title: Sample Slide Show
*/

57
examples/extra/curl_post.fun Executable file
View file

@ -0,0 +1,57 @@
#!/usr/bin/env fun
/*
* This file is part of the Fun programming language.
* https://fun-lang.xyz/
*
* Copyright 2025 Johannes Findeisen <you@hanez.org>
* Licensed under the terms of the Apache-2.0 license.
* https://opensource.org/license/apache-2-0
*
* Added: 2025-11-25
*/
/*
* Demonstrates curl_post sending form data and printing response.
*/
url = "https://httpbin.org/post"
data = "name=Fun&lang=fun"
resp = curl_post(url, data)
print("Response: " + resp)
// If JSON support is enabled, parse it
obj = json_parse(resp)
if obj != nil
print("Content-Type: " + to_string(obj["headers"]["Content-Type"]))
if obj != nil
print("Host: " + to_string(obj["headers"]["Host"]))
if obj != nil
print("Origin: " + to_string(obj["origin"]))
// Possible output:
// Response: {
// "args": {},
// "data": "",
// "files": {},
// "form": {
// "lang": "fun",
// "name": "Fun"
// },
// "headers": {
// "Accept": "*/*",
// "Content-Length": "17",
// "Content-Type": "application/x-www-form-urlencoded",
// "Host": "httpbin.org",
// "X-Amzn-Trace-Id": "Root=1-6944834b-74f499e251c322713e7dd9a8"
// },
// "json": nil,
// "origin": "5.252.226.107",
// "url": "https://httpbin.org/post"
// }
//
// Content-Type: application/x-www-form-urlencoded
// Host: httpbin.org
// Origin: 5.252.226.107

107
examples/extra/json_showcase.fun Executable file
View file

@ -0,0 +1,107 @@
#!/usr/bin/env fun
/*
* This file is part of the Fun programming language.
* https://fun-lang.xyz/
*
* Copyright 2025 Johannes Findeisen <you@hanez.org>
* Licensed under the terms of the Apache-2.0 license.
* https://opensource.org/license/apache-2-0
*
* Added: 2025-11-24
*/
// Demonstrates JSON.parse/stringify/from_file/to_file via the stdlib JSON class.
include <io/json.fun>
json = JSON()
print("-- JSON: parse from string and pretty print --")
// Build a sample JSON text with most value types
sample = '{"name":"Ada","active":true,"score":99.5,"count":42,"tags":["C","Ada","Math"],"extra":null}'
obj = json.parse(sample)
print("Dump:")
print(obj)
print(obj["name"]) // Ada
print(obj["active"]) // 1
print(obj["count"]) // 42
print(len(obj["tags"])) // 3
pretty = json.stringify(obj, 1)
print(pretty)
print("-- JSON: load from file, inspect, and save pretty to /tmp --")
// Load non existent json file
path = "examples/data/nonexistent.json"
cfg = json.from_file(path)
print("Dump:")
print(cfg)
// Load a more complex example shipped with the repo
path = "examples/data/complex.json"
cfg = json.from_file(path)
print("Dump:")
print(cfg)
// Access nested fields
print(cfg["project"]["name"]) // project name
print(cfg["project"]["version"]) // version string
print(len(cfg["users"])) // number of users
// Derive a small summary map
summary = {}
summary["user_count"] = len(cfg["users"])
summary["first_user_name"] = cfg["users"][1]["name"]
summary["features_enabled"] = cfg["features"]["enabled"]
print(json.stringify(summary, 1))
// Write the loaded config back as pretty JSON
out_path = "/tmp/fun_complex_out.json"
ok = json.to_file(out_path, cfg, 1)
print(ok) // 1 on success
/* Expected output:
-- JSON: parse from string and pretty print --
Dump:
{"name": Ada, "active": true, "score": 99.5, "count": 42, "tags": [C, Ada, Math], "extra": nil}
Ada
true
42
3
{
"name":"Ada",
"active":true,
"score":99.5,
"count":42,
"tags":[
"C",
"Ada",
"Math"
],
"extra":null
}
-- JSON: load from file, inspect, and save pretty to /tmp --
Dump:
nil
Dump:
{"project": {"name": Fun, "version": 0.27.2, "website": https://fun-lang.xyz, "license": {"name": Apache-2.0, "url": https://opensource.org/license/apache-2-0}}, "features": {"enabled": [arrays, maps, json, pcsc], "experimental": {"repl": true, "sockets": true, "odbc": false, "notes": nil}}, "users": [{"id": 1, "name": Ada, "roles": [admin, math], "active": true, "score": 99.5, "prefs": {"theme": dark, "editor": {"tabWidth": 2, "font": Fira Code}}}, {"id": 2, "name": Linus, "roles": [user, kernel], "active": false, "score": 88, "prefs": {"theme": light, "editor": {"tabWidth": 8, "font": Monospace}}}], "metrics": {"counters": [0, 1, 1, 2, 3, 5, 8], "latency_ms": {"p50": 1.23, "p90": 3.21, "p99": 12.34}, "builds": 1234567890123456789, "last_release_ts": 1732406400000}, "matrix": [[1, 2, 3], [4, 5, 6], [7, 8, 9]], "notes": UTF-8 emojis: 🚀🔥, "null_field": nil}
Fun
0.27.2
2
{
"user_count":2,
"first_user_name":"Linus",
"features_enabled":[
"arrays",
"maps",
"json",
"pcsc"
]
}
1
*/

View file

@ -0,0 +1,46 @@
#!/usr/bin/env fun
/*
* This file is part of the Fun programming language.
* https://fun-lang.xyz/
*
* Copyright 2025 Johannes Findeisen <you@hanez.org>
* Licensed under the terms of the Apache-2.0 license.
* https://opensource.org/license/apache-2-0
*
* Added: 2026-01-03
*/
/*
* Minimal Notcurses hello example.
*/
include <ui/notcurses.fun>
n = Notcurses()
if n.init() == 0
print("Notcurses not available. Rebuild with -DFUN_WITH_NOTCURSES=ON.")
exit(0)
n.clear()
n.draw_text(2, 0, "Fun + Notcurses")
n.draw_text(4, 0, "Press any key to exit...")
// blocking until key
_ = n.getch(0)
n.shutdown()
/* Possible output:
A TUI.
After exit:
3 renders, 991,14µs (223,57µs min, 330,38µs avg, 531,91µs max)
3 rasters, 320,76µs (106,45µs min, 106,92µs avg, 107,72µs max)
3 writes, 198,26µs (62,54µs min, 66,09µs avg, 69,94µs max)
59B (0B min, 19B avg, 30B max) 1 input Ghpa: 0
0 failed renders, 0 failed rasters, 0 refreshes, 0 input errors
RGB emits:elides: def 1:38 fg 0:0 bg 0:0
Cell emits:elides: 39:74805 (99,95%) 97,44% 0,00% 0,00%
Bmap emits:elides: 0:0 (0,00%) 0B (0,00%) SuM: 0 (0,00%)
*/

214
examples/extra/pcre2_opcodes.fun Executable file
View file

@ -0,0 +1,214 @@
#!/usr/bin/env fun
/*
* This file is part of the Fun programming language.
* https://fun-lang.xyz/
*
* Copyright 2025 Johannes Findeisen <you@hanez.org>
* Licensed under the terms of the Apache-2.0 license.
* https://opensource.org/license/apache-2-0
*
* Added: 2025-11-25
*/
// PCRE2 example using VM builtins directly (no class wrapper)
// Requires building Fun with -DFUN_WITH_PCRE2=ON
print("-- PCRE2 builtins (no class) --")
pattern = "(\\w+)" // capture a word
text = "Hello 123 world"
// Flags: 1=I, 2=M, 4=S, 8=U (UTF), 16=X; well use UTF by default
flags = 8
print("test:")
print(pcre2_test(pattern, text, flags))
m = pcre2_match(pattern, text, flags)
if (m != nil)
print("first full:")
print(m["full"])
print("span:")
print(m["start"])
print("..")
print(m["end"])
print("groups count:")
print(len(m["groups"]))
all = pcre2_findall("\\w+", text, flags)
for x in all
print("all:")
print(x["full"])
print("@")
print(x["start"])
print("..")
print(x["end"])
print("")
print("-- More regex demos --")
// Helper: OR flags (uses VM bor opcode)
fun OR(a, b)
return bor(a, b)
// Demo 1: E-mail extraction (case-insensitive)
email_text = "E-mails: one@example.com, Two@Example.COM; invalid: x@y"
email_pat = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
email_flags = OR(flags, 1) // UTF | I
print("Emails (findall):")
emails = pcre2_findall(email_pat, email_text, email_flags)
for e in emails
print(e["full"])
// Demo 2: URLs (very simple, for demo purposes)
url_text = "See http://example.com and https://fun-lang.xyz/docs?x=1#top"
url_pat = "https?://[A-Za-z0-9._~:/?#[@]!$&'()*+,;=%-]+"
print("URLs:")
for u in pcre2_findall(url_pat, url_text, flags)
print(u["full"])
// Demo 3: IPv4 addresses
ip_text = "ping 8.8.8.8 and 192.168.0.1; not 999.999.999.999"
ip_pat = "(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)"
print("IPv4:")
for ip in pcre2_findall(ip_pat, ip_text, flags)
print(ip["full"])
// Demo 4: Dates (YYYY-MM-DD)
date_text = "Born 1999-12-31, updated 2025-11-25, bad 2025-13-40"
date_pat = "(\\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])"
print("Dates (with groups Y/M/D):")
for d in pcre2_findall(date_pat, date_text, flags)
print(d["full"])
print(join(d["groups"], "/"))
// Demo 5: Hex colors (#RRGGBB)
color_text = "Palette: #FF00FF, #1a2b3c, not #abcd or #12345g"
color_pat = "#[0-9A-Fa-f]{6}"
print("Hex colors:")
for c in pcre2_findall(color_pat, color_text, flags)
print(c["full"])
// Demo 6: Quoted strings with escapes
q_text = 'say "hi there" and "indented" plus "quote\\"inside"'
q_pat = '"([^"\\\\]|\\\\.)*"'
print("Quoted strings (with escapes):")
for q in pcre2_findall(q_pat, q_text, flags)
print(q["full"])
// Demo 7: Multiline anchors with /m (M flag)
ml_text = "first line\nSecond line\nthird"
ml_pat = "^(\\w+)"
ml_flags = OR(flags, 2) // UTF | M
print("Multiline ^ anchors (first token of each line):")
for ml in pcre2_findall(ml_pat, ml_text, ml_flags)
print(ml["full"])
// Demo 8: Dotall vs non-dotall
ds_text = "BEGIN\nline1\nline2\nEND"
pat_nd = "BEGIN.*END" // default: . does not match newlines
pat_ds = "BEGIN.*END" // with DOTALL, it does
print("Dotall OFF (should fail):")
print(pcre2_test(pat_nd, ds_text, flags))
print("Dotall ON (should match):")
print(pcre2_test(pat_ds, ds_text, OR(flags, 4)))
// Demo 9: Word boundaries and case-insensitive find
wb_text = "The theater and the THE can differ."
wb_pat = "\\bthe\\b"
print("Word boundary, case-insensitive:")
for w in pcre2_findall(wb_pat, wb_text, OR(flags, 1))
print(w["full"])
// Demo 10: Lookahead word followed by number
la_text = "foo 123, bar, baz 9"
la_pat = "\\w+(?=\\s+\\d+)"
print("Lookahead (word before number):")
for a in pcre2_findall(la_pat, la_text, flags)
print(a["full"])
// Demo 11: Non-greedy vs greedy
ng_text = "<a>one</a><a>two</a>"
greedy = "<a>.*</a>"
lazy = "<a>.*?</a>"
print("Greedy:")
for g in pcre2_findall(greedy, ng_text, OR(flags, 4)) // DOTALL ensures '.' covers any
print(g["full"])
print("Non-greedy:")
for l in pcre2_findall(lazy, ng_text, OR(flags, 4))
print(l["full"])
/* Expected output:
-- PCRE2 builtins (no class) --
test:
1
first full:
Hello
span:
0
..
5
groups count:
1
all:
Hello
@
0
..
5
all:
123
@
6
..
9
all:
world
@
10
..
15
-- More regex demos --
Emails (findall):
one@example.com
Two@Example.COM
URLs:
IPv4:
8.8.8.8
192.168.0.1
Dates (with groups Y/M/D):
1999-12-31
1999/12/31
2025-11-25
2025/11/25
Hex colors:
#FF00FF
#1a2b3c
Quoted strings (with escapes):
"hi there"
"indented"
"quote\"inside"
Multiline ^ anchors (first token of each line):
first
Second
third
Dotall OFF (should fail):
0
Dotall ON (should match):
1
Word boundary, case-insensitive:
The
the
THE
Lookahead (word before number):
foo
baz
Greedy:
<a>one</a><a>two</a>
Non-greedy:
<a>one</a>
<a>two</a>
*/

83
examples/extra/pcsc_example.fun Executable file
View file

@ -0,0 +1,83 @@
#!/usr/bin/env fun
/*
* This file is part of the Fun programming language.
* https://fun-lang.xyz/
*
* Copyright 2025 Johannes Findeisen <you@hanez.org>
* Licensed under the terms of the Apache-2.0 license.
* https://opensource.org/license/apache-2-0
*
* Added: 2025-10-02
*/
// Minimal PCSC example for Fun language
// Establish context and list readers (prints [] if none or unsupported)
// This example is very smartcard specific, but it works in my test environment.
// The card I am using is a german "eTicket" (local transport ticket).
//include <hex.fun>
include <io/pcsc.fun>
p = PCSC()
readers = p.get_readers()
number rc = len(readers)
print("Found " + to_string(rc) + " readers:")
for i in range(0, rc)
print(" " + to_string(i+1) + ". " + readers[i])
print("Dump:")
print(readers)
// Select Applet
string apdu = "00a4040c0cD2760001354B414E4D30310000"
print("Transmit APDU (Select Applet): " + apdu)
result = p.transmit(apdu)
print("Response:")
print(" Data: " + to_string(len(result["data"])) + " bytes")
print(" SW1: " + to_string(result["sw1"]))
print(" SW2: " + to_string(result["sw2"]))
print(" Code: " + to_string(result["code"]))
print("Dump:")
print(result)
// Call the random number generator (RNG)
apdu = "0084000008"
print("Transmit APDU (Call the random number generator (RNG): " + apdu)
result = p.transmit(apdu)
print("Response:")
print(" Data: " + to_string(len(result["data"])) + " bytes")
print(" SW1: " + to_string(result["sw1"]))
print(" SW2: " + to_string(result["sw2"]))
print(" Code: " + to_string(result["code"]))
print("Dump:")
print(result)
/* Possible output:
Found 2 readers:
1. OMNIKEY CardMan (076B:5321) 5321 00 00
2. OMNIKEY CardMan (076B:5321) 5321 00 01
Dump:
[OMNIKEY CardMan (076B:5321) 5321 00 00, OMNIKEY CardMan (076B:5321) 5321 00 01]
Transmit APDU (Select Applet): 00a4040c0cD2760001354B414E4D30310000
Response:
Data: 251 bytes
SW1: 144
SW2: 0
Code: 0
Dump:
{"data": [224, 129, 248, 226, 24, 192, 1, 1, 129, 15, 0, 0, 5, 250, 136, 243, 17, 36, 236, 105, 135, 46, 236, 105, 135, 128, 2, 7, 131, 228, 7, 192, 1, 2, 130, 2, 0, 162, 231, 3, 192, 1, 3, 236, 29, 192, 1, 4, 134, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 135, 2, 0, 0, 195, 2, 1, 9, 144, 16, 9, 8, 7, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 233, 29, 192, 1, 9, 131, 20, 0, 0, 0, 1, 136, 243, 41, 106, 136, 142, 136, 42, 38, 33, 139, 156, 45, 30, 191, 125, 132, 2, 7, 1, 233, 29, 192, 1, 8, 131, 20, 0, 0, 0, 1, 136, 243, 41, 106, 136, 142, 136, 42, 38, 33, 139, 156, 45, 30, 191, 125, 132, 2, 7, 1, 233, 29, 192, 1, 7, 131, 20, 0, 0, 0, 1, 136, 243, 41, 106, 136, 142, 136, 42, 38, 33, 139, 156, 45, 30, 191, 125, 132, 2, 7, 1, 233, 29, 192, 1, 6, 131, 20, 0, 0, 15, 22, 136, 243, 31, 143, 136, 142, 136, 42, 37, 55, 0, 1, 47, 55, 191, 125, 132, 2, 7, 1, 233, 29, 192, 1, 5, 131, 20, 0, 0, 15, 21, 136, 243, 7, 216, 136, 143, 136, 42, 37, 55, 0, 1, 37, 58, 191, 125, 132, 2, 7, 1], "sw1": 144, "sw2": 0, "code": 0}
Transmit APDU (Call the random number generator (RNG): 0084000008
Response:
Data: 8 bytes
SW1: 144
SW2: 0
Code: 0
Dump:
{"data": [25, 179, 169, 196, 57, 36, 89, 139], "sw1": 144, "sw2": 0, "code": 0}
*/