Skip to main content

submilli_engine/stdlib/session/
declaration.rs

1//! Type surface of `submilli:session`.
2//!
3//! `get` is declared generic in `T` but must never reach the ordinary
4//! generic-call lowering: that sets `return_cast`, which codegen emits as a
5//! Wasm representation cast rather than a structural check, so wrong-shaped
6//! stored data would arrive statically typed and never validated. The
7//! typechecker intercepts this symbol by mangled name and rewrites the call
8//! into a checked `Cast` instead — see `infer_generic_call`. The declaration
9//! and that interception are a matched pair; neither is sound alone.
10
11use std::collections::BTreeMap;
12
13use crate::{
14    Dispatch, PackageDeclaration, Param, PropertySig, Span, Type, TypeKind, TypeSymbol, ValueKind,
15    ValueSymbol,
16};
17
18use super::{MAX_LIST_LIMIT, MODULE_NAME};
19
20/// The export name of the checked read. Shared with the typechecker's
21/// interception (`checked_session_get`) so the declaration and the check that
22/// keeps it sound can't drift apart.
23const SESSION_GET: &str = "get";
24
25/// Whether `mangled` is this package's checked read. Matching the
26/// package-export mangled name rather than a receiver name is what makes the
27/// typechecker's rewrite independent of how the symbol was imported —
28/// `session.get`, `kv.get` under an aliased namespace import, and a
29/// named-import `get` all carry this name, while a user's own `session`
30/// binding never can.
31pub fn is_checked_get(mangled: &crate::MangledName) -> bool {
32    *mangled == crate::mangle::package_symbol(MODULE_NAME, SESSION_GET)
33}
34
35/// The type parameter of [`SESSION_GET`].
36const GET_TYPE_PARAM: &str = "T";
37
38pub fn package_declaration() -> PackageDeclaration {
39    let mut defs = PackageDeclaration::with_package(MODULE_NAME);
40    insert_entry_interface(&mut defs);
41    insert_page_interface(&mut defs);
42    insert_generic_fn(
43        &mut defs,
44        SESSION_GET,
45        vec![GET_TYPE_PARAM.to_string()],
46        vec![Param::new("key", Type::String)],
47        Type::union(vec![
48            Type::TypeVar(GET_TYPE_PARAM.to_string()),
49            Type::Undefined,
50        ]),
51        "/**\n * Read a session value, checked against `T`. The stored value is tested \
52         structurally — every field, element, and union arm — and a mismatch throws a \
53         catchable `TypeError` rather than handing back a wrongly-typed value, so \
54         `get<Progress>(\"progress\")` returns a real `Progress`, `undefined` for a missing key, or throws.\n *\n \
55         * Returns `T | undefined`: a missing key returns `undefined`; a stored `null` \
56         is preserved when `T` permits it and otherwise throws a `TypeError`.\n *\n * `T` must be a type the runtime can \
57         verify: object, array, tuple, union, and primitive shapes. A bare `unknown`, a \
58         generic parameter of the calling function, a class, or an interface with \
59         methods is rejected at compile time.\n * @param key Session key. Exact UTF-16 \
60         code units; no normalization, no path semantics.\n * @capability session.read \
61         { key: $key }\n */",
62    );
63    insert_fn(
64        &mut defs,
65        "has",
66        vec![Param::new("key", Type::String)],
67        Type::Boolean,
68        "/**\n * Whether the session holds an entry for `key`. A stored `null` is an \
69         entry and answers `true`.\n * @param key Session key.\n * @capability \
70         session.read { key: $key }\n */",
71    );
72    insert_fn(
73        &mut defs,
74        "set",
75        vec![
76            Param::new("key", Type::String),
77            Param::new("value", Type::Unknown),
78        ],
79        Type::Void,
80        "/**\n * Store `value` under `key`, replacing any previous entry. `value` must \
81         be JSON-compatible data — `null`, a boolean, a finite number, a string, an \
82         array, or a plain object of those. A function, a `Map`/`Set`, a host handle, \
83         or a value reachable from itself is rejected and the previous entry is left \
84         intact. Traps if the value or the session exceeds its configured size \
85         limits.\n * @param key Session key.\n * @param value The data to store.\n * \
86         @capability session.write { key: $key }\n */",
87    );
88    insert_fn(
89        &mut defs,
90        "remove",
91        vec![Param::new("key", Type::String)],
92        Type::Boolean,
93        "/**\n * Delete `key`. Returns `true` when an entry existed.\n * @param key \
94         Session key.\n * @capability session.remove { key: $key }\n */",
95    );
96    insert_fn(
97        &mut defs,
98        "list",
99        vec![
100            Param::new("prefix", Type::String),
101            Param::new("limit", Type::Number),
102            Param::with_default(
103                "cursor",
104                Type::union(vec![Type::String, Type::Undefined]),
105                crate::DefaultValue::Undefined,
106            ),
107        ],
108        page_type(),
109        &format!(
110            "/**\n * Enumerate session keys starting with `prefix`, in UTF-16 code-unit \
111             order. Returns metadata only — `key` and `sizeBytes` — never the stored \
112             values; read one with `get`. Pass `\"\"` to list every key.\n *\n * Each \
113             page holds at most `limit` entries. `nextCursor` is a `string` when the \
114             listing is unfinished and `undefined` only when no further matching key remains, \
115             so page until it is `undefined` rather than until a page is short: a page can be \
116             short because the scan bound was reached, not because the keys ran out. Pass \
117             the previous page's `nextCursor` back unchanged; a cursor minted for a \
118             different prefix, or one this runtime did not issue, throws.\n *\n * Each \
119             page reflects the store as it is when the page is read, not a snapshot: a \
120             key written behind a cursor is not seen until the listing restarts.\n *\n * \
121             Keys the policy does not permit reading are omitted, and neither the entry \
122             count nor the cursor reveals them.\n * @param prefix Key prefix, matched as \
123             exact UTF-16 code units — no normalization, no path semantics. `\"\"` \
124             matches every key.\n * @param limit Maximum entries in the page; 1 to \
125             {MAX_LIST_LIMIT}. Outside that range throws.\n * @param cursor The previous \
126             page's `nextCursor`; omit it to start at the first key.\n * @capability \
127             session.list {{ prefix: $prefix }}\n * @capability \
128             session.read {{ key: $key }} per candidate key\n */"
129        ),
130    );
131    defs
132}
133
134fn entry_type() -> Type {
135    Type::InterfaceRef {
136        mangled: crate::mangle::package_symbol(MODULE_NAME, "Entry"),
137        package: crate::Package(MODULE_NAME.to_string()),
138        name: "Entry".to_string(),
139        args: Vec::new(),
140    }
141}
142
143fn page_type() -> Type {
144    Type::InterfaceRef {
145        mangled: crate::mangle::package_symbol(MODULE_NAME, "Page"),
146        package: crate::Package(MODULE_NAME.to_string()),
147        name: "Page".to_string(),
148        args: Vec::new(),
149    }
150}
151
152fn insert_entry_interface(defs: &mut PackageDeclaration) {
153    let mut properties = BTreeMap::new();
154    insert_property(
155        &mut properties,
156        "key",
157        Type::String,
158        "/** The session key, in the exact code units it was stored under. */",
159    );
160    insert_property(
161        &mut properties,
162        "sizeBytes",
163        Type::Number,
164        "/** Serialized size of the stored value in bytes — the value alone, not the key and not the store's per-entry overhead. */",
165    );
166    insert_interface(
167        defs,
168        "Entry",
169        properties,
170        "/** One key a `list` page discloses. Carries the key and the value's size; the value itself is never part of a listing — call `get(entry.key)` for it. */",
171    );
172}
173
174fn insert_page_interface(defs: &mut PackageDeclaration) {
175    let mut properties = BTreeMap::new();
176    insert_property(
177        &mut properties,
178        "entries",
179        Type::Array(Box::new(entry_type())),
180        "/** The keys this page discloses, in UTF-16 code-unit order. May be shorter than `limit`, or empty, while `nextCursor` is still defined. */",
181    );
182    insert_property(
183        &mut properties,
184        "nextCursor",
185        Type::union(vec![Type::String, Type::Undefined]),
186        "/** Opaque cursor for the next page, or `undefined` when no further matching key remains. Pass it back to `list` unchanged, with the same prefix. */",
187    );
188    insert_interface(
189        defs,
190        "Page",
191        properties,
192        "/** One page of a `list` call: the `entries` it discloses and the `nextCursor` that continues it. Constructed only by `list`. */",
193    );
194}
195
196fn insert_interface(
197    defs: &mut PackageDeclaration,
198    name: &str,
199    properties: BTreeMap<String, PropertySig>,
200    doc: &str,
201) {
202    defs.types.insert(
203        name.to_string(),
204        TypeSymbol {
205            name: name.to_string(),
206            mangled_name: crate::mangle::package_symbol(MODULE_NAME, name),
207            declaration_span: Span::at(crate::FileId::SESSION),
208            kind: TypeKind::Interface {
209                index: None,
210                generics: Vec::new(),
211                methods: BTreeMap::new(),
212                properties,
213                dispatch: Dispatch::Direct,
214                doc: crate::doc(crate::FileId::SESSION, doc),
215            },
216        },
217    );
218}
219
220fn insert_property(
221    properties: &mut BTreeMap<String, PropertySig>,
222    name: &str,
223    ty: Type,
224    doc: &str,
225) {
226    properties.insert(
227        name.to_string(),
228        PropertySig {
229            ty,
230            readonly: true,
231            optional: false,
232            intrinsic: false,
233            doc: crate::doc(crate::FileId::SESSION, doc),
234        },
235    );
236}
237
238fn insert_fn(defs: &mut PackageDeclaration, name: &str, params: Vec<Param>, ret: Type, doc: &str) {
239    insert_generic_fn(defs, name, Vec::new(), params, ret, doc);
240}
241
242fn insert_generic_fn(
243    defs: &mut PackageDeclaration,
244    name: &str,
245    generics: Vec<String>,
246    params: Vec<Param>,
247    ret: Type,
248    doc: &str,
249) {
250    defs.values.insert(
251        name.to_string(),
252        ValueSymbol {
253            name: name.to_string(),
254            mangled_name: crate::mangle::package_symbol(MODULE_NAME, name),
255            declaration_span: Span::at(crate::FileId::SESSION),
256            kind: ValueKind::Function {
257                generics,
258                params,
259                ret,
260                type_predicate: None,
261                doc: crate::doc(crate::FileId::SESSION, doc),
262            },
263        },
264    );
265}