plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
bf629a2
— Peter John
2026-09-03T19:47:08+05:30
feat(plum): trait conformance checking, Stringable->ToStr, finish str.plum
Generated files not shown: Cargo.lock, plum-runtime/Cargo.lock
- README.md +5 -2
- examples/types.plum +1 -1
- libs/std/buffer.plum +1 -1
- libs/std/http.plum +156 -22
- libs/std/list.plum +2 -2
- libs/std/map.plum +3 -3
- libs/std/option.plum +1 -1
- libs/std/result.plum +1 -1
- libs/std/str.plum +96 -7
- libs/std/time.plum +1 -1
- libs/std/uuid.plum +1 -1
- plum-checker/src/lib.rs +114 -2
- plum-checker/src/monomorphize.rs +19 -3
- plum-checker/tests/checker_tests.rs +126 -0
- plum-cli/Cargo.toml +1 -0
- plum-cli/src/main.rs +48 -0
- plum-runtime/Cargo.toml +1 -0
- plum-runtime/src/main.rs +43 -0
- test/sample.plum +1 -1
- tooling/tree-sitter-plum/test/corpus/type.txt +1 -1
- website/src/content/docs/declarations/enum.md +1 -1
- website/src/content/docs/index.mdx +2 -2
README.md
CHANGED
|
@@ -234,7 +234,7 @@ type Point =
|
|
|
234
234
|
x: Int
|
|
235
235
|
y: Int
|
|
236
236
|
|
|
237
|
-
type Named(
|
|
237
|
+
type Named(ToStr) = # implements ToStr
|
|
238
238
|
name: Str
|
|
239
239
|
|
|
240
240
|
trait Shape =
|
|
@@ -253,6 +253,8 @@ enum Option =
|
|
|
253
253
|
|
|
254
254
|
Full example: [`examples/types.plum`](examples/types.plum).
|
|
255
255
|
|
|
256
|
+
`type X(TraitName, ...) = ...`'s trait claims are checked: `plum-checker` verifies `X` actually defines every method `TraitName` declares, with a matching param count/types and return type (a return/param type the trait itself can't parameterize, like `Err`'s `cause() -> Option`, matches any concrete instantiation an implementer declares, e.g. `Option[MyError]`). A trait name that isn't actually declared anywhere (`Comparable`/`Readable`/`Writable` are used this way in a few places in `libs/std` today) is silently unenforced rather than an error, since there's nothing real yet to check it against.
|
|
257
|
+
|
|
256
258
|
### Generics
|
|
257
259
|
|
|
258
260
|
Generic type parameters are single letters only: `a`, `b`, `c`, `d`.
|
|
@@ -389,7 +391,8 @@ hello, world!
|
|
|
389
391
|
Some things parse and type-check but don't compile to wasm yet — `plum-wasm-codegen` reports a clear error rather than silently producing wrong code:
|
|
390
392
|
|
|
391
393
|
- interpolating a `Float` value in a string (`Str`/`Int`/`Bool` interpolation, and plain non-interpolated literals, all compile) — correct decimal formatting of a float is a substantial separate undertaking (something like Grisu/Ryu), scoped out for now
|
|
392
|
-
- The generic-field-type gap that used to block `libs/std`'s real `List[T]`/`Node[T]` from compiling at all (a class/enum-variant field declared with a concrete instantiation of another generic type, e.g. `Node.next: Option[Node]`) is fixed — `List[T]`'s methods (`get`/`length`/`add`/`set`/`removeAt`/`remove`/`clear`/`reverse`/`each`/`map`/`reduce`/`sort`/`join`, including its `
|
|
394
|
+
- The generic-field-type gap that used to block `libs/std`'s real `List[T]`/`Node[T]` from compiling at all (a class/enum-variant field declared with a concrete instantiation of another generic type, e.g. `Node.next: Option[Node]`) is fixed — `List[T]`'s methods (`get`/`length`/`add`/`set`/`removeAt`/`remove`/`clear`/`reverse`/`each`/`map`/`reduce`/`sort`/`join`, including its `ToStr`-bounded dispatch) are exercised directly, at their real generic type, by the `test` blocks at the bottom of [`libs/std/list.plum`](libs/std/list.plum) itself (run via `plum test libs/std/list.plum`) — not a non-generic stand-in.
|
|
393
395
|
- `Map[K, V]` previously hit a *different* bug here: a top-level function whose own declared return type was a fully-concrete generic instantiation (e.g. `fun makeMap() -> Map[Str, Int] = ...`) caused monomorphization to eagerly (and incorrectly) attempt to specialize an unrelated generic type's method (`Option.filter`) at an unresolved type variable, producing a spurious `expected Option, found Option$V` type error even though `filter` was never called anywhere in the program. Root cause: `maybeRewriteReturn` (in `plum-checker/src/monomorphize.rs`) treated ANY return type merely NAMING a known generic class/enum as still-unresolved and in need of rewriting from the body's inferred tail type — even when that name already carried concrete type args (`List[Str]`, `Map[Str, Int]`), clobbering an already-correct declared return type with a stale, unmangled one inferred through tables monomorphization hadn't finished refreshing yet. Fixed by only treating a BARE reference (no `[...]` at all, e.g. `-> Box`) as needing that rewrite; a companion fix pre-resolves every ordinary (non-generic) fn/method's signature into the type tables before any body rewriting begins, so cross-file call order no longer matters. `Option.andThen`/`Result.map`/`Result.mapErr` (a single extra generic, possibly nested inside a closure's return type) are now implemented and working. `Map.map` (needing TWO new generic params nested inside a closure's return type, on a class rather than an enum) is now implemented too, once `specializeFn` was fixed to also substitute a method's own extra generics inside its BODY (not just its params/return) — an explicit bracketed construction like `Map[X, Y](items: ...)` written directly in a method's own body previously kept the literal letters "X"/"Y" forever, silently minting bogus specializations that corrupted unrelated template compilation elsewhere in the program. A second, narrower gap remains: a closure-literal argument whose body does field access on its own param (`|p| cb(p.key, p.val)`) still can't type-check once more than one specialization of the same generic class shares that field name (e.g. both `Pair$Str$Int` and `Pair$Str$Str` declare `key`/`val`) — the checker's field-usage heuristic for inferring a closure param's class becomes ambiguous and gives up; `Map.map`'s own body sidesteps this by using a manual linked-list walk (matching `keys`/`values`/`each`'s existing style) instead of `List.map` with a field-accessing closure
|
|
394
396
|
- A generic class/enum method whose return type nests that SAME class/enum inside itself (`List[T].chunk(self) -> List[List[T]]`) used to stack-overflow the compiler for every program merely importing the class, whether or not anything called the method — fixed; `List.chunk`/`List.partition` now ship and work as a working example of the pattern (build any inner `List[T]` value via an EXISTING ordinary method, e.g. `self.sublist(...)`, never a second bare `List(...)` construction in the same body, which is ambiguous with the method's own return-type fallback)
|
|
395
397
|
- A ternary as a closure's own inline body (`|n| cond ? a : b`) used to parse as an OUTER ternary wrapping the whole closure instead (`(|n| cond) ? a : b`) — a grammar shift/reduce ambiguity where `closure`'s default precedence (0) beat `ternary_expression`'s deliberately-low `PREC.conditional` (-1) at the point the parser decides whether to keep extending the closure's body or reduce it as already-complete. Fixed by giving `closure` its own even-lower precedence (`PREC.closure = -2`, `tooling/tree-sitter-plum/grammar.js`) so the parser now always prefers letting a ternary (or anything else valid there) keep extending the closure's inline body — see `examples/closures.plum`'s `"closure with an inline ternary body runs correctly"` test.
|
|
398
|
+
- `libs/std/str.plum` is otherwise complete (including `endsWith`/`pad`/`truncate`, filled in alongside the `ToStr`-conformance work below), but three methods remain deliberately unimplemented `todo` stubs (they compile fine and trap at runtime if actually called, rather than failing to compile — a different flavor of gap than the rest of this section): `test`/`matchPattern`/`matchAll`/`replace`/`replaceAll`/`search` all need a real `Regex` type/engine, which doesn't exist anywhere in `libs/std` yet; `deburr` (diacritic stripping, `é` -> `e`) needs a full Unicode decomposition table; `template` (lodash's `_.template`) needs the ability to compile and run Plum source from a `Str` value at runtime — there's no `eval`/dynamic-codegen capability in the language to build it on.
|
examples/types.plum
CHANGED
|
@@ -2,7 +2,7 @@ type Point =
|
|
|
2
2
|
x: Int
|
|
3
3
|
y: Int
|
|
4
4
|
|
|
5
|
-
type Named(
|
|
5
|
+
type Named(ToStr) =
|
|
6
6
|
name: Str
|
|
7
7
|
|
|
8
8
|
type Box[T] =
|
libs/std/buffer.plum
CHANGED
|
@@ -12,7 +12,7 @@ import std/str
|
|
|
12
12
|
# `bytes.Buffer`'s asymptotic behavior — unlike the previous `Str`-backed
|
|
13
13
|
# version of this type, which recopied everything written so far on every
|
|
14
14
|
# write.
|
|
15
|
-
type Buffer(
|
|
15
|
+
type Buffer(ToStr) =
|
|
16
16
|
data: []Byte
|
|
17
17
|
len: Int
|
|
18
18
|
|
libs/std/http.plum
CHANGED
|
@@ -1,28 +1,162 @@
|
|
|
1
1
|
module std
|
|
2
2
|
|
|
3
|
+
import std/buffer
|
|
4
|
+
import std/json
|
|
5
|
+
import std/list
|
|
3
|
-
import std/
|
|
6
|
+
import std/map
|
|
7
|
+
import std/option
|
|
8
|
+
import std/result
|
|
4
|
-
import std/
|
|
9
|
+
import std/str
|
|
5
|
-
import std/http/content_type
|
|
6
10
|
|
|
11
|
+
# An HTTP response: status code, response headers, and the raw response
|
|
12
|
+
# body as a `Str` (a byte array, so binary bodies round-trip intact).
|
|
7
13
|
type Response =
|
|
8
|
-
headers: Map(Str, Str)
|
|
9
|
-
body: Buffer
|
|
10
14
|
status: Int
|
|
15
|
+
headers: Map[Str, Str]
|
|
16
|
+
body: Str
|
|
11
17
|
|
|
18
|
+
# 2xx status codes are success; everything else (redirects, 4xx, 5xx) is
|
|
19
|
+
# surfaced here rather than as an `Err` from `request` — a non-2xx
|
|
12
|
-
#
|
|
20
|
+
# response is still a complete, well-formed HTTP exchange, not a failed
|
|
13
|
-
# NOTE: the original used a `Response::create()` fluent builder chain
|
|
14
|
-
# (`.header(...).contentType(...).body(...).status(...)`), but this language has
|
|
15
|
-
# no "::" static-call syntax and no mutating "with"-style builder methods, so
|
|
16
|
-
# this constructs the Response directly instead.
|
|
17
|
-
|
|
21
|
+
# one (`request` itself only fails for transport-level problems like a
|
|
18
|
-
content := content_type.fromExt(file_path.ext())
|
|
19
|
-
|
|
22
|
+
# DNS/connection error).
|
|
20
|
-
Response(headers: Map(), body: data, status: 200)
|
|
21
|
-
|
|
22
|
-
fun
|
|
23
|
+
fun ok(self) -> Bool =
|
|
24
|
+
self.status >= 200 && self.status < 300
|
|
25
|
+
|
|
26
|
+
# Parses `body` as JSON. Fails the same way `Json.fromStr` does for a
|
|
27
|
+
# response body that isn't valid JSON.
|
|
28
|
+
fun json(self) -> Result[Json, JsonParseError] =
|
|
29
|
+
return Json.fromStr(self.body)
|
|
30
|
+
|
|
31
|
+
fun emptyHeaders() -> Map[Str, Str] =
|
|
32
|
+
return Map[Str, Str](items: List[Pair[Str, Str]](head: None, tail: None, size: 0))
|
|
33
|
+
|
|
34
|
+
# A single blocking network round trip — this VM has no async/event-loop
|
|
35
|
+
# mechanism, so `rawHttpRequest` runs to completion before returning (same
|
|
36
|
+
# idea as `libs/std/os.plum`'s `rawReadFile`). `headers` is `"Key: Value"`
|
|
37
|
+
# lines joined by `\n` (`""` for none). The result packs an outcome flag,
|
|
38
|
+
# then either the status code and response headers (success) or an error
|
|
39
|
+
# message (failure), as fields joined by `\x01`, up to the first `\x00` —
|
|
40
|
+
# everything after that byte is the raw response body. `\x00`/`\x01` can
|
|
41
|
+
# never occur in the metadata fields themselves (the flag/status are
|
|
42
|
+
# decimal digits, header names/values and the error message are always
|
|
43
|
+
# plain text), so they safely mark where the opaque body bytes start even
|
|
44
|
+
# when the body itself is arbitrary binary data.
|
|
45
|
+
extern fun rawHttpRequest(method: Str, url: Str, headers: Str, body: Str) -> Str
|
|
46
|
+
|
|
47
|
+
# Packs `headers` into the `"Key: Value"`-per-line format `rawHttpRequest`
|
|
48
|
+
# expects for its own `headers` argument.
|
|
49
|
+
fun encodeHeaders(headers: Map[Str, Str]) -> Str =
|
|
50
|
+
buf := Buffer()
|
|
51
|
+
headers.each(|k, v|
|
|
52
|
+
if buf.length() > 0
|
|
23
|
-
|
|
53
|
+
buf.write("\n")
|
|
24
|
-
|
|
54
|
+
buf.write(k)
|
|
55
|
+
buf.write(": ")
|
|
56
|
+
buf.write(v))
|
|
57
|
+
return buf.toStr()
|
|
58
|
+
|
|
59
|
+
# The reverse of `encodeHeaders`, for the response headers `rawHttpRequest`
|
|
60
|
+
# packs into its result.
|
|
25
|
-
fun
|
|
61
|
+
fun decodeHeaders(raw: Str) -> Map[Str, Str] =
|
|
62
|
+
result := emptyHeaders()
|
|
63
|
+
if raw == ""
|
|
64
|
+
return result
|
|
65
|
+
raw.split("\n", 0).each(|line|
|
|
66
|
+
idx := line.indexOf(": ")
|
|
67
|
+
if idx >= 0
|
|
68
|
+
key := line.sub(0, idx)
|
|
69
|
+
val := line.sub(idx + 2, line.length())
|
|
70
|
+
result.set(key, val))
|
|
71
|
+
return result
|
|
72
|
+
|
|
73
|
+
# Performs a single HTTP request and waits for the full response. Fails
|
|
74
|
+
# only for a transport-level problem (DNS failure, connection refused, TLS
|
|
75
|
+
# error, ...) — an HTTP-level error status (404, 500, ...) is still a
|
|
76
|
+
# successful round trip, returned as `Ok(Response(...))` with that status
|
|
77
|
+
# (check `Response.ok()`).
|
|
78
|
+
fun request(method: Str, url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, Str] =
|
|
79
|
+
raw := rawHttpRequest(method, url, encodeHeaders(headers), body)
|
|
80
|
+
sep := raw.indexOf("\x00")
|
|
81
|
+
meta := sep >= 0 ? raw.sub(0, sep) : raw
|
|
82
|
+
resp_body := sep >= 0 ? raw.sub(sep + 1, raw.length()) : ""
|
|
83
|
+
parts := meta.split("\x01", 3)
|
|
84
|
+
flag := parts.get(0).unwrapOr("")
|
|
85
|
+
if flag != "1"
|
|
86
|
+
return Err(parts.get(2).unwrapOr("http request failed"))
|
|
87
|
+
match Int.fromStr(parts.get(1).unwrapOr(""))
|
|
88
|
+
Ok(status) =>
|
|
89
|
+
return Ok(Response(status: status, headers: decodeHeaders(parts.get(2).unwrapOr("")), body: resp_body))
|
|
90
|
+
Err(e) =>
|
|
91
|
+
return Err("invalid status code in http response: {e}")
|
|
92
|
+
|
|
93
|
+
fun get(url: Str, headers: Map[Str, Str]) -> Result[Response, Str] =
|
|
94
|
+
return request("GET", url, headers, "")
|
|
95
|
+
|
|
96
|
+
fun head(url: Str, headers: Map[Str, Str]) -> Result[Response, Str] =
|
|
97
|
+
return request("HEAD", url, headers, "")
|
|
98
|
+
|
|
99
|
+
fun delete(url: Str, headers: Map[Str, Str]) -> Result[Response, Str] =
|
|
100
|
+
return request("DELETE", url, headers, "")
|
|
101
|
+
|
|
102
|
+
fun post(url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, Str] =
|
|
103
|
+
return request("POST", url, headers, body)
|
|
104
|
+
|
|
105
|
+
fun put(url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, Str] =
|
|
106
|
+
return request("PUT", url, headers, body)
|
|
107
|
+
|
|
108
|
+
fun patch(url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, Str] =
|
|
109
|
+
return request("PATCH", url, headers, body)
|
|
110
|
+
|
|
111
|
+
# Convenience wrapper: sends `body` as a JSON `Str`, adding a
|
|
112
|
+
# `Content-Type: application/json` header, and parses the response back as
|
|
113
|
+
# JSON via `Response.json()`.
|
|
114
|
+
fun postJson(url: Str, headers: Map[Str, Str], body: Json) -> Result[Response, Str] =
|
|
115
|
+
headers.set("Content-Type", "application/json")
|
|
116
|
+
return post(url, headers, body.toStr())
|
|
117
|
+
|
|
118
|
+
test "encodeHeaders/decodeHeaders round-trip a header map"
|
|
119
|
+
h := emptyHeaders()
|
|
120
|
+
h.set("Content-Type", "application/json")
|
|
121
|
+
h.set("Accept", "*/*")
|
|
26
|
-
|
|
122
|
+
decoded := decodeHeaders(encodeHeaders(h))
|
|
123
|
+
expect decoded.get("Content-Type").unwrap() == "application/json"
|
|
124
|
+
expect decoded.get("Accept").unwrap() == "*/*"
|
|
125
|
+
|
|
27
|
-
|
|
126
|
+
test "decodeHeaders returns an empty map for an empty string"
|
|
28
|
-
|
|
127
|
+
expect decodeHeaders("").isEmpty() == True
|
|
128
|
+
|
|
129
|
+
test "get performs a real HTTP round trip"
|
|
130
|
+
match get("https://httpbin.org/get", emptyHeaders())
|
|
131
|
+
Ok(resp) =>
|
|
132
|
+
expect resp.ok() == True
|
|
133
|
+
expect resp.status == 200
|
|
134
|
+
Err(_) =>
|
|
135
|
+
expect True == False
|
|
136
|
+
|
|
137
|
+
test "get reports a non-2xx status without failing the request"
|
|
138
|
+
match get("https://httpbin.org/status/404", emptyHeaders())
|
|
139
|
+
Ok(resp) =>
|
|
140
|
+
expect resp.ok() == False
|
|
141
|
+
expect resp.status == 404
|
|
142
|
+
Err(_) =>
|
|
143
|
+
expect True == False
|
|
144
|
+
|
|
145
|
+
test "post sends a body and the server echoes it back"
|
|
146
|
+
match post("https://httpbin.org/post", emptyHeaders(), "hello world")
|
|
147
|
+
Ok(resp) =>
|
|
148
|
+
expect resp.ok() == True
|
|
149
|
+
match resp.json()
|
|
150
|
+
Ok(j) =>
|
|
151
|
+
expect j.asMap().unwrap().get("data").unwrap().asStr().unwrap() == "hello world"
|
|
152
|
+
Err(_) =>
|
|
153
|
+
expect True == False
|
|
154
|
+
Err(_) =>
|
|
155
|
+
expect True == False
|
|
156
|
+
|
|
157
|
+
test "request fails for an unreachable host"
|
|
158
|
+
match get("http://this-host-does-not-exist.invalid/", emptyHeaders())
|
|
159
|
+
Ok(_) =>
|
|
160
|
+
expect True == False
|
|
161
|
+
Err(_) =>
|
|
162
|
+
expect True == True
|
libs/std/list.plum
CHANGED
|
@@ -12,7 +12,7 @@ type Node[T] =
|
|
|
12
12
|
|
|
13
13
|
# A list is a data structure describing a contiguous section of an array stored separately from the slice variable itself.
|
|
14
14
|
# It contains the pointers to the start and end nodes (head, tail) and maintains the size as well
|
|
15
|
-
type List[T:
|
|
15
|
+
type List[T: ToStr](ToStr) =
|
|
16
16
|
head: Option[Node[T]]
|
|
17
17
|
tail: Option[Node[T]]
|
|
18
18
|
size: Int
|
|
@@ -460,7 +460,7 @@ type List[T: Stringable](Stringable) =
|
|
|
460
460
|
break
|
|
461
461
|
res.toStr()
|
|
462
462
|
|
|
463
|
-
# `List[T:
|
|
463
|
+
# `List[T: ToStr](ToStr)` declared implementing `ToStr`
|
|
464
464
|
# from the start but never actually defined `toStr` — harmless for a
|
|
465
465
|
# PLAIN `List[Int]`/`List[Str]`/etc (nothing needs to call `.toStr()` on
|
|
466
466
|
# the LIST ITSELF, just on its elements, which `join` above already
|
libs/std/map.plum
CHANGED
|
@@ -7,11 +7,11 @@ import std/option
|
|
|
7
7
|
# `toStr` (unlike `Option`'s — see `libs/std/option.plum`'s note on
|
|
8
8
|
# `toOptionStr`) IS safe as an ordinary method here: `Pair[K, V]` is only
|
|
9
9
|
# ever used as `List[Pair[K, V]]`'s element type inside `Map[K, V]`, and
|
|
10
|
-
# `List[T:
|
|
10
|
+
# `List[T: ToStr]` already requires its own `T` to support `toStr` —
|
|
11
|
-
# so a `Pair` used as a `List` element always has `K`/`V:
|
|
11
|
+
# so a `Pair` used as a `List` element always has `K`/`V: ToStr` too,
|
|
12
12
|
# and `List`'s own eagerly-compiled `join`/`toStr` (which call `.toStr()` on
|
|
13
13
|
# every element) need this to exist for every `Map` specialization anyway.
|
|
14
|
-
type Pair[K, V](
|
|
14
|
+
type Pair[K, V](ToStr) =
|
|
15
15
|
key: K
|
|
16
16
|
val: V
|
|
17
17
|
|
libs/std/option.plum
CHANGED
|
@@ -112,7 +112,7 @@ enum Option =
|
|
|
112
112
|
# `toStr` — so an `Option.toStr` calling `.toStr()` on the wrapped value
|
|
113
113
|
# would fail to compile for THAT specialization even though nothing ever
|
|
114
114
|
# actually calls `.toStr()` on an `Option[Node[Int]]`. Use `toOptionStr`
|
|
115
|
-
# below (an explicit stringifier callback, not an implicit `T:
|
|
115
|
+
# below (an explicit stringifier callback, not an implicit `T: ToStr`
|
|
116
116
|
# bound) wherever printing an `Option` is needed.
|
|
117
117
|
fun toOptionStr(self, valueToStr: fn(T) -> Str) -> Str =
|
|
118
118
|
match self
|
libs/std/result.plum
CHANGED
|
@@ -116,7 +116,7 @@ enum Result =
|
|
|
116
116
|
|
|
117
117
|
# No implicit `toStr(self) -> Str` — see the identical note on
|
|
118
118
|
# `Option.toOptionStr` in `libs/std/option.plum`: a method that assumes
|
|
119
|
-
# `T`/`E:
|
|
119
|
+
# `T`/`E: ToStr` gets compiled for EVERY specialization of `Result`
|
|
120
120
|
# anywhere in the program (there's no lazy/on-demand method compilation),
|
|
121
121
|
# so an implicit bound like this can break an unrelated specialization
|
|
122
122
|
# whose payload doesn't support it. Explicit stringifier callbacks instead.
|
libs/std/str.plum
CHANGED
|
@@ -3,13 +3,13 @@ module std
|
|
|
3
3
|
import std/list
|
|
4
4
|
|
|
5
5
|
# Any type that can be converted to a str needs to implement this trait
|
|
6
|
-
trait
|
|
6
|
+
trait ToStr =
|
|
7
7
|
toStr() -> Str
|
|
8
8
|
|
|
9
9
|
# A Str is an array of contiguous data stored in memory with a null termination using hex 0x00 or ASCII 0x00.
|
|
10
10
|
# It is immutable and cannot be modified. It is copied for any changes and saved to a new memory location.
|
|
11
11
|
# The previous str is freed if its reference count is 0 within the block.
|
|
12
|
-
type Str(Comparable,
|
|
12
|
+
type Str(Comparable, ToStr, Readable, Writable) =
|
|
13
13
|
data: Buffer
|
|
14
14
|
|
|
15
15
|
# Number of bytes in the string. Every other method below is built on top of
|
|
@@ -104,6 +104,9 @@ type Str(Comparable, Stringable, Readable, Writable) =
|
|
|
104
104
|
fun startsWith(self, search: Str) -> Bool =
|
|
105
105
|
matchesAt(self, search, 0, search.length())
|
|
106
106
|
|
|
107
|
+
fun endsWith(self, search: Str) -> Bool =
|
|
108
|
+
matchesAt(self, search, self.length() - search.length(), search.length())
|
|
109
|
+
|
|
107
110
|
fun concat(self, other: Str) -> Str =
|
|
108
111
|
self + other
|
|
109
112
|
|
|
@@ -247,9 +250,28 @@ type Str(Comparable, Stringable, Readable, Writable) =
|
|
|
247
250
|
fun escapeRegExp(self) -> Str =
|
|
248
251
|
escapeRegExpFrom(self, 0, self.length())
|
|
249
252
|
|
|
253
|
+
# Pads BOTH sides of `self` with repeated copies of `sub` until its length
|
|
254
|
+
# is at least `count`, split as evenly as possible between the two sides
|
|
255
|
+
# (the left side gets any odd byte of the remainder, matching lodash's
|
|
256
|
+
# `_.pad`). Inherits `padStart`/`padEnd`'s own overshoot behavior when
|
|
257
|
+
# `sub` doesn't evenly divide the needed amount on either side.
|
|
250
|
-
fun pad(self) -> Str =
|
|
258
|
+
fun pad(self, sub: Str, count: Int) -> Str =
|
|
259
|
+
len := self.length()
|
|
260
|
+
if len >= count || sub.length() == 0
|
|
261
|
+
return self
|
|
262
|
+
total := count - len
|
|
263
|
+
left := total / 2
|
|
264
|
+
right := total - left
|
|
265
|
+
return self.padStart(sub, len + left).padEnd(sub, len + left + right)
|
|
266
|
+
|
|
267
|
+
# `template` (lodash's `_.template`) compiles a string containing
|
|
268
|
+
# `<%= expr %>`-style placeholders into a REUSABLE function that renders it
|
|
269
|
+
# against different data each call — that needs the ability to compile and
|
|
270
|
+
# run Plum source AT RUNTIME (from a `Str` value, not a `.plum` file), which
|
|
271
|
+
# the language has no way to do (no `eval`, no dynamic codegen from within
|
|
272
|
+
# a running program). Left as a known gap rather than a fundamentally
|
|
273
|
+
# different, simpler feature (e.g. a one-shot find/replace) under the same
|
|
251
|
-
|
|
274
|
+
# name.
|
|
252
|
-
|
|
253
275
|
fun template(self) -> Str =
|
|
254
276
|
todo
|
|
255
277
|
|
|
@@ -262,8 +284,17 @@ type Str(Comparable, Stringable, Readable, Writable) =
|
|
|
262
284
|
fun trimStart(self) -> Str =
|
|
263
285
|
trimStartFrom(self, 0, self.length())
|
|
264
286
|
|
|
287
|
+
# Truncates `self` to at most `length` bytes (INCLUDING the "..." suffix,
|
|
288
|
+
# lodash's default `omission` string) if it's longer than `length`; returns
|
|
289
|
+
# `self` unchanged otherwise. `length` too small to fit the full "..."
|
|
290
|
+
# itself just returns as many of its leading bytes as fit.
|
|
265
|
-
fun truncate(self) -> Str =
|
|
291
|
+
fun truncate(self, length: Int) -> Str =
|
|
292
|
+
if self.length() <= length
|
|
266
|
-
|
|
293
|
+
return self
|
|
294
|
+
omission := "..."
|
|
295
|
+
if length <= omission.length()
|
|
296
|
+
return omission.sub(0, length)
|
|
297
|
+
return self.sub(0, length - omission.length()) + omission
|
|
267
298
|
|
|
268
299
|
fun unescape(self) -> Str =
|
|
269
300
|
unescapeFrom(self, 0, self.length())
|
|
@@ -526,3 +557,61 @@ test "string interpolation supports a method call taking a closure literal"
|
|
|
526
557
|
test "string interpolation supports a ternary expression"
|
|
527
558
|
n := 5
|
|
528
559
|
expect "{n > 0 ? "positive" : "non-positive"}" == "positive"
|
|
560
|
+
|
|
561
|
+
# ---- Str method regression tests ----
|
|
562
|
+
|
|
563
|
+
test "endsWith matches a real suffix and rejects a non-suffix or an over-long search"
|
|
564
|
+
expect "hello.plum".endsWith(".plum") == True
|
|
565
|
+
expect "hello.plum".endsWith(".rs") == False
|
|
566
|
+
expect "hi".endsWith("hello") == False
|
|
567
|
+
|
|
568
|
+
test "startsWith/endsWith/contains/indexOf agree on a shared example"
|
|
569
|
+
s := "the quick brown fox"
|
|
570
|
+
expect s.startsWith("the") == True
|
|
571
|
+
expect s.endsWith("fox") == True
|
|
572
|
+
expect s.contains("quick") == True
|
|
573
|
+
expect s.indexOf("brown") == 10
|
|
574
|
+
expect s.indexOf("missing") == -1
|
|
575
|
+
|
|
576
|
+
test "trim/trimStart/trimEnd strip only leading/trailing whitespace"
|
|
577
|
+
expect " hi ".trim() == "hi"
|
|
578
|
+
expect " hi ".trimStart() == "hi "
|
|
579
|
+
expect " hi ".trimEnd() == " hi"
|
|
580
|
+
expect "hi".trim() == "hi"
|
|
581
|
+
|
|
582
|
+
test "repeat concatenates self count times, and is empty for count <= 0"
|
|
583
|
+
expect "ab".repeat(3) == "ababab"
|
|
584
|
+
expect "ab".repeat(0) == ""
|
|
585
|
+
expect "ab".repeat(-1) == ""
|
|
586
|
+
|
|
587
|
+
test "padStart/padEnd/pad grow a string to at least the target length"
|
|
588
|
+
expect "5".padStart("0", 3) == "005"
|
|
589
|
+
expect "5".padEnd("0", 3) == "500"
|
|
590
|
+
expect "hi".pad("-", 6) == "--hi--"
|
|
591
|
+
expect "hi".pad("-", 5) == "-hi--"
|
|
592
|
+
expect "hello".pad("-", 3) == "hello"
|
|
593
|
+
|
|
594
|
+
test "truncate shortens a too-long string with a trailing ellipsis"
|
|
595
|
+
expect "hello world".truncate(8) == "hello..."
|
|
596
|
+
expect "hi".truncate(8) == "hi"
|
|
597
|
+
expect "hello world".truncate(2) == ".."
|
|
598
|
+
|
|
599
|
+
test "toLower/upperCase/capitalize/lowerFirst/upperFirst case-convert as expected"
|
|
600
|
+
expect "Hello World".toLower() == "hello world"
|
|
601
|
+
expect "Hello World".upperCase() == "HELLO WORLD"
|
|
602
|
+
expect "hello".capitalize() == "Hello"
|
|
603
|
+
expect "Hello".lowerFirst() == "hello"
|
|
604
|
+
expect "hello".upperFirst() == "Hello"
|
|
605
|
+
|
|
606
|
+
test "camelCase/snakeCase/kebabCase/startCase convert a multi-word phrase"
|
|
607
|
+
expect "foo bar baz".camelCase() == "fooBarBaz"
|
|
608
|
+
expect "foo bar baz".snakeCase() == "foo_bar_baz"
|
|
609
|
+
expect "foo bar baz".kebabCase() == "foo-bar-baz"
|
|
610
|
+
expect "foo bar baz".startCase() == "Foo Bar Baz"
|
|
611
|
+
|
|
612
|
+
test "reverse reverses by character, not by raw byte"
|
|
613
|
+
expect "hello".reverse() == "olleh"
|
|
614
|
+
|
|
615
|
+
test "escape/unescape round-trip HTML-sensitive characters"
|
|
616
|
+
expect "<a href=\"x\">&'</a>".escape() == "<a href="x">&'</a>"
|
|
617
|
+
expect "<a href="x">&'</a>".unescape() == "<a href=\"x\">&'</a>"
|
libs/std/time.plum
CHANGED
|
@@ -6,7 +6,7 @@ import std/str
|
|
|
6
6
|
extern fun rawNowMillis() -> Int
|
|
7
7
|
|
|
8
8
|
# A single point in time, stored as milliseconds since the Unix epoch.
|
|
9
|
-
type Time(
|
|
9
|
+
type Time(ToStr) =
|
|
10
10
|
value: Int
|
|
11
11
|
|
|
12
12
|
fun toMillis(self) -> Int =
|
libs/std/uuid.plum
CHANGED
|
@@ -5,7 +5,7 @@ import std/str
|
|
|
5
5
|
|
|
6
6
|
# A UUID, stored as its canonical 36-character
|
|
7
7
|
# `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` text form.
|
|
8
|
-
type Uuid(
|
|
8
|
+
type Uuid(ToStr) =
|
|
9
9
|
value: Str
|
|
10
10
|
|
|
11
11
|
fun toStr(self) -> Str =
|
plum-checker/src/lib.rs
CHANGED
|
@@ -260,9 +260,111 @@ pub fn buildGlobalTables(source: &ast::Source) -> (TypeEnv, ClassEnv, MethodEnv,
|
|
|
260
260
|
(global_env, classes, methods, enum_variants, enum_params)
|
|
261
261
|
}
|
|
262
262
|
|
|
263
|
+
/// A `Type`'s name for comparison purposes only — deliberately ignores `.generics`
|
|
264
|
+
/// entirely (on both sides), so a trait's bare return/param type (`cause() ->
|
|
265
|
+
/// Option`, unable to name a concrete payload since a trait has no instance to
|
|
266
|
+
/// infer one from) is treated as compatible with ANY instantiation an implementer
|
|
267
|
+
/// declares (`cause(self) -> Option[JsonParseError]`) — a real but deliberately
|
|
268
|
+
/// coarse check (arity + base type names), not full structural/generic equality.
|
|
269
|
+
fn paramTypeCompareName(pt: &ast::ParamType) -> Option<&str> {
|
|
270
|
+
match pt {
|
|
271
|
+
ast::ParamType::Type(t) => Some(t.name.as_str()),
|
|
272
|
+
ast::ParamType::Variadic(t) => Some(t.name.as_str()),
|
|
273
|
+
// A function-value param type has no single "name" to compare — never
|
|
274
|
+
// matches a trait method's plain `Type` param either way, but no real
|
|
275
|
+
// trait in `libs/std` declares one today, so this never actually fires.
|
|
276
|
+
ast::ParamType::Fn(_, _) => None,
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/// Verifies every `type X(TraitName, ...) = ...` claim against `TraitName`'s own
|
|
281
|
+
/// declared methods — until now, `implements` was pure documentation with zero
|
|
282
|
+
/// enforcement (a class could claim any trait, real or not, and never define a
|
|
283
|
+
/// single one of its methods, with nothing ever catching it). A `TraitName` that
|
|
284
|
+
/// doesn't resolve to any declared `trait` in this source (e.g. `Comparable`,
|
|
285
|
+
/// `Readable`, `Writable` — used across `libs/std` but never actually declared
|
|
286
|
+
/// anywhere) is silently SKIPPED rather than an error: those names are still
|
|
287
|
+
/// purely aspirational today, and erroring on them would break every existing
|
|
288
|
+
/// type that names one, for reasons unrelated to whether it actually implements
|
|
289
|
+
/// its REAL trait claims. Runs on the pre-monomorphization source deliberately —
|
|
290
|
+
/// a generic class's own methods (and a real trait's own declared signatures,
|
|
291
|
+
/// which are never specialized at all) read naturally here, before mangling
|
|
292
|
+
/// folds a method's concrete return/param types into new, unrelated-looking
|
|
293
|
+
/// names (`Option[JsonParseError]` -> `Option$JsonParseError`).
|
|
294
|
+
fn checkTraitConformance(source: &ast::Source) -> Vec<CheckError> {
|
|
295
|
+
let mut errors = Vec::new();
|
|
296
|
+
let traits: BTreeMap<&str, &ast::Trait> = source.items.iter()
|
|
297
|
+
.filter_map(|i| match i { ast::Item::Trait(t) => Some((t.name.as_str(), t)), _ => None })
|
|
298
|
+
.collect();
|
|
299
|
+
let methods_by_receiver: BTreeMap<(&str, &str), &ast::Fn> = source.items.iter()
|
|
300
|
+
.filter_map(|i| match i {
|
|
301
|
+
ast::Item::Fn(f) => f.type_param.as_deref().map(|recv| ((recv, f.name.as_str()), f)),
|
|
302
|
+
_ => None,
|
|
303
|
+
})
|
|
304
|
+
.collect();
|
|
305
|
+
|
|
306
|
+
for item in &source.items {
|
|
307
|
+
let ast::Item::Class(c) = item else { continue };
|
|
308
|
+
for trait_name in &c.implements {
|
|
309
|
+
let Some(tr) = traits.get(trait_name.as_str()) else { continue };
|
|
310
|
+
for tm in &tr.methods {
|
|
311
|
+
let Some(f) = methods_by_receiver.get(&(c.name.as_str(), tm.name.as_str())) else {
|
|
312
|
+
errors.push(CheckError {
|
|
313
|
+
message: format!("class '{}' claims to implement trait '{}' but is missing method '{}'", c.name, trait_name, tm.name),
|
|
314
|
+
});
|
|
315
|
+
continue;
|
|
316
|
+
};
|
|
317
|
+
if f.params.len() != tm.params.len() {
|
|
318
|
+
errors.push(CheckError {
|
|
319
|
+
message: format!(
|
|
320
|
+
"class '{}' method '{}' (implementing trait '{}'): expected {} param(s), got {}",
|
|
321
|
+
c.name, tm.name, trait_name, tm.params.len(), f.params.len()
|
|
322
|
+
),
|
|
323
|
+
});
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
for (i, (fp, tp)) in f.params.iter().zip(tm.params.iter()).enumerate() {
|
|
327
|
+
let (actual, expected) = (paramTypeCompareName(&fp.ty), paramTypeCompareName(&tp.ty));
|
|
328
|
+
if actual != expected {
|
|
329
|
+
errors.push(CheckError {
|
|
330
|
+
message: format!(
|
|
331
|
+
"class '{}' method '{}' (implementing trait '{}'): param {} ('{}'): expected type '{}', got '{}'",
|
|
332
|
+
c.name, tm.name, trait_name, i, tp.name,
|
|
333
|
+
expected.unwrap_or("<fn>"), actual.unwrap_or("<fn>")
|
|
334
|
+
),
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
match (&f.returns, &tm.returns) {
|
|
339
|
+
(Some(ft), Some(tt)) if ft.name != tt.name => {
|
|
340
|
+
errors.push(CheckError {
|
|
341
|
+
message: format!(
|
|
342
|
+
"class '{}' method '{}' (implementing trait '{}'): expected return type '{}', got '{}'",
|
|
343
|
+
c.name, tm.name, trait_name, tt.name, ft.name
|
|
344
|
+
),
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
(None, Some(tt)) => {
|
|
348
|
+
errors.push(CheckError {
|
|
349
|
+
message: format!(
|
|
350
|
+
"class '{}' method '{}' (implementing trait '{}'): expected return type '{}', got none",
|
|
351
|
+
c.name, tm.name, trait_name, tt.name
|
|
352
|
+
),
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
_ => {}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
errors
|
|
361
|
+
}
|
|
362
|
+
|
|
263
363
|
pub fn checkSource(source: &ast::Source) -> CheckResult<()> {
|
|
364
|
+
// Runs against the ORIGINAL (pre-monomorphization) source, deliberately —
|
|
365
|
+
// see `checkTraitConformance`'s own doc comment for why.
|
|
366
|
+
let mut errors: Vec<CheckError> = checkTraitConformance(source);
|
|
264
367
|
let source = monomorphize::monomorphizeSource(source).map_err(|e| vec![CheckError { message: e }])?;
|
|
265
|
-
let mut errors: Vec<CheckError> = Vec::new();
|
|
266
368
|
let (global_env, classes, methods, enum_variants, enum_params) = buildGlobalTables(&source);
|
|
267
369
|
let min_required = buildMinRequiredArgs(&source);
|
|
268
370
|
let ctx = CheckCtx { classes: &classes, methods: &methods, enum_variants: &enum_variants, enum_params: &enum_params, min_required: &min_required };
|
|
@@ -1099,7 +1201,17 @@ pub fn inferExpr(expr: &ast::Expr, env: &TypeEnv, ctx: &CheckCtx) -> Result<Plum
|
|
|
1099
1201
|
None => Ok(PlumType::TVar("_".to_string())),
|
|
1100
1202
|
},
|
|
1101
1203
|
},
|
|
1204
|
+
// An unresolved generic method return (e.g. `Result[T, E].unwrap()`'s
|
|
1205
|
+
// bare `T`, which this checker's `PlumType` erases entirely — see
|
|
1206
|
+
// `types.rs`'s `TNamed` having no type-argument slot) reaches here as
|
|
1207
|
+
// a plain `TVar`, not a real "wrong type". Field access on it is
|
|
1208
|
+
// "unmodeled" the same way an unknown enum's fields already are just
|
|
1209
|
+
// above (`ctx.enum_params.get` returning `None`) — allow it and let
|
|
1210
|
+
// codegen (which DOES track concrete monomorphized types) catch a
|
|
1211
|
+
// genuine mismatch. Only a definitely-wrong concrete type (`Int`,
|
|
1212
|
+
// `Str`, ...) still hard-errors here.
|
|
1213
|
+
PlumType::TVar(_) => Ok(PlumType::TVar("_".to_string())),
|
|
1102
|
-
|
|
1214
|
+
other => Err(format!("cannot access field '{}' on non-class type {}", field_name, other)),
|
|
1103
1215
|
},
|
|
1104
1216
|
ast::AttrKind::Method(call) => match methodReceiverName(&obj_ty) {
|
|
1105
1217
|
Some(class_name) => match ctx.methods.get(&(class_name.clone(), call.name.clone())) {
|
plum-checker/src/monomorphize.rs
CHANGED
|
@@ -1622,12 +1622,28 @@ impl<'a> Monomorphizer<'a> {
|
|
|
1622
1622
|
fn fnBareGenericRefs(&self, f: &ast::Fn) -> Vec<String> {
|
|
1623
1623
|
let mut names: Vec<String> = Vec::new();
|
|
1624
1624
|
for p in &f.params {
|
|
1625
|
-
let
|
|
1625
|
+
let t = match &p.ty {
|
|
1626
|
-
ast::ParamType::Type(t) =>
|
|
1626
|
+
ast::ParamType::Type(t) => t,
|
|
1627
|
-
ast::ParamType::Variadic(t) =>
|
|
1627
|
+
ast::ParamType::Variadic(t) => t,
|
|
1628
1628
|
// TODO: fn-value params don't yet participate in bare-generic resolution.
|
|
1629
1629
|
ast::ParamType::Fn(_, _) => continue,
|
|
1630
1630
|
};
|
|
1631
|
+
// A param already fully instantiated with concrete type arguments
|
|
1632
|
+
// (`headers: Map[Str, Str]`) is NOT a bare reference to the generic
|
|
1633
|
+
// template — only the truly bare spelling (`headers: Map`, no `[...]`
|
|
1634
|
+
// at all) needs this function's own per-call-site specialization.
|
|
1635
|
+
// Without this check, ANY function taking an already-concrete
|
|
1636
|
+
// generic-typed param (however unrelated to its own logic) was
|
|
1637
|
+
// wrongly routed through `fns_bare_generic`'s worklist instead of
|
|
1638
|
+
// the ordinary per-item pass, silently dropping it from `m.produced`
|
|
1639
|
+
// under its original name — the caller's own inferred return type
|
|
1640
|
+
// (via `fn_return_generic_enum`, which doesn't consult this
|
|
1641
|
+
// classification at all) still looked correct, masking the missing
|
|
1642
|
+
// function until codegen.
|
|
1643
|
+
if !t.generics.is_empty() {
|
|
1644
|
+
continue;
|
|
1645
|
+
}
|
|
1646
|
+
let n = &t.name;
|
|
1631
1647
|
if (self.classes_generic.contains_key(n.as_str()) || self.enums_generic_by_name.contains_key(n.as_str()))
|
|
1632
1648
|
&& !names.iter().any(|x| x == n)
|
|
1633
1649
|
{
|
plum-checker/tests/checker_tests.rs
CHANGED
|
@@ -906,3 +906,129 @@ fun bad(nums: ...Int) -> Int =
|
|
|
906
906
|
let source = parse(src);
|
|
907
907
|
assert!(checkSource(&source).is_err());
|
|
908
908
|
}
|
|
909
|
+
|
|
910
|
+
#[test]
|
|
911
|
+
fn classImplementingTraitWithMatchingMethodPasses() {
|
|
912
|
+
let src = "\
|
|
913
|
+
trait Greeter =
|
|
914
|
+
greet(name: Str) -> Str
|
|
915
|
+
|
|
916
|
+
type Robot(Greeter) =
|
|
917
|
+
id: Int
|
|
918
|
+
|
|
919
|
+
fun greet(self, name: Str) -> Str =
|
|
920
|
+
\"beep {name}\"
|
|
921
|
+
";
|
|
922
|
+
let source = parse(src);
|
|
923
|
+
assert!(checkSource(&source).is_ok(), "expected Ok, got: {:?}", checkSource(&source));
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
#[test]
|
|
927
|
+
fn classClaimingTraitButMissingMethodIsError() {
|
|
928
|
+
let src = "\
|
|
929
|
+
trait Greeter =
|
|
930
|
+
greet(name: Str) -> Str
|
|
931
|
+
|
|
932
|
+
type Robot(Greeter) =
|
|
933
|
+
id: Int
|
|
934
|
+
";
|
|
935
|
+
let source = parse(src);
|
|
936
|
+
let result = checkSource(&source);
|
|
937
|
+
assert!(result.is_err());
|
|
938
|
+
let errs = result.unwrap_err();
|
|
939
|
+
assert!(errs.iter().any(|e| e.message.contains("missing method 'greet'")), "got: {:?}", errs);
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
#[test]
|
|
943
|
+
fn classClaimingTraitWithWrongParamCountIsError() {
|
|
944
|
+
let src = "\
|
|
945
|
+
trait Greeter =
|
|
946
|
+
greet(name: Str) -> Str
|
|
947
|
+
|
|
948
|
+
type Robot(Greeter) =
|
|
949
|
+
id: Int
|
|
950
|
+
|
|
951
|
+
fun greet(self) -> Str =
|
|
952
|
+
\"beep\"
|
|
953
|
+
";
|
|
954
|
+
let source = parse(src);
|
|
955
|
+
let result = checkSource(&source);
|
|
956
|
+
assert!(result.is_err());
|
|
957
|
+
let errs = result.unwrap_err();
|
|
958
|
+
assert!(errs.iter().any(|e| e.message.contains("expected 1 param(s), got 0")), "got: {:?}", errs);
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
#[test]
|
|
962
|
+
fn classClaimingTraitWithWrongParamTypeIsError() {
|
|
963
|
+
let src = "\
|
|
964
|
+
trait Greeter =
|
|
965
|
+
greet(name: Str) -> Str
|
|
966
|
+
|
|
967
|
+
type Robot(Greeter) =
|
|
968
|
+
id: Int
|
|
969
|
+
|
|
970
|
+
fun greet(self, name: Int) -> Str =
|
|
971
|
+
\"beep\"
|
|
972
|
+
";
|
|
973
|
+
let source = parse(src);
|
|
974
|
+
let result = checkSource(&source);
|
|
975
|
+
assert!(result.is_err());
|
|
976
|
+
let errs = result.unwrap_err();
|
|
977
|
+
assert!(errs.iter().any(|e| e.message.contains("expected type 'Str', got 'Int'")), "got: {:?}", errs);
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
#[test]
|
|
981
|
+
fn classClaimingTraitWithWrongReturnTypeIsError() {
|
|
982
|
+
let src = "\
|
|
983
|
+
trait Greeter =
|
|
984
|
+
greet(name: Str) -> Str
|
|
985
|
+
|
|
986
|
+
type Robot(Greeter) =
|
|
987
|
+
id: Int
|
|
988
|
+
|
|
989
|
+
fun greet(self, name: Str) -> Int =
|
|
990
|
+
0
|
|
991
|
+
";
|
|
992
|
+
let source = parse(src);
|
|
993
|
+
let result = checkSource(&source);
|
|
994
|
+
assert!(result.is_err());
|
|
995
|
+
let errs = result.unwrap_err();
|
|
996
|
+
assert!(errs.iter().any(|e| e.message.contains("expected return type 'Str', got 'Int'")), "got: {:?}", errs);
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
#[test]
|
|
1000
|
+
fn classClaimingUndeclaredTraitNameIsNotEnforced() {
|
|
1001
|
+
// `Comparable`/`Readable`/`Writable`-style names used across `libs/std` but
|
|
1002
|
+
// never declared as a real `trait` anywhere — silently unenforced, not an
|
|
1003
|
+
// error, since there is nothing real to check it against.
|
|
1004
|
+
let src = "\
|
|
1005
|
+
type Robot(NotARealTrait) =
|
|
1006
|
+
id: Int
|
|
1007
|
+
";
|
|
1008
|
+
let source = parse(src);
|
|
1009
|
+
assert!(checkSource(&source).is_ok(), "expected Ok, got: {:?}", checkSource(&source));
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
#[test]
|
|
1013
|
+
fn classImplementingTraitWithGenericReturnTypeMismatchIsPermitted() {
|
|
1014
|
+
// A trait method's own return type can never name a concrete payload (it
|
|
1015
|
+
// has no instance to infer one from) — an implementer instantiating that
|
|
1016
|
+
// same generic type with a concrete arg is still a match (base type name
|
|
1017
|
+
// only; see `checkTraitConformance`'s doc comment).
|
|
1018
|
+
let src = "\
|
|
1019
|
+
enum Option[T] =
|
|
1020
|
+
| Some[T]
|
|
1021
|
+
| None
|
|
1022
|
+
|
|
1023
|
+
trait Err =
|
|
1024
|
+
cause() -> Option
|
|
1025
|
+
|
|
1026
|
+
type MyErr(Err) =
|
|
1027
|
+
pos: Int
|
|
1028
|
+
|
|
1029
|
+
fun cause(self) -> Option[MyErr] =
|
|
1030
|
+
None
|
|
1031
|
+
";
|
|
1032
|
+
let source = parse(src);
|
|
1033
|
+
assert!(checkSource(&source).is_ok(), "expected Ok, got: {:?}", checkSource(&source));
|
|
1034
|
+
}
|
plum-cli/Cargo.toml
CHANGED
|
@@ -17,3 +17,4 @@ tree-sitter = "0.26"
|
|
|
17
17
|
tree-sitter-plum = { path = "../tooling/tree-sitter-plum" }
|
|
18
18
|
toml_edit = "0.22"
|
|
19
19
|
wasmtime = "47"
|
|
20
|
+
ureq = "2.10"
|
plum-cli/src/main.rs
CHANGED
|
@@ -389,11 +389,59 @@ fn hostImports(store: &mut wasmtime::Store<()>, module: &wasmtime::Module) -> Re
|
|
|
389
389
|
Ok(())
|
|
390
390
|
})))
|
|
391
391
|
}
|
|
392
|
+
("plum", "rawHttpRequest") => {
|
|
393
|
+
let func_ty = imp.ty().func().cloned()
|
|
394
|
+
.ok_or_else(|| anyhow::anyhow!("plum::rawHttpRequest import must be a function"))?;
|
|
395
|
+
Ok(wasmtime::Extern::Func(wasmtime::Func::new(&mut *store, func_ty.clone(), move |mut caller, params, results| {
|
|
396
|
+
let method = readStrArg(&mut caller, ¶ms[0])?;
|
|
397
|
+
let url = readStrArg(&mut caller, ¶ms[1])?;
|
|
398
|
+
let headers = readStrArg(&mut caller, ¶ms[2])?;
|
|
399
|
+
let body = readStrArg(&mut caller, ¶ms[3])?;
|
|
400
|
+
let raw = performHttpRequest(&method, &url, &headers, &body);
|
|
401
|
+
results[0] = wasmtime::Val::AnyRef(Some(makeStrResult(&mut caller, &func_ty, raw.as_bytes())?));
|
|
402
|
+
Ok(())
|
|
403
|
+
})))
|
|
404
|
+
}
|
|
392
405
|
(m, n) => anyhow::bail!("unsupported host import {m}::{n}"),
|
|
393
406
|
}
|
|
394
407
|
}).collect()
|
|
395
408
|
}
|
|
396
409
|
|
|
410
|
+
/// Performs one blocking HTTP round trip for `plum::rawHttpRequest` and packs
|
|
411
|
+
/// the outcome into the wire format `libs/std/http.plum`'s `request` expects
|
|
412
|
+
/// (see that extern's doc comment): `"1\x01<status>\x01<headers>\x00<body>"`
|
|
413
|
+
/// on success, `"0\x01\x01<message>\x00"` for a transport-level failure. A
|
|
414
|
+
/// non-2xx HTTP status (404, 500, ...) is NOT a failure here — it's still a
|
|
415
|
+
/// complete response, so it goes through the success branch with its own
|
|
416
|
+
/// status code.
|
|
417
|
+
fn performHttpRequest(method: &str, url: &str, headers: &str, body: &str) -> String {
|
|
418
|
+
let agent = ureq::Agent::new();
|
|
419
|
+
let mut req = agent.request(method, url);
|
|
420
|
+
for line in headers.split('\n') {
|
|
421
|
+
if let Some((k, v)) = line.split_once(": ") {
|
|
422
|
+
req = req.set(k, v);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
let result = if body.is_empty() { req.call() } else { req.send_string(body) };
|
|
426
|
+
match result {
|
|
427
|
+
Ok(resp) | Err(ureq::Error::Status(_, resp)) => {
|
|
428
|
+
let status = resp.status();
|
|
429
|
+
let mut header_lines = String::new();
|
|
430
|
+
for name in resp.headers_names() {
|
|
431
|
+
if let Some(v) = resp.header(&name) {
|
|
432
|
+
if !header_lines.is_empty() {
|
|
433
|
+
header_lines.push('\n');
|
|
434
|
+
}
|
|
435
|
+
header_lines.push_str(&format!("{name}: {v}"));
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
let body_text = resp.into_string().unwrap_or_default();
|
|
439
|
+
format!("1\x01{status}\x01{header_lines}\x00{body_text}")
|
|
440
|
+
}
|
|
441
|
+
Err(e) => format!("0\x01\x01{e}\x00"),
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
397
445
|
/// A pseudo-random `i64` seeded from the wall clock — `xorshift64*`, cheap and
|
|
398
446
|
/// dependency-free (no `rand` crate in this workspace). Not cryptographically
|
|
399
447
|
/// secure; fine for `Int.random`/`List.shuffle`/`Uuid.v4`, none of which need
|
plum-runtime/Cargo.toml
CHANGED
|
@@ -11,6 +11,7 @@ path = "src/main.rs"
|
|
|
11
11
|
|
|
12
12
|
[dependencies]
|
|
13
13
|
wasmtime = "47"
|
|
14
|
+
ureq = "2.10"
|
|
14
15
|
|
|
15
16
|
# Stand on its own rather than joining the parent directory's workspace: `plum
|
|
16
17
|
# build` compiles this crate on demand with PLUM_WASM_PATH set, and it would
|
plum-runtime/src/main.rs
CHANGED
|
@@ -193,11 +193,54 @@ fn hostImports(store: &mut wasmtime::Store<()>, module: &wasmtime::Module) -> Ve
|
|
|
193
193
|
Ok(())
|
|
194
194
|
}))
|
|
195
195
|
}
|
|
196
|
+
("plum", "rawHttpRequest") => {
|
|
197
|
+
let func_ty = imp.ty().func().cloned().expect("plum::rawHttpRequest import should be a function");
|
|
198
|
+
wasmtime::Extern::Func(wasmtime::Func::new(&mut *store, func_ty.clone(), move |mut caller, params, results| {
|
|
199
|
+
let method = readStrArg(&mut caller, ¶ms[0])?;
|
|
200
|
+
let url = readStrArg(&mut caller, ¶ms[1])?;
|
|
201
|
+
let headers = readStrArg(&mut caller, ¶ms[2])?;
|
|
202
|
+
let body = readStrArg(&mut caller, ¶ms[3])?;
|
|
203
|
+
let raw = performHttpRequest(&method, &url, &headers, &body);
|
|
204
|
+
results[0] = wasmtime::Val::AnyRef(Some(makeStrResult(&mut caller, &func_ty, raw.as_bytes())?));
|
|
205
|
+
Ok(())
|
|
206
|
+
}))
|
|
207
|
+
}
|
|
196
208
|
(m, n) => panic!("unsupported host import {m}::{n}"),
|
|
197
209
|
}
|
|
198
210
|
}).collect()
|
|
199
211
|
}
|
|
200
212
|
|
|
213
|
+
/// See the identical helper in `plum-cli/src/main.rs` — this crate is built
|
|
214
|
+
/// fresh per `plum build` invocation, not linked against `plum-cli`, so the
|
|
215
|
+
/// logic is duplicated rather than shared.
|
|
216
|
+
fn performHttpRequest(method: &str, url: &str, headers: &str, body: &str) -> String {
|
|
217
|
+
let agent = ureq::Agent::new();
|
|
218
|
+
let mut req = agent.request(method, url);
|
|
219
|
+
for line in headers.split('\n') {
|
|
220
|
+
if let Some((k, v)) = line.split_once(": ") {
|
|
221
|
+
req = req.set(k, v);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
let result = if body.is_empty() { req.call() } else { req.send_string(body) };
|
|
225
|
+
match result {
|
|
226
|
+
Ok(resp) | Err(ureq::Error::Status(_, resp)) => {
|
|
227
|
+
let status = resp.status();
|
|
228
|
+
let mut header_lines = String::new();
|
|
229
|
+
for name in resp.headers_names() {
|
|
230
|
+
if let Some(v) = resp.header(&name) {
|
|
231
|
+
if !header_lines.is_empty() {
|
|
232
|
+
header_lines.push('\n');
|
|
233
|
+
}
|
|
234
|
+
header_lines.push_str(&format!("{name}: {v}"));
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
let body_text = resp.into_string().unwrap_or_default();
|
|
238
|
+
format!("1\x01{status}\x01{header_lines}\x00{body_text}")
|
|
239
|
+
}
|
|
240
|
+
Err(e) => format!("0\x01\x01{e}\x00"),
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
201
244
|
/// See the identical helper in `plum-cli/src/main.rs` — this crate is built
|
|
202
245
|
/// fresh per `plum build` invocation, not linked against `plum-cli`, so the
|
|
203
246
|
/// logic is duplicated rather than shared.
|
test/sample.plum
CHANGED
|
@@ -216,7 +216,7 @@ fun random() -> Float = # generate random number
|
|
|
216
216
|
fun fromStr() -> Result(Int, Err) = # convert Str to Int
|
|
217
217
|
Ok(0)
|
|
218
218
|
|
|
219
|
-
type Int(Comparable,
|
|
219
|
+
type Int(Comparable, ToStr)
|
|
220
220
|
|
|
221
221
|
fun toFloat<Int>() -> Float = # convert Int to Float
|
|
222
222
|
Float(self)
|
tooling/tree-sitter-plum/test/corpus/type.txt
CHANGED
|
@@ -6,7 +6,7 @@ type Dog =
|
|
|
6
6
|
name: Str
|
|
7
7
|
age: B
|
|
8
8
|
|
|
9
|
-
type Cat(
|
|
9
|
+
type Cat(ToStr) =
|
|
10
10
|
name: Str
|
|
11
11
|
age: Int
|
|
12
12
|
|
website/src/content/docs/declarations/enum.md
CHANGED
|
@@ -6,7 +6,7 @@ description: These are basic types
|
|
|
6
6
|
An Algebraic Data Type
|
|
7
7
|
|
|
8
8
|
```rs
|
|
9
|
-
enum Ordering:
|
|
9
|
+
enum Ordering: ToStr {
|
|
10
10
|
LT
|
|
11
11
|
EQ
|
|
12
12
|
GT
|
website/src/content/docs/index.mdx
CHANGED
|
@@ -55,11 +55,11 @@ fn toCelsius(f: float): float =
|
|
|
55
55
|
fn addItems(items ...str) =
|
|
56
56
|
list.add(items)
|
|
57
57
|
|
|
58
|
-
trait
|
|
58
|
+
trait ToStr where
|
|
59
59
|
fn toStr(): str
|
|
60
60
|
|
|
61
61
|
// `Cat is a speciecs of felidae
|
|
62
|
-
struct Cat is
|
|
62
|
+
struct Cat is ToStr, Equal, Comparable =
|
|
63
63
|
| name: str
|
|
64
64
|
| age: int
|
|
65
65
|
|