@oxy.so/bloom 23.9.0 → 23.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/bloom-lang-spec.mdx +730 -0
- package/docs/bloom-language-classnames.mdx +6 -6
- package/docs/bloom-language-codemod.mdx +10 -0
- package/docs/bloom-language-for-agents.mdx +20 -4
- package/docs/bloom-language-from-jsx.mdx +1 -0
- package/docs/bloom-language-getting-started.mdx +2 -1
- package/docs/bloom-language-modifiers.mdx +28 -16
- package/docs/bloom-language-nodes.mdx +1301 -440
- package/docs/bloom-language-tokens.mdx +2 -0
- package/docs/bloom-language-tour.mdx +54 -9
- package/docs/bloom-language.mdx +142 -33
- package/docs/task-catalog.json +1 -1
- package/docs/task-catalog.mdx +1 -1
- package/lib/commonjs/agent-avatar/VectorCharacterAvatar.js +18 -10
- package/lib/commonjs/agent-avatar/VectorCharacterAvatar.js.map +1 -1
- package/lib/commonjs/agent-avatar/VectorStaticPortrait.js +102 -77
- package/lib/commonjs/agent-avatar/VectorStaticPortrait.js.map +1 -1
- package/lib/commonjs/agent-avatar/vector-halo.js +57 -0
- package/lib/commonjs/agent-avatar/vector-halo.js.map +1 -0
- package/lib/commonjs/avatar/Avatar.js +65 -62
- package/lib/commonjs/avatar/Avatar.js.map +1 -1
- package/lib/commonjs/avatar/CharacterFace.js +50 -45
- package/lib/commonjs/avatar/CharacterFace.js.map +1 -1
- package/lib/commonjs/avatar-group/AvatarGroupBase.js +311 -244
- package/lib/commonjs/avatar-group/AvatarGroupBase.js.map +1 -1
- package/lib/commonjs/data-table/DataTable.js +10 -11
- package/lib/commonjs/data-table/DataTable.js.map +1 -1
- package/lib/commonjs/image/BloomImage.js +3 -0
- package/lib/commonjs/image/BloomImage.js.map +1 -1
- package/lib/commonjs/stat-bar/StatBar.js +41 -43
- package/lib/commonjs/stat-bar/StatBar.js.map +1 -1
- package/lib/module/agent-avatar/VectorCharacterAvatar.js +18 -10
- package/lib/module/agent-avatar/VectorCharacterAvatar.js.map +1 -1
- package/lib/module/agent-avatar/VectorStaticPortrait.js +103 -78
- package/lib/module/agent-avatar/VectorStaticPortrait.js.map +1 -1
- package/lib/module/agent-avatar/vector-halo.js +52 -0
- package/lib/module/agent-avatar/vector-halo.js.map +1 -0
- package/lib/module/avatar/Avatar.js +65 -62
- package/lib/module/avatar/Avatar.js.map +1 -1
- package/lib/module/avatar/CharacterFace.js +50 -45
- package/lib/module/avatar/CharacterFace.js.map +1 -1
- package/lib/module/avatar-group/AvatarGroupBase.js +311 -244
- package/lib/module/avatar-group/AvatarGroupBase.js.map +1 -1
- package/lib/module/data-table/DataTable.js +10 -11
- package/lib/module/data-table/DataTable.js.map +1 -1
- package/lib/module/image/BloomImage.js +3 -0
- package/lib/module/image/BloomImage.js.map +1 -1
- package/lib/module/stat-bar/StatBar.js +41 -43
- package/lib/module/stat-bar/StatBar.js.map +1 -1
- package/lib/typescript/commonjs/agent-avatar/VectorCharacterAvatar.d.ts.map +1 -1
- package/lib/typescript/commonjs/agent-avatar/VectorStaticPortrait.d.ts +2 -2
- package/lib/typescript/commonjs/agent-avatar/VectorStaticPortrait.d.ts.map +1 -1
- package/lib/typescript/commonjs/agent-avatar/types.d.ts +6 -0
- package/lib/typescript/commonjs/agent-avatar/types.d.ts.map +1 -1
- package/lib/typescript/commonjs/agent-avatar/vector-halo.d.ts +32 -0
- package/lib/typescript/commonjs/agent-avatar/vector-halo.d.ts.map +1 -0
- package/lib/typescript/commonjs/avatar/Avatar.d.ts.map +1 -1
- package/lib/typescript/commonjs/avatar/CharacterFace.d.ts +4 -1
- package/lib/typescript/commonjs/avatar/CharacterFace.d.ts.map +1 -1
- package/lib/typescript/commonjs/avatar/types.d.ts +9 -0
- package/lib/typescript/commonjs/avatar/types.d.ts.map +1 -1
- package/lib/typescript/commonjs/avatar-group/AvatarGroupBase.d.ts.map +1 -1
- package/lib/typescript/commonjs/data-table/DataTable.d.ts.map +1 -1
- package/lib/typescript/commonjs/image/BloomImage.d.ts.map +1 -1
- package/lib/typescript/module/agent-avatar/VectorCharacterAvatar.d.ts.map +1 -1
- package/lib/typescript/module/agent-avatar/VectorStaticPortrait.d.ts +2 -2
- package/lib/typescript/module/agent-avatar/VectorStaticPortrait.d.ts.map +1 -1
- package/lib/typescript/module/agent-avatar/types.d.ts +6 -0
- package/lib/typescript/module/agent-avatar/types.d.ts.map +1 -1
- package/lib/typescript/module/agent-avatar/vector-halo.d.ts +32 -0
- package/lib/typescript/module/agent-avatar/vector-halo.d.ts.map +1 -0
- package/lib/typescript/module/avatar/Avatar.d.ts.map +1 -1
- package/lib/typescript/module/avatar/CharacterFace.d.ts +4 -1
- package/lib/typescript/module/avatar/CharacterFace.d.ts.map +1 -1
- package/lib/typescript/module/avatar/types.d.ts +9 -0
- package/lib/typescript/module/avatar/types.d.ts.map +1 -1
- package/lib/typescript/module/avatar-group/AvatarGroupBase.d.ts.map +1 -1
- package/lib/typescript/module/data-table/DataTable.d.ts.map +1 -1
- package/lib/typescript/module/image/BloomImage.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/agent-avatar/VectorCharacterAvatar.tsx +26 -7
- package/src/agent-avatar/VectorStaticPortrait.tsx +18 -5
- package/src/agent-avatar/types.ts +6 -0
- package/src/agent-avatar/vector-halo.ts +52 -0
- package/src/avatar/Avatar.tsx +2 -0
- package/src/avatar/CharacterFace.tsx +6 -0
- package/src/avatar/types.ts +6 -0
- package/src/avatar-group/AvatarGroupBase.tsx +36 -4
- package/src/data-table/DataTable.tsx +8 -10
- package/src/image/BloomImage.tsx +3 -0
- package/src/stat-bar/StatBar.tsx +14 -14
|
@@ -0,0 +1,730 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Bloom (.bloom) language specification, draft 0
|
|
3
|
+
description: The grammar, type system, reactivity model, effects, modules, interop and standard library of Bloom's own language, written in .bloom files and compiled by bloomc. Phase 0 draft for the owner's review.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Bloom (`.bloom`) language specification: draft 0
|
|
7
|
+
|
|
8
|
+
Status: **draft 0.2, phase 0** (2026-11-26; 0.1 and 0.2 fold in what porting Mention's Settings → Notifications and building the prototype found). Nothing here is released. The
|
|
9
|
+
decision record is [ADR 0001](https://github.com/OxyHQ/Bloom/blob/main/docs/adr/0001-bloom-own-language.md). The
|
|
10
|
+
TS-embedded language (`@oxy.so/bloom-language` chains in `.tsx`) is called
|
|
11
|
+
**the embedded language** below; `.bloom` compiles *to* it, so everything the
|
|
12
|
+
embedded language draws, `.bloom` draws the same way.
|
|
13
|
+
|
|
14
|
+
Notation: `«x»` is a placeholder; "phase 0" marks what the prototype
|
|
15
|
+
implements, "phase 1+" what is specified but not built yet.
|
|
16
|
+
|
|
17
|
+
## 1. A taste
|
|
18
|
+
|
|
19
|
+
```bloom
|
|
20
|
+
import { useTranslation } from "react-i18next"
|
|
21
|
+
|
|
22
|
+
enum Load<T> {
|
|
23
|
+
loading
|
|
24
|
+
failed(message: String)
|
|
25
|
+
ready(T)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
struct Draft {
|
|
29
|
+
text: String = ""
|
|
30
|
+
sensitive: Bool = false
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
pub view Composer(maxLength: Int = 500, onSend: async (Draft) -> Result<Unit, String>) {
|
|
34
|
+
let { t } = useTranslation()
|
|
35
|
+
@state draft = Draft()
|
|
36
|
+
@state sending = false
|
|
37
|
+
|
|
38
|
+
let left = maxLength - draft.text.count // derived, recomputed only when draft changes
|
|
39
|
+
let canSend = !sending && left >= 0 && !draft.text.isEmpty
|
|
40
|
+
|
|
41
|
+
async fn send() {
|
|
42
|
+
sending = true
|
|
43
|
+
match await onSend(draft) {
|
|
44
|
+
case .ok(_) => draft = Draft()
|
|
45
|
+
case .err(message) => toast(message, type: "error")
|
|
46
|
+
}
|
|
47
|
+
sending = false
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
body {
|
|
51
|
+
VStack {
|
|
52
|
+
TextField($draft.text, t("compose.placeholder"))
|
|
53
|
+
HStack {
|
|
54
|
+
Toggle($draft.sensitive).label(t("compose.sensitive"))
|
|
55
|
+
Spacer()
|
|
56
|
+
Text("${left}").foreground(left < 0 ? "error" : "muted")
|
|
57
|
+
Button(Text(t("compose.send"))).disabled(!canSend).onPress { await send() }
|
|
58
|
+
}
|
|
59
|
+
.spacing("sm")
|
|
60
|
+
}
|
|
61
|
+
.spacing("md")
|
|
62
|
+
.padding("lg")
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## 2. Lexical structure
|
|
68
|
+
|
|
69
|
+
- **Source** is UTF-8. A file is one module.
|
|
70
|
+
- **Comments:** `// line`, `/* block */` (nesting), `/// doc` (attached to the next item; shown on hover).
|
|
71
|
+
- **Newlines terminate** statements, fields, variants and builder items. A newline does **not**
|
|
72
|
+
terminate when (a) the next non-blank line starts with `.` followed by an identifier
|
|
73
|
+
(a modifier or member continues the expression), or with a binary operator other than `-`
|
|
74
|
+
(`&&`, `||`, `??`, `+`, `*`, `/`, `==`, …), or (b) the line ends inside `(`/`[`, after a binary
|
|
75
|
+
operator, after `,`, `=`, `->`, `=>` or `in`. Comment-only lines count as blank for (a). `;`
|
|
76
|
+
may separate items on one line.
|
|
77
|
+
- **Identifiers:** `[a-zA-Z_][a-zA-Z0-9_]*`. Types, views and enum names are `UpperCamel`;
|
|
78
|
+
values, functions, fields and enum cases are `lowerCamel` (a warning otherwise, B0901).
|
|
79
|
+
- **Keywords:** `as async await body case default defer else enum false fn for from if import in
|
|
80
|
+
let match none pub return screen layout struct task true type var view while`. Attribute words after `@`:
|
|
81
|
+
`state list record env`.
|
|
82
|
+
- **Literals:** `42`, `1_000`, `0xff` (Int); `1.5`, `2e3` (Float); `true`/`false`; `none`;
|
|
83
|
+
strings `"…"` with escapes `\n \t \" \\ \$ \u{1F600}` and interpolation `${expr}`;
|
|
84
|
+
raw multi-line strings `"""…"""` (interpolation kept, indentation stripped to the closing
|
|
85
|
+
delimiter).
|
|
86
|
+
- **Binding projection:** `$name` (a binding to `@state name`, see 7.2).
|
|
87
|
+
|
|
88
|
+
## 3. Grammar (EBNF)
|
|
89
|
+
|
|
90
|
+
`NL` is a terminating newline (section 2). `{ x }` is zero or more, `[ x ]` optional.
|
|
91
|
+
|
|
92
|
+
```ebnf
|
|
93
|
+
file = { import NL } { item NL } ;
|
|
94
|
+
|
|
95
|
+
import = "import" "{" import_spec { "," import_spec } [ "," ] "}" "from" STRING
|
|
96
|
+
| "import" "*" "as" IDENT "from" STRING ;
|
|
97
|
+
import_spec = [ "type" ] NAME [ "as" NAME ] ;
|
|
98
|
+
|
|
99
|
+
item = { doc } [ "pub" [ "default" ] ]
|
|
100
|
+
( struct | enum | alias | fn | view | screen | layout | const ) ;
|
|
101
|
+
const = "let" IDENT [ ":" type ] "=" expr ;
|
|
102
|
+
struct = "struct" TYPE_NAME [ generics ] "{" { field NL } "}" ;
|
|
103
|
+
field = IDENT ":" type [ "=" expr ] ;
|
|
104
|
+
enum = "enum" TYPE_NAME [ generics ] "{" { variant ( NL | "," ) } "}" ;
|
|
105
|
+
variant = IDENT [ "(" payload { "," payload } ")" ] ;
|
|
106
|
+
payload = [ IDENT ":" ] type ;
|
|
107
|
+
alias = "type" TYPE_NAME [ generics ] "=" type ;
|
|
108
|
+
generics = "<" TYPE_NAME { "," TYPE_NAME } ">" ;
|
|
109
|
+
|
|
110
|
+
fn = [ "async" ] "fn" IDENT [ generics ] "(" [ params ] ")" [ "->" type ] block ;
|
|
111
|
+
params = param { "," param } [ "," ] ;
|
|
112
|
+
param = [ ".." ] IDENT ":" type [ "=" expr ] ; (* "..": a rest parameter, last *)
|
|
113
|
+
|
|
114
|
+
view = "view" TYPE_NAME [ "(" [ params ] ")" ] view_block ; (* a param may be ".." TYPE: props spread *)
|
|
115
|
+
screen = "screen" TYPE_NAME [ "(" [ params ] ")" ] view_block ; (* a route: default export *)
|
|
116
|
+
layout = "layout" TYPE_NAME [ "(" [ params ] ")" ] view_block ; (* a route layout *)
|
|
117
|
+
view_block = "{" { member NL } "body" block "}" ;
|
|
118
|
+
member = state | let_stmt | fn | effect | equal ;
|
|
119
|
+
equal = "equal" "(" IDENT "," IDENT ")" block ; (* contextual, like effect *)
|
|
120
|
+
effect = "effect" [ "(" "id" ":" expr ")" ] block ; (* contextual: `effect` stays a name *)
|
|
121
|
+
state = "@" ( "state" | "list" | "record" | "env" | "ref" ) IDENT [ ":" type ] "=" expr ;
|
|
122
|
+
|
|
123
|
+
block = "{" { stmt ( NL | ";" ) } "}" ;
|
|
124
|
+
stmt = let_stmt | var_stmt | assign | "return" [ expr ] | "defer" block | while | for | expr ;
|
|
125
|
+
let_stmt = "let" pattern [ ":" type ] "=" expr ;
|
|
126
|
+
var_stmt = "var" IDENT [ ":" type ] "=" expr ;
|
|
127
|
+
assign = place ( "=" | "+=" | "-=" | "*=" ) expr ;
|
|
128
|
+
place = IDENT { "." IDENT } ;
|
|
129
|
+
while = "while" expr_no_trailing block ;
|
|
130
|
+
for = "for" pattern "in" expr_no_trailing block ;
|
|
131
|
+
|
|
132
|
+
type = base_type [ "?" ] ;
|
|
133
|
+
base_type = TYPE_NAME [ "<" type { "," type } ">" ]
|
|
134
|
+
| "[" type "]" (* List<T> *)
|
|
135
|
+
| "[" type ":" type "]" (* Map<K, V> *)
|
|
136
|
+
| "(" type "," type { "," type } ")" (* tuple *)
|
|
137
|
+
| [ "async" ] "(" [ type { "," type } ] ")" "->" type ;
|
|
138
|
+
|
|
139
|
+
expr = if_expr | match_expr | closure | binary ;
|
|
140
|
+
if_expr = "if" cond block [ "else" ( if_expr | block ) ] ;
|
|
141
|
+
cond = expr_no_trailing | "let" pattern "=" expr_no_trailing ;
|
|
142
|
+
match_expr = "match" expr_no_trailing "{" { "case" pattern [ "if" expr ] "=>" ( block | expr ) NL } "}" ;
|
|
143
|
+
(* after "=>", "{" always opens a block; "{}" is the empty block, of type Unit;
|
|
144
|
+
an arm may also be one statement: case .ok(_) => draft = Draft() *)
|
|
145
|
+
task_expr = "task" block ; (* spawns; the expression is Unit *)
|
|
146
|
+
closure = "{" [ closure_params "in" ] { stmt ( NL | ";" ) } "}" ;
|
|
147
|
+
closure_params= IDENT [ ":" type ] { "," IDENT [ ":" type ] }
|
|
148
|
+
| "(" IDENT { "," IDENT } ")" ; (* one tuple parameter, its items named *)
|
|
149
|
+
|
|
150
|
+
binary = unary { BINOP unary } ; (* precedence table in 6.1 *)
|
|
151
|
+
unary = [ "!" | "-" | "await" ] postfix ; (* "await" binds tighter than a trailing "?":
|
|
152
|
+
await f()? is (await f())? *)
|
|
153
|
+
postfix = primary { call | "." NAME | "?." NAME | "?." "(" [ args ] ")" | "[" expr "]" | "?" } ;
|
|
154
|
+
call = "(" [ args ] ")" [ closure ] | closure ; (* a trailing closure; never in
|
|
155
|
+
expr_no_trailing heads *)
|
|
156
|
+
args = arg { "," arg } [ "," ] ;
|
|
157
|
+
arg = [ IDENT ":" ] expr | ".." expr ; (* named argument; a struct spread, or a
|
|
158
|
+
list spread into a rest parameter *)
|
|
159
|
+
primary = literal | "()" | task_expr | STRING | NAME | "." IDENT | "$" IDENT { "." IDENT }
|
|
160
|
+
| "(" expr ")" | "(" expr "," expr { "," expr } ")"
|
|
161
|
+
| "[" [ item { "," item } ] "]" | "[" expr ":" expr { "," expr ":" expr } "]" | "[:]" ;
|
|
162
|
+
|
|
163
|
+
item = expr | ".." expr ; (* `[..a, b]`: a list's items in place *)
|
|
164
|
+
pattern = "_" | IDENT | literal | "." IDENT [ "(" pattern { "," pattern } ")" ]
|
|
165
|
+
| TYPE_NAME "." IDENT [ "(" … ")" ] | "(" pattern { "," pattern } ")"
|
|
166
|
+
| "{" IDENT [ ":" pattern ] { "," … } "}" (* record destructuring *)
|
|
167
|
+
| pattern "|" pattern ;
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Three grammar rules keep it unambiguous, as in Swift:
|
|
171
|
+
|
|
172
|
+
A keyword that never starts an expression (`type`, `body`, `view`, `screen`, `layout`, `from`)
|
|
173
|
+
may name a parameter, a struct field or a value, so a TS API's props and fields keep their
|
|
174
|
+
names (`view NoticeRow(type: String, body: String)`, `Text(body)`). Record keys, labels and
|
|
175
|
+
members after `.` may be any keyword.
|
|
176
|
+
|
|
177
|
+
1. **No trailing closure in a head.** `if x { … }`, `match x {`, `for p in xs {` and `while`
|
|
178
|
+
never read the `{` as a trailing closure of `x`.
|
|
179
|
+
2. **Match arms start with `case`**, so a line starting with `.` is always a continuation.
|
|
180
|
+
3. **An enum case at the start of a line is qualified** (`Load.ready(x)`), since `.ready(x)` there
|
|
181
|
+
would continue the previous line. `ok(x)`, `err(e)` are prelude constructors.
|
|
182
|
+
|
|
183
|
+
## 4. Types
|
|
184
|
+
|
|
185
|
+
### 4.1 The types
|
|
186
|
+
|
|
187
|
+
| Bloom | Meaning | Runtime representation (zero-cost) | `.d.ts` emitted |
|
|
188
|
+
|---|---|---|---|
|
|
189
|
+
| `Int` | 53-bit safe integer | JS number | `number` |
|
|
190
|
+
| `Float` | IEEE double | JS number | `number` |
|
|
191
|
+
| `Bool`, `String`, `Unit` | | boolean, string, `undefined` | `boolean`, `string`, `void` |
|
|
192
|
+
| `[T]` | immutable list | frozen-in-dev JS array | `readonly T[]` |
|
|
193
|
+
| `[String: V]` | immutable dictionary | plain object | `Readonly<Record<string, V>>` |
|
|
194
|
+
| `Map<K, V>` | immutable map, any key | `Map` | `ReadonlyMap<K, V>` |
|
|
195
|
+
| `Set<T>` | immutable set | `Set` | `ReadonlySet<T>` |
|
|
196
|
+
| `(A, B)` | tuple | array | `readonly [A, B]` |
|
|
197
|
+
| `T?` | `Option<T>` | the value or `undefined` | `T \| undefined` |
|
|
198
|
+
| `Result<T, E>` | success or error | `{ ok: true, value } \| { ok: false, error }` | the same union |
|
|
199
|
+
| `struct S { … }` | nominal record | plain object | `interface S { readonly … }` |
|
|
200
|
+
| `enum E { a, b }` (no payloads) | | string literal | `"a" \| "b"` |
|
|
201
|
+
| `enum E { a, b(T) }` | tagged union | `"a"` or `{ tag: "b", _0: T }` (named payloads keep their names) | the union |
|
|
202
|
+
| `(A) -> R`, `async (A) -> R` | a Bloom function (async: one that awaits) | JS function (async → returns a Promise) | `(a: A) => R` / `Promise<R>` |
|
|
203
|
+
| `Promise<T>` | a TS promise (it may reject) | the promise | `Promise<T>` |
|
|
204
|
+
| `Error` | a JS error: `message: String`, `name: String` | the `Error` object | `Error` |
|
|
205
|
+
| `View` | a UI value | an embedded-language node (`Child`) | `Child` |
|
|
206
|
+
| `Binding<T>` | read and write of a state | `[value, set]` (the embedded language's binding) | `Binding<T>` |
|
|
207
|
+
| token sets (`Space`, `Color`, `Font`, …) | closed string sets from `spec/language.json` | string | the literal union |
|
|
208
|
+
| `Foreign` | a TS value Bloom could not type (4.6) | as is | the TS type |
|
|
209
|
+
|
|
210
|
+
`T??` is rejected (B0203): an optional is never nested, so `undefined` alone can represent it.
|
|
211
|
+
|
|
212
|
+
### 4.2 Inference
|
|
213
|
+
|
|
214
|
+
Local bidirectional inference with unification (Hindley–Milner without let-generalisation of
|
|
215
|
+
locals). Signatures are required at module level (parameters and results of `fn`, fields,
|
|
216
|
+
view parameters), inferred everywhere inside: `let`, closure parameters (from the expected
|
|
217
|
+
function type), generic arguments at call sites, empty collections from use. A literal
|
|
218
|
+
`"md"` checks against an expected token set; `none` against an expected `T?`. A `T` is
|
|
219
|
+
promoted to `T?` where a `T?` is expected (never the reverse; unwrap with `if let`, `??`,
|
|
220
|
+
`?.`, `match` or `?`). In `if x != none { … }` (also `none != x`, and each side of `&&`) a
|
|
221
|
+
local, parameter or prop `x` is present in the block, as TS narrows it: `if onEnd != none {
|
|
222
|
+
onEnd() }`. So it is on the right of `&&` (`name != none && !name.isEmpty`) and, for `x == none`,
|
|
223
|
+
on the right of `||` (`x == none || x.isEmpty`); in the branch of `?:` that knows (`p != none ?
|
|
224
|
+
p.x : d`, `p == none ? d : p.x`); and after a guard
|
|
225
|
+
that returns (`if x == none { return … }`, also `a == none || b == none`), in the rest of the
|
|
226
|
+
block. Values are immutable, so a member chain of such a name narrows the same way
|
|
227
|
+
(`u.name != none && !u.name.isEmpty`, `u?.name`, `u.avatar?.url`); the emitter writes `u.name!`,
|
|
228
|
+
since TS does not keep a property's narrowing inside a closure.
|
|
229
|
+
|
|
230
|
+
Numbers: an `Int` widens to `Float` wherever a `Float` is expected, Bloom to Bloom and at the
|
|
231
|
+
TS boundary (a TS `number` reads as `Float`), inside lists, optionals, dictionaries and record
|
|
232
|
+
fields too (`[Int]` fits `[Float]`). It costs nothing and loses nothing: both are JS numbers
|
|
233
|
+
and an `Int` stays within 2^53, so no conversion is emitted. An integer literal is a `Float`
|
|
234
|
+
where one is expected (`let x: Float = 0`). Arithmetic with an `Int` and a `Float` operand
|
|
235
|
+
is `Float`; `i / j` of two `Int`s stays integer division (it truncates) even where a `Float`
|
|
236
|
+
is expected, while `7 / 2` there is `3.5` (its literals are `Float`s). A conditional with an
|
|
237
|
+
`Int` and a `Float` branch is `Float`. A `Float` never narrows implicitly.
|
|
238
|
+
|
|
239
|
+
### 4.3 Soundness rules
|
|
240
|
+
|
|
241
|
+
- No `any`, no implicit null, no implicit narrowing: `Float` → `Int` is `.rounded()`,
|
|
242
|
+
`.floor()`, `.ceil()` or `.truncated()` (B0201). `Int` → `Float` widens implicitly (4.2).
|
|
243
|
+
- Exhaustive `match` (B0301 lists the missing cases); unreachable arms warn (B0302).
|
|
244
|
+
- Values are immutable. `var` exists only as a function-local; it cannot be captured by a
|
|
245
|
+
closure (B0402), so no closure observes a mutation.
|
|
246
|
+
- Equality `==` is defined on `Int`, `Float`, `Bool`, `String`, fieldless enums and `none`
|
|
247
|
+
checks; on structs and payload enums it is structural and compiled to a field comparison
|
|
248
|
+
(phase 1; phase 0 rejects it with B0210). `x == none` / `x != none` tests presence on any
|
|
249
|
+
optional, a function's too. `T == T?` compares as optionals (`a == b` with `b: Int?`), as
|
|
250
|
+
Swift does.
|
|
251
|
+
- Integer division `/` on `Int` truncates toward zero; `%` follows the dividend's sign.
|
|
252
|
+
|
|
253
|
+
### 4.4 Structs
|
|
254
|
+
|
|
255
|
+
```bloom
|
|
256
|
+
struct Prefs {
|
|
257
|
+
pushEnabled: Bool = true
|
|
258
|
+
likes: Bool = true
|
|
259
|
+
}
|
|
260
|
+
let p = Prefs() // every field has a default
|
|
261
|
+
let q = p.with(likes: false) // an updated copy
|
|
262
|
+
let r = Prefs(..patch, likes: true) // spread a Prefs or a Partial<Prefs>, then fields
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
A field without a default is required at construction. `Partial<S>` is the struct with every
|
|
266
|
+
field optional (a patch), built with `S.patch(field: v, …)`. Construction compiles to an object
|
|
267
|
+
literal (no function call). A spread `..p` of a `Partial<S>` fills only the fields `p` has: an
|
|
268
|
+
absent or `undefined` field keeps the default (compiled per field, `p?.likes ?? true`), unlike a
|
|
269
|
+
JS object spread; an optional patch (`Partial<S>?`) spreads the same way. Keyed field access (`prefs[key]`, key paths) is phase 1; until then an
|
|
270
|
+
exhaustive `match` on a fieldless enum maps a key to a field.
|
|
271
|
+
|
|
272
|
+
### 4.5 Enums, Option and Result
|
|
273
|
+
|
|
274
|
+
```bloom
|
|
275
|
+
enum Shape {
|
|
276
|
+
circle(radius: Float)
|
|
277
|
+
rect(w: Float, h: Float)
|
|
278
|
+
}
|
|
279
|
+
fn area(s: Shape) -> Float {
|
|
280
|
+
match s {
|
|
281
|
+
case .circle(r) => 3.14159 * r * r
|
|
282
|
+
case .rect(w, h) => w * h
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
`Option<T>` is written `T?`: `none`, `x ?? fallback`, `x?.field`, `x?.method(…)`, `f?.(…)`,
|
|
288
|
+
`if let v = x { … }`. A `?.` short-circuits the rest of its chain, as in JS: in
|
|
289
|
+
`b?.label.uppercased()` the `.uppercased()` reads `b`'s label and the whole is `String?`. A
|
|
290
|
+
link whose own type is optional is not read through (`b?.note.trimmed()` with `note: String?`
|
|
291
|
+
is B0209; write `b?.note?.trimmed()`). `?.` on a value that is never `none` is B0201. A method
|
|
292
|
+
JS has compiles to `x?.m(…)`; any other (`s?.toInt()`) reads `x` once and runs only when it
|
|
293
|
+
is not `none`. An optional call of a Unit function is Unit.
|
|
294
|
+
`Result<T, E>` has cases `ok(T)` and `err(E)`; `expr?` in a function returning
|
|
295
|
+
`Result<_, E>` returns the error early (in one returning `T?`, a `none` early). Inside
|
|
296
|
+
`catching { … }` and in a closure TS calls (a TS parameter's function, sync or async, or one of no Bloom type),
|
|
297
|
+
`expr?` on a `Result` throws its error instead: `catching` gives it as `.err`, and the promise
|
|
298
|
+
TS awaits rejects (`queryFn: { let page = (await api.list())?; page.items }`). Methods:
|
|
299
|
+
`.map`, `.mapErr`, `.unwrapOr`, `.ok()` (to an optional), `.isOk`.
|
|
300
|
+
|
|
301
|
+
### 4.6 Generics
|
|
302
|
+
|
|
303
|
+
`fn first<T>(xs: [T]) -> T?`, `struct Page<T> { items: [T], cursor: String? }`,
|
|
304
|
+
`enum Load<T>`. Type parameters are inferred at call sites; no bounds in phase 0 (phase 1:
|
|
305
|
+
`<T: Equatable>`-style protocol bounds compiled away by monomorphising the comparison).
|
|
306
|
+
|
|
307
|
+
### 4.7 The foreign boundary
|
|
308
|
+
|
|
309
|
+
A TS import is typed from its `.d.ts` (section 10). Declarations bloomc can map (primitives,
|
|
310
|
+
arrays, `T | undefined | null`, object types, interfaces, string-literal unions, function
|
|
311
|
+
types, `Promise<T>`, generic functions and interfaces without conditional or mapped types)
|
|
312
|
+
get Bloom types. Anything else is `Foreign`: a value you may pass back to TS, call, or read
|
|
313
|
+
members from (each read is `Foreign` again). **A `Foreign` value is accepted wherever a Bloom
|
|
314
|
+
type is expected** (an argument, a modifier, a condition, an annotated `let`, a field, a
|
|
315
|
+
return), and there the emitter writes a checked boundary, `(expr satisfies T)`, so the
|
|
316
|
+
TypeScript checker verifies it against the real `.d.ts` and its diagnostic maps back to the
|
|
317
|
+
`.bloom` span. Where nothing is expected (`let x = foreignCall()`) the value stays `Foreign`,
|
|
318
|
+
and using it as a Bloom value with no expected type (an operator, a `match`, a member of a Bloom
|
|
319
|
+
type) is B0601 with the fix "annotate it: `let x: T = …`". Nothing crosses unchecked: Bloom code
|
|
320
|
+
is checked by bloomc, and every crossing by `tsc`.
|
|
321
|
+
|
|
322
|
+
`foreign ?? e` takes `e`'s type (the left side may be `null` in TS as well as `undefined`);
|
|
323
|
+
TS checks the whole where it lands; a TS value compared with `none` is compared loosely
|
|
324
|
+
(`!= null`), as TS's absence may be `null`. Where `e` says less than TS knows (`data ?? []`), its items
|
|
325
|
+
are the TS value's (`NonNullable<…>[number]`), so `.map { m in m.name }` reads TS members. A TS
|
|
326
|
+
value beside a number in arithmetic is a number (`insets.top + 4` is a `Float`; for `+` beside
|
|
327
|
+
a string, a `String`), and the emitter writes `(insets.top satisfies number)`. So does a TS value beside `none` or a Bloom value in a
|
|
328
|
+
branch (`on ? none : presets.find { … }`), and `for x in foreign` walks TS items. A TS tuple
|
|
329
|
+
of string literals (`['a', 'b'] as const`) is a list of their union, `[("a" | "b")]`. `f || b`
|
|
330
|
+
of a TS value `f` is JS's `||` (`list.title || "Untitled"`): `b`'s type, checked by
|
|
331
|
+
`satisfies`. A field of a TS value is TS's to write (`player.loop = true`, `p.time += 5`),
|
|
332
|
+
emitted as written and checked by tsc. A node's argument TS types (a signature's `value`) takes `none` where TS takes
|
|
333
|
+
`undefined` (`SettingsSection(none, …)`). A TS
|
|
334
|
+
class that extends nothing (`ViewModifier`) is a value
|
|
335
|
+
and a type, both `Foreign`: `look: ViewModifier? = none` then `.modifier(look ?? card)`.
|
|
336
|
+
|
|
337
|
+
`x is T` tests a TS value of no Bloom type (`unknown`, a union) at run time, for the types JS
|
|
338
|
+
can test: `String`, `Int` (an integer number), `Float`, `Bool` and `[T]` (`Array.isArray`; its
|
|
339
|
+
items are taken as `T`). `if x is T { … }` narrows a name to `T` in the block. It sits at the
|
|
340
|
+
comparisons' precedence. `is` on a Bloom value, or for another type, is B0213: a Bloom type's
|
|
341
|
+
cases are an enum's, matched with `match`. A Bloom file reads no JS global implicitly: numbers
|
|
342
|
+
come from the prelude (section 12), timers are `task { await sleep(ms) … }`, and any other global
|
|
343
|
+
is imported by name, `import { encodeURIComponent, JSON } from "js"`: nothing is emitted for
|
|
344
|
+
the import, and its names are `Foreign`, typed by TypeScript (lib.es, lib.dom) where they cross.
|
|
345
|
+
A JS class imported so (`Date`, `URL`, `AbortController`, `URLSearchParams`, `Error`, …) is
|
|
346
|
+
built by a call: `Date(at)` is `new Date(at)`; Bloom has no `new`. `Foreign<"T">` writes out a
|
|
347
|
+
TS type Bloom does not express (`Foreign<"ReturnType<typeof setTimeout>">`,
|
|
348
|
+
`Foreign<"AvatarProps['source']">`, `Foreign<"string | number">`): its values are `Foreign`,
|
|
349
|
+
and the emitted TS names the type as written, so TS checks every use.
|
|
350
|
+
|
|
351
|
+
A record literal where a dictionary `[String: V]` is expected is a dictionary literal: each value
|
|
352
|
+
is checked as a `V` (a TS value as any other), and `..d` spreads a dictionary into it
|
|
353
|
+
(`let ICONS: [String: BloomIcon] = { mixed: RiGitMergeLine }`). A record, or a TS object type,
|
|
354
|
+
fits a dictionary when each of its fields fits `V` (`let GAPS: [String: Float] = SPACING`).
|
|
355
|
+
|
|
356
|
+
TS declarations as libraries write them (react-native's): `export * as X from "…"` is a
|
|
357
|
+
namespace, `Foreign` (`StyleSheet.create({ … })`); a value and a type of one name (`declare const
|
|
358
|
+
Platform: PlatformType; declare type Platform = typeof Platform`) are both read, the value
|
|
359
|
+
typed, the type `Foreign`; a const whose type is, through aliases and `&`, a function from props
|
|
360
|
+
to a node is a component (`TextInput(value: v)`). As a type, such a component is its instance,
|
|
361
|
+
as a ref holds it (`@ref input: TextInput? = none`; read from its `ref` prop, else React's
|
|
362
|
+
`ComponentRef`), and `ref: input` passes a TS component the `@ref` itself.
|
|
363
|
+
|
|
364
|
+
## 5. Values, functions and closures
|
|
365
|
+
|
|
366
|
+
```bloom
|
|
367
|
+
let x = 1 // immutable
|
|
368
|
+
var total = 0 // function-local, mutable, not capturable
|
|
369
|
+
fn double(x: Int) -> Int { x * 2 } // the last expression is the result
|
|
370
|
+
async fn load(id: String) -> Result<Post, String> { … }
|
|
371
|
+
let inc = { n in n + 1 } // closure: (Int) -> Int from use
|
|
372
|
+
xs.map { p in p.title } // trailing closure
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
A rest parameter `..xs: [T]` comes last, has no default, and takes any number of `T`s after
|
|
376
|
+
the other positional arguments; in the body it is a `[T]`. A call spreads a list into a rest
|
|
377
|
+
parameter (Bloom's or a TS function's `...args`) with `..`: `total(1, ..xs)`,
|
|
378
|
+
`joinClasses("row", ..names)` compiles to `joinClasses("row", ...names)`. A spread where no rest
|
|
379
|
+
parameter takes it is B0207 (outside a construction, where `..s` spreads a struct). A view takes
|
|
380
|
+
props, never a rest parameter.
|
|
381
|
+
|
|
382
|
+
Named arguments: a Bloom function's parameters can be passed by name (`f(1, label: "x")`)
|
|
383
|
+
in any order after the positional ones. **In a call to a TS function, named arguments form one
|
|
384
|
+
object passed last**: `t("key", defaultValue: "General")` is `t("key", { defaultValue: "General" })`.
|
|
385
|
+
|
|
386
|
+
## 6. Expressions and control flow
|
|
387
|
+
|
|
388
|
+
### 6.1 Precedence (high to low)
|
|
389
|
+
|
|
390
|
+
| Level | Operators | Assoc. |
|
|
391
|
+
|---|---|---|
|
|
392
|
+
| postfix | call, `.x`, `?.x`, `[i]`, `?` | left |
|
|
393
|
+
| prefix | `!` `-` `await` | right |
|
|
394
|
+
| multiplicative | `*` `/` `%` | left |
|
|
395
|
+
| additive | `+` `-` (`+` also joins `String`s) | left |
|
|
396
|
+
| comparison | `<` `<=` `>` `>=` | none |
|
|
397
|
+
| equality | `==` `!=` | none |
|
|
398
|
+
| and | `&&` | left |
|
|
399
|
+
| or | `\|\|` | left |
|
|
400
|
+
| default | `??` | right |
|
|
401
|
+
| conditional | `c ? a : b` | right |
|
|
402
|
+
|
|
403
|
+
`if`/`else` and `match` are expressions; every branch has the same type (an `if` without
|
|
404
|
+
`else` in a builder yields an optional child).
|
|
405
|
+
|
|
406
|
+
## 7. Views
|
|
407
|
+
|
|
408
|
+
### 7.1 A view
|
|
409
|
+
|
|
410
|
+
```bloom
|
|
411
|
+
pub view PostRow(post: Post, compact: Bool = false) {
|
|
412
|
+
«members: @state / @list / @record / @env / let / fn»
|
|
413
|
+
body { «one View expression» }
|
|
414
|
+
}
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
- A `view` is a component: it compiles to `view(function PostRow(props) { … })` in the
|
|
418
|
+
embedded language, one memoised fiber, the same as a hand-written `view()`. Parameters are its
|
|
419
|
+
props.
|
|
420
|
+
- **`..Props` spreads a type's fields as props**: `view PostCard(..PostCardProps, dense: Bool =
|
|
421
|
+
false)`. `..card: PostCardProps` also names their whole value, `card` (emitted `props`, a
|
|
422
|
+
dependency of what reads it), to hand on as is: `summary(card: card)`. The type is a struct, a record type or a TS interface (B0204 otherwise); each field
|
|
423
|
+
is a prop of its name and type, and one with a default (or a TS optional one) may be left
|
|
424
|
+
out. Its props interface `extends` a TS interface and writes a struct's fields out; when the
|
|
425
|
+
view's `XProps` name is the spread type's own, it is `XViewProps`, and with only spreads the
|
|
426
|
+
props are the type itself.
|
|
427
|
+
- **`..r` among a call's props** spreads a struct's or record's fields as props, JSX's
|
|
428
|
+
`{...r}`: `W(..p)`, `W(..q, b: 2)` (a later prop of the same name wins). Each field a prop
|
|
429
|
+
takes is checked against it, and the record may have more. On a TS component it is `{ ...r }`,
|
|
430
|
+
which tsc checks.
|
|
431
|
+
- **`equal(old, new) { <Bool> }`** is a view member: whether two props are equal for the view,
|
|
432
|
+
compiled to `memo`'s comparator (`view(function X(props) { … }, (old, new_) => …)`); `true`
|
|
433
|
+
skips the render. `old` and `new` are the view's props record as passed, so a prop with a
|
|
434
|
+
default is optional there. It reads only them and module names (it runs outside any render).
|
|
435
|
+
A view has one (B0435), and a screen, a layout or a view without props none.
|
|
436
|
+
- A view called with arguments that are all static (literals, module values) is a static
|
|
437
|
+
chain like a node's: built once, at module scope.
|
|
438
|
+
- A `fn … -> View`, at module level or as a view member, is **inlined UI**: a plain call, no
|
|
439
|
+
fiber, no state; prefer it for repeated rows inside one view.
|
|
440
|
+
- `screen Name { … }` is a view that is the file's default export and an Expo Router route
|
|
441
|
+
(`screen()` from `@oxy.so/bloom-language/router`); `layout Name { … }` the same for `layout()`.
|
|
442
|
+
- `pub` exports; `pub default` makes it the default export.
|
|
443
|
+
|
|
444
|
+
### 7.2 Builders, modifiers and tokens
|
|
445
|
+
|
|
446
|
+
- A trailing closure passed to a parameter of type `Children` is a **builder**: each line is a
|
|
447
|
+
child (`View`, `View?` or `[View]`); `if`/`else`, `match` and `for … in` lines build
|
|
448
|
+
conditional and repeated children; `let` lines bind locals. `VStack { a; b }` is
|
|
449
|
+
`VStack(a, b)`. A conditional keeps its slot (structural identity, as SwiftUI does).
|
|
450
|
+
- **Modifiers are methods on `View`**, typed from `spec/language.json`: each node accepts its
|
|
451
|
+
own modifiers plus the universal ones (B0501 otherwise, with the closest name). Order is
|
|
452
|
+
nesting, as in the embedded language. A modifier that takes a view takes a `View?` too
|
|
453
|
+
(`.trailing(active ? Icon(i) : none)`): an absent one draws nothing.
|
|
454
|
+
- **Tokens are string literals checked against the token set** the modifier takes:
|
|
455
|
+
`.padding("md")`, `.background("primary/10")`. A wrong token is B0502 with the valid set.
|
|
456
|
+
A token in a variable has the token set's type (`let gap: Space = compact ? "sm" : "md"`);
|
|
457
|
+
with nothing expected, a conditional of string literals is their literal union (`let side =
|
|
458
|
+
card ? "96" : "48"`, as TS's `const` infers) and a literal beside a literal union joins it
|
|
459
|
+
(`c ? "md" : gutter`), so either fits a token set. `defineModifier { v in … }` reads `v` as a
|
|
460
|
+
`View` (TS's `V extends ViewModifiers<V>`); the recipe is a value (`.modifier(look ?? card)`).
|
|
461
|
+
- **Events take closures**: `.onPress { saving = true }`; an `async` closure
|
|
462
|
+
(`.onPress { await save() }`) runs as a task (section 8).
|
|
463
|
+
- **Inputs take bindings**: `TextField($draft)`, `Toggle($prefs.likes)`. `$x` projects
|
|
464
|
+
`@state x`; `$x.field` projects a field (writes `x.with(field: v)`). A closure pair is
|
|
465
|
+
`Binding(get: v, set: { v in … })`.
|
|
466
|
+
- **TS React components are nodes**: an imported component `OxyAuthPrompt` is called with its
|
|
467
|
+
props as named arguments, `OxyAuthPrompt(label: t("x"), description: t("y"))`, and a
|
|
468
|
+
trailing builder as `children`.
|
|
469
|
+
|
|
470
|
+
- A token parameter whose TypeScript type also takes a boolean takes a `Bool` (or an optional
|
|
471
|
+
one): `.allowsHitTesting(false)` (`HitTesting`), `.when(on) { … }` (`Condition | boolean`),
|
|
472
|
+
`.accessibilityState(checked: on)` (`boolean | "mixed"`). A modifier's closure whose
|
|
473
|
+
parameter has no Bloom type stays where it is passed, so TS types it from there.
|
|
474
|
+
- A modifier's parameter that TypeScript lets be `undefined` takes `none` and any optional
|
|
475
|
+
(`.onEndReached(more ? load : none, 0.5)`, `.footerContent(none)`); a parameter marked `?`
|
|
476
|
+
in its signature may be left out. `c ? a : none` is `A?` wherever it is written, so the
|
|
477
|
+
`none` branch is never held to the other's type.
|
|
478
|
+
|
|
479
|
+
### 7.3 Reactivity (compile-time)
|
|
480
|
+
|
|
481
|
+
| Declaration | Meaning | Compiles to |
|
|
482
|
+
|---|---|---|
|
|
483
|
+
| `@state x = e` | local state | `useState(e)` (lazy `() => e` when `e` is not a constant) |
|
|
484
|
+
| `@list feed = src` | a bloom-data list | `useList(src)` |
|
|
485
|
+
| `@record post = Post.record(id)` | a bloom-data record, field-level subscribed | `useRecord(Post, id)` |
|
|
486
|
+
| `@env scheme = Env.colorScheme` | an environment value | `useEnvironment(key)` |
|
|
487
|
+
| `let v = expr` (member) | derived value | inlined if trivial, else memoised on its dependencies |
|
|
488
|
+
| `let x = useThing()` | a TS hook (a `use[A-Z]` import) | the call, at the top, unconditionally |
|
|
489
|
+
| `fn f() {}` (member) | handler | a closure memoised on what it reads; hoisted to module scope when it reads nothing reactive |
|
|
490
|
+
|
|
491
|
+
**The dependency graph is known at compile time.** Every member's reads are resolved by the
|
|
492
|
+
checker: state, props, hook results and other members. The emitter then writes the memo cache
|
|
493
|
+
itself (`react/compiler-runtime`'s `c(n)`, the slot array the React Compiler uses) with exact
|
|
494
|
+
dependencies, and marks the body `"use no memo"` so the React Compiler skips it. Because values
|
|
495
|
+
are immutable, a dependency is the value itself (no mutation analysis, no proxies, no
|
|
496
|
+
subscriptions at runtime). Static subtrees are hoisted to module scope by the existing language
|
|
497
|
+
compiler pass, which runs on bloomc's output in the same process.
|
|
498
|
+
|
|
499
|
+
**Writes.** Assigning a state member in a closure is `setX(v)`; when the right side reads the
|
|
500
|
+
state (`count += 1`, `count = count + 1`) it is the functional update `setX(count => count + 1)`.
|
|
501
|
+
Reading a state member after assigning it in the same closure is B0410 (it would read the
|
|
502
|
+
render's value); bind the new value to a `let` first. Hook calls are only allowed as view
|
|
503
|
+
members and at the top level of a hook function (B0420), so the rules of hooks hold by
|
|
504
|
+
construction. A **hook function** is a `fn` named `use[A-Z]…`: its top-level `let`s and its
|
|
505
|
+
result may call hooks (not a branch, a loop or a closure), and calling it is calling a hook. A
|
|
506
|
+
`.bloom` module of `pub fn useX(…)` is a module of hooks. A hook function written without
|
|
507
|
+
`-> T` has the type of its last line (nothing when that is not a value).
|
|
508
|
+
|
|
509
|
+
**Refs.** `@ref x = v` keeps a value across renders without causing one (`useRef`). It is read
|
|
510
|
+
and written as `x` (emitted `x.current`; Bloom code never writes `.current`), in handlers,
|
|
511
|
+
effects and tasks: reading or writing it while the view draws is B0411, since the body would
|
|
512
|
+
not follow it. `.ref(x)` passes the ref itself for a host view to fill; such a ref (`@ref field:
|
|
513
|
+
ViewInstance? = none`) holds `null` in JS when empty and reads as `none`. So do `.inputRef(x)`,
|
|
514
|
+
a TS parameter typed as a ref (`RefObject<…>`, `Ref<…>`), and, while the view draws, a TS
|
|
515
|
+
argument of a type Bloom does not read (`useVisible(target: card)`; tsc checks it). A ref is
|
|
516
|
+
never a memo dependency.
|
|
517
|
+
|
|
518
|
+
### 7.4 Environment
|
|
519
|
+
|
|
520
|
+
`@env x = key` reads a value set above with `.environment(key, value)`. Keys are made with
|
|
521
|
+
`defineEnvironment` (embedded language) and imported. Text traits (`foreground`, `font`, …)
|
|
522
|
+
inherit as in the embedded language.
|
|
523
|
+
|
|
524
|
+
## 8. Effects, tasks and concurrency
|
|
525
|
+
|
|
526
|
+
**Sync throws.** `catching { … }` runs its block and gives `Result<T, Error>`: the last line's
|
|
527
|
+
value is `.ok`, and what TS code in it throws synchronously (`URL(link)`, `JSON.parse(s)`) is
|
|
528
|
+
`.err`. It is emitted as an inline `try`/`catch`, with no helper; the block cannot `return`, and
|
|
529
|
+
`?` in it ends at it (`let r = (await fetch(url))?` inside: a rejection is `.err`).
|
|
530
|
+
|
|
531
|
+
**`fail(e: Error) -> Never`** throws `e`. It is allowed where a throw has a catcher: in a
|
|
532
|
+
closure TS calls (a TS parameter's function, sync or async, or one of no Bloom type), where a
|
|
533
|
+
thrown error is how TS hears of a failure (`mutationFn: { v in if v.isEmpty { fail(Error("Empty")) } … }`,
|
|
534
|
+
a rejected promise; a sync TS callback's throw), and in `catching { … }`'s block, which gives
|
|
535
|
+
it as `.err`. As a statement or a block's last line it is `throw e;`; where a value is needed
|
|
536
|
+
(`c ? x : fail(e)`), an inline throw. Anywhere else a failure is a value: `fail` is B0222,
|
|
537
|
+
whose fix is to return `err(e)` from a function that returns a `Result`. `?` on a `Result`
|
|
538
|
+
in those closures throws the same way (4.5).
|
|
539
|
+
|
|
540
|
+
- `async fn` / `await`. Awaiting a Bloom async function yields its result. **A TS function that
|
|
541
|
+
returns a promise has the Bloom type `(A) -> Promise<T>`, and awaiting a `Promise<T>` yields
|
|
542
|
+
`Result<T, Error>`**, because a JS promise can reject; `await f()?` propagates (`await` binds tighter than `?`, as Rust's `.await?`). A synchronous
|
|
543
|
+
TS throw is a panic (a bug), as in Rust. A Bloom `async` function (or closure) never rejects,
|
|
544
|
+
so it is TS's `(A) => Promise<T>` where TS takes one (`onRefresh: reload`); a closure that
|
|
545
|
+
awaits, given for one, has `T` as its result.
|
|
546
|
+
- **An async call is awaited or spawned, never dropped**: calling an async function or a
|
|
547
|
+
promise-returning TS function without `await` is B0430, except as `task { await save(v) }`,
|
|
548
|
+
which spawns it (fire and forget, completing like a handler) and is `Unit`. A binding setter
|
|
549
|
+
that saves is `Binding(get: prefs.likes, set: { v in task { await save(.likes, v) } })`.
|
|
550
|
+
- `defer { … }` runs when the enclosing block exits, after an early `return` too (compiled to
|
|
551
|
+
`try`/`finally`); the place for "`saving = false` whatever happened". At the top of a
|
|
552
|
+
`.task { … }` it also runs when the task is cancelled (the view unmounts or its `id:`
|
|
553
|
+
changes), at once rather than at the next `await`, and then not again.
|
|
554
|
+
- **`effect { … }`** is a view member: synchronous work that runs after a render. Its
|
|
555
|
+
dependencies are inferred from its reads, exactly as the memo scopes' are (no deps array);
|
|
556
|
+
`effect(id: x) { … }` re-runs for `x` instead; a tuple `id: (a, b)` is its values, each a
|
|
557
|
+
dependency (`[a, b]`, never a fresh array per render), for `.task(id:)` too. It writes states as a handler does. A `defer`
|
|
558
|
+
at the top of its body is its cleanup, run before the next run and on unmount (several run
|
|
559
|
+
last first); a `defer` in a nested block keeps its block meaning. Once a cleanup is set the
|
|
560
|
+
effect does not `return` (B0434): return before the `defer`. It does not `await` (B0215):
|
|
561
|
+
start async work with `task { … }`, or use `.task`. It compiles to exactly one `useEffect`.
|
|
562
|
+
- **`.task { … }` on a view's body** starts when the view appears and is cancelled when it
|
|
563
|
+
disappears. `.task(id: value) { … }` restarts when `value` changes. Inside, `Task.signal` is the
|
|
564
|
+
`AbortSignal` to hand to `fetch`/bloom-data, and after every `await` a cancelled task stops.
|
|
565
|
+
Compiles to one `useEffect` with an `AbortController` (what a careful hand-written effect does).
|
|
566
|
+
- **`.onChange(of: value) { old, new in … }`** runs after a change (one `useEffect`, comparing in a
|
|
567
|
+
ref only when `old` is used).
|
|
568
|
+
- **Handlers' async closures complete**: a user action (a save, a like) is not cancelled by
|
|
569
|
+
navigating away; the state writes after unmount are no-ops.
|
|
570
|
+
- **Structured concurrency:** `let (a, b) = await all(loadA(), loadB())` (both or the first error);
|
|
571
|
+
`await race(…)`; `sleep(ms)`. A task's children are cancelled with it.
|
|
572
|
+
|
|
573
|
+
## 9. Navigation
|
|
574
|
+
|
|
575
|
+
`navigate("/settings/notifications/subscriptions")` returns a press handler (the embedded
|
|
576
|
+
language's panel-aware `navigate`); `navigate("/posts/[id]", id: post.id)` fills params.
|
|
577
|
+
Phase 1: the route table is read from the app's `app/` tree and routes become a generated enum,
|
|
578
|
+
so a wrong path is a compile error.
|
|
579
|
+
|
|
580
|
+
## 10. Modules and interop
|
|
581
|
+
|
|
582
|
+
- **A file is a module**; items are private unless `pub`. Module-level `let` must be a constant
|
|
583
|
+
expression (no calls with effects), so there is no global mutable state; shared state lives in
|
|
584
|
+
bloom-data entities, lists and models, which are explicit stores.
|
|
585
|
+
- **Prelude** (always in scope): the core types, `ok`/`err`/`none`, `all`/`race`/`sleep`, every
|
|
586
|
+
node of `spec/language.json` (`VStack`, `Text`, `Button`, …) with its modifiers, `Embed`,
|
|
587
|
+
`toast`, `navigate`.
|
|
588
|
+
- **Bloom modules:** `import { PostRow } from "./PostRow.bloom"`.
|
|
589
|
+
- **Bloom standard modules:** `import { … } from "bloom/data"` (bloom-data),
|
|
590
|
+
`"bloom/router"`, `"bloom/motion"`; they compile to the matching `@oxy.so/*` import.
|
|
591
|
+
- **TS/npm modules:** `import { useAuth } from "@oxy.so/services/ui/client"`; typed from its
|
|
592
|
+
`.d.ts` (4.7); a module that writes `export = N` (`@types/react`) exports namespace `N`'s
|
|
593
|
+
members (`import { type ComponentType, lazy, memo } from "react"`).
|
|
594
|
+
`let Panel = lazy { import("./Panel") }` (React's `lazy`, imported) is a component whose props
|
|
595
|
+
TS checks; `import("…")` is a dynamic import, emitted as written. A `use[A-Z]` function is a hook (7.3). An import is a **component** (a node,
|
|
596
|
+
7.2) when its type is a React component type (`ComponentType`, `FC`, `ComponentClass`, the
|
|
597
|
+
exotic ones: `MemoExoticComponent`, `ForwardRefExoticComponent`, `LazyExoticComponent`,
|
|
598
|
+
`NamedExoticComponent`; a wrapped component gives its props), a function of one props object
|
|
599
|
+
returning an element, `memo(Inner)` or `memo(function Inner(props: P) { … })` (`Inner`'s
|
|
600
|
+
props), or an `UpperCamel` class (`extends Component<P>` gives `P`; any other's
|
|
601
|
+
props are TS's to check), or, when it is `Foreign`, when its name is `UpperCamel` and it is
|
|
602
|
+
used as a node. A TS interface with a call signature (`ToastFn`) or an index signature
|
|
603
|
+
(`[key: string]: unknown`) is `Foreign`: callable, and taking any keys, checked by TS.
|
|
604
|
+
- **Resolution:** relative paths; the project's `tsconfig.json` `compilerOptions.paths` (`@/*`);
|
|
605
|
+
packages through `node_modules` and their `exports` (`types`, then `react-native`, `import`).
|
|
606
|
+
An explicit import shadows a prelude name. A module is never both `X.tsx` and `X.bloom`
|
|
607
|
+
(B0610): an extensionless import must mean one file.
|
|
608
|
+
- **TS importing Bloom:** bloomc writes `Name.d.bloom.ts` beside `Name.bloom` (TS's
|
|
609
|
+
`allowArbitraryExtensions`), so `import { Composer } from "./Composer.bloom"` type-checks in TS;
|
|
610
|
+
`bloom-lang-dts --root . <dirs>` writes them beside the sources (`bloomc build --out` writes
|
|
611
|
+
them into its out directory). A `view` is a node factory, as in the embedded language: TSX draws it with
|
|
612
|
+
`toElement(Composer({ maxLength: 280 }))`, not `<Composer />`; inside the embedded language it
|
|
613
|
+
is a node like any other.
|
|
614
|
+
- **Gradual:** a `.bloom` file and a `.tsx` file import each other freely, one file at a time.
|
|
615
|
+
|
|
616
|
+
## 11. What bloomc emits
|
|
617
|
+
|
|
618
|
+
For each `.bloom` file bloomc emits typed TypeScript, then runs the embedded-language pass
|
|
619
|
+
(hoisting static chains) on it in the same process, then hands it to the host transformer
|
|
620
|
+
(Metro/Babel/Noxcturnal, babel-jest, Vite). A source map composes all three back to `.bloom`.
|
|
621
|
+
A file's output can depend on the declarations of what it imports (named arguments, whether a
|
|
622
|
+
callee is a view); `bloomc build`'s cache follows imports, while Metro's and Jest's per-file
|
|
623
|
+
caches do not yet (phase 1: the adapters' cache keys include the imports' declarations).
|
|
624
|
+
|
|
625
|
+
```ts
|
|
626
|
+
// view Counter { @state n = 0; body { Button(Text("${n}")).onPress { n += 1 } } }
|
|
627
|
+
import { c as _c } from "react/compiler-runtime";
|
|
628
|
+
import { useState } from "react";
|
|
629
|
+
import { Button, Text, view } from "@oxy.so/bloom-language";
|
|
630
|
+
export const Counter = view(function Counter() {
|
|
631
|
+
"use no memo";
|
|
632
|
+
const $ = _c(3);
|
|
633
|
+
const [n, setN] = useState(0);
|
|
634
|
+
let t0;
|
|
635
|
+
if ($[0] !== n) {
|
|
636
|
+
t0 = Button(Text(`${n}`)).onPress(() => setN((n) => n + 1));
|
|
637
|
+
$[0] = n;
|
|
638
|
+
$[1] = t0;
|
|
639
|
+
} else t0 = $[1];
|
|
640
|
+
return t0;
|
|
641
|
+
});
|
|
642
|
+
```
|
|
643
|
+
|
|
644
|
+
Zero-cost rules the emitter keeps (each is gated, see the ADR):
|
|
645
|
+
|
|
646
|
+
1. Struct construction and `with` are object literals; fieldless enums are strings; `T?` is
|
|
647
|
+
`undefined`; `?`/`??`/`?.` are inline conditionals. No wrapper objects, no runtime library
|
|
648
|
+
calls for language features.
|
|
649
|
+
2. One fiber per `view`, none per `fn -> View`. Hooks only for `@state`/`@list`/`@record`/`@env`,
|
|
650
|
+
imported hooks, `.task`/`.onChange`, and one memo cache when anything is memoised.
|
|
651
|
+
3. Closures that read nothing reactive are module-scope constants.
|
|
652
|
+
4. `"use no memo"` on every emitted view body; bloomc owns the memoisation.
|
|
653
|
+
|
|
654
|
+
## 12. Standard library surface (draft)
|
|
655
|
+
|
|
656
|
+
| Type | Members (each compiles to the JS intrinsic, inline) |
|
|
657
|
+
|---|---|
|
|
658
|
+
| `String` | `count`, `isEmpty`, `slice(a, b)`, `contains`, `startsWith`, `endsWith`, `lowercased()`, `uppercased()`, `trimmed()`, `split(sep)`, `replace(a, b)` (every match; with a `RegExp` pattern JS's `replace`, its flags saying how often), `match(re)` (TS's `RegExpMatchArray | null`), `toInt() -> Int?`, `toFloat() -> Float?` |
|
|
659
|
+
| `Int`/`Float` | `toFloat()`, `rounded()`, `floor()`, `ceil()`, `truncated()`, `abs()`, `min(b)`, `max(b)`, `clamp(lo, hi)`, `format(…)` (Intl) |
|
|
660
|
+
| `[T]` | `count`, `isEmpty`, `first`, `last`, `map`, `filter`, `compactMap`, `reduce`, `find -> T?`, `findIndex -> Int?`, `contains`, `sorted(by:)`, `reversed()`, `prefix(n)`, `dropFirst(n)`, `appending(x)`, `inserting(x, at:)`, `removing(at:)`, `joined(sep)`, `flatMap`, `any { }` / `all { }` (`some`/`every`), `slice(a, b)`, `indexOf(x) -> Int?`, `enumerated() -> [(Int, T)]` (`xs.enumerated().map { (i, x) in … }` and `for (i, x) in xs.enumerated()` build no pairs: `xs.map((x, i) => …)`, `xs.entries()`), `[i] -> T?`; there is no `forEach` (write `for`); the literal `[..a, b]` spreads a list in place (`[...a, b]`) |
|
|
661
|
+
| `[String: V]` | `count`, `isEmpty`, `[k] -> V?`, `keys`, `values`, `entries`, `setting(k, v)`, `removing(k)` |
|
|
662
|
+
| `Map<K, V>` | `Map(entries)` / `Map()` / `Map<K, V>()` (`new Map`), `count`, `isEmpty`, `get(k) -> V?`, `contains(k)`, `keys`, `values`, `entries` (lists), `setting(k, v)`, `removing(k)`; `for (k, v) in m` |
|
|
663
|
+
| `Set<T>` | `Set(values)` / `Set()` (`new Set`), `count`, `isEmpty`, `contains(x)`, `values`, `inserting(x)`, `removing(x)`; `for x in s` |
|
|
664
|
+
| prelude | `min(a, b, …)` / `max` (also `..xs`), `abs(x)`, `round(x)` / `floor` / `ceil` (to `Int`): `Math.…`; `Int(s) -> Int?`, `Float(s) -> Float?` (`Double(s)` the same) in place of `Number(…)`; `x.clamped(lo, hi)`; `Regex(pattern, flags?)`, a JS `RegExp` (`new RegExp`; `re.test(s)` is TS's); `catching { … } -> Result<T, Error>`: the block's last line is `ok`, what TS code in it throws is `err` (emitted as a local `try`/`catch`; no `return` inside, and `?` there throws to it) |
|
|
665
|
+
| `Option`/`Result` | as in 4.5 |
|
|
666
|
+
| tasks | `Task.signal`, `all`, `race`, `sleep`, `Task.isCancelled` |
|
|
667
|
+
| UI | the nodes, modifiers and tokens of `spec/language.json`; `defineTokens` in a `let` |
|
|
668
|
+
|
|
669
|
+
`[k: v]` is the dictionary literal (string keys). `Map` and `Set` are the prelude's JS
|
|
670
|
+
collections: a method that changes one gives a new one (`setting`, `inserting`, `removing`
|
|
671
|
+
copy it), so a `var` or `@state` holding one is assigned as any other value
|
|
672
|
+
(`picked = picked.inserting(id)`), and they have no `==` (B0210). A TS `Map`/`ReadonlyMap`/
|
|
673
|
+
`Set`/`ReadonlySet` reads as one.
|
|
674
|
+
|
|
675
|
+
## 13. Diagnostics
|
|
676
|
+
|
|
677
|
+
Every error has a code, a primary span, a one-line message, labels on related spans, a
|
|
678
|
+
`help:` with the fix (and a machine-applicable edit when there is one), and a `= docs:` link:
|
|
679
|
+
|
|
680
|
+
```text
|
|
681
|
+
error[B0502]: `"medium"` is not a space token
|
|
682
|
+
--> components/settings/pages/notifications.bloom:42:18
|
|
683
|
+
|
|
|
684
|
+
42 | .padding("medium")
|
|
685
|
+
| ^^^^^^^^ expected one of: none 2xs xs sm md lg xl 2xl 3xl 4xl 5xl
|
|
686
|
+
|
|
|
687
|
+
help: did you mean `"md"`?
|
|
688
|
+
= docs: https://github.com/OxyHQ/Bloom/blob/main/docs/bloom-language-tokens.mdx#space
|
|
689
|
+
```
|
|
690
|
+
|
|
691
|
+
Code ranges: B01xx syntax, B02xx types, B03xx patterns, B04xx state and effects, B05xx UI
|
|
692
|
+
(nodes, modifiers, tokens), B06xx interop, B09xx style warnings. Assigned so far include B0201
|
|
693
|
+
(mismatched type, with the annotation to write), B0203 (nested optional), B0210 (structural
|
|
694
|
+
`==`), B0220 (`?` inside a condition), B0301/B0302 (non-exhaustive / unreachable `match`), B0402
|
|
695
|
+
(captured `var`), B0410 (state read after write), B0411 (a `@ref` used while the view draws), B0420 (hook not a view member), B0430 (async
|
|
696
|
+
call neither awaited nor spawned), B0431 (`.task` not on the body's root), B0432 (`Task.signal`
|
|
697
|
+
outside a task), B0434 (an effect returns after its cleanup is set), B0435 (a second `equal`, or one without props), B0501/B0502 (modifier / token), B0601 (untyped `Foreign` use), B0602 (no
|
|
698
|
+
declarations found for a TS import), B0610 (`X.tsx` beside `X.bloom`). Parsing recovers at item,
|
|
699
|
+
statement and closing-brace boundaries, so one typo reports one error.
|
|
700
|
+
|
|
701
|
+
## 14. Formatting
|
|
702
|
+
|
|
703
|
+
`bloomc fmt` is the only style (no options): 2-space indent, 100 columns, one modifier per line
|
|
704
|
+
once a chain does not fit on one line, trailing commas in multi-line argument lists,
|
|
705
|
+
members ordered as written, blank lines kept (at most one), imports sorted by path, struct fields
|
|
706
|
+
and enum variants one per line. A block with one statement stays on one line when it fits (a
|
|
707
|
+
view's `body` never does); an `if`/`else` chain is on one line together or breaks together; a
|
|
708
|
+
builder line's chain breaks one modifier per line once its builder spans lines; a chain inside an
|
|
709
|
+
expression breaks only with two or more calls. A binary expression breaks after its operator, but
|
|
710
|
+
before `<` and `>` (a line ending in `>` may close a type's arguments; one ending in `<` goes on).
|
|
711
|
+
Formatting is idempotent and preserves comments.
|
|
712
|
+
|
|
713
|
+
## 15. Cheat sheet for agents
|
|
714
|
+
|
|
715
|
+
1. A file is a module. `pub view Name(params) { members; body { … } }`; a route is `screen`.
|
|
716
|
+
2. UI is a builder: one child per line; `if`, `for`, `match` build children; modifiers chain with
|
|
717
|
+
`.name(…)` on the next line; order is nesting.
|
|
718
|
+
3. Every style value is a token string: `.padding("md")`, `.foreground("muted")`.
|
|
719
|
+
4. State is `@state x = v`; write it with `x = …` in a closure; inputs take `$x`.
|
|
720
|
+
5. Derived values are `let` members; handlers are `fn` members or closures. Never memoise by hand.
|
|
721
|
+
6. No null: `T?`, `none`, `??`, `?.`, `if let`. No exceptions: `Result`, `?`, `match`.
|
|
722
|
+
7. `match` arms start with `case`; an enum case at the start of a line is `Type.case`.
|
|
723
|
+
8. Awaiting a TS promise gives `Result<T, Error>`.
|
|
724
|
+
9. TS: `import { x } from "pkg"`; hooks (`useX`) only as view members; TS components are nodes
|
|
725
|
+
with named-argument props; named arguments to a TS function become one options object; a TS
|
|
726
|
+
value goes straight into any typed position (tsc checks it there).
|
|
727
|
+
10. An async call is `await`ed or spawned with `task { … }`; `defer { … }` for cleanup.
|
|
728
|
+
11. Navigation: `navigate("/path")` in screens; inside a surface with its own router (a settings
|
|
729
|
+
modal), use that surface's router hook.
|
|
730
|
+
12. Run `bloomc check` and `bloomc fmt`; every error says what to write instead.
|