ferrovue 0.3.0 → 0.5.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.
Files changed (106) hide show
  1. package/README.md +225 -42
  2. package/dist/attrs.d.ts +3 -53
  3. package/dist/attrs.js +41 -469
  4. package/dist/calls.d.ts +4 -0
  5. package/dist/calls.js +221 -0
  6. package/dist/children.d.ts +16 -0
  7. package/dist/children.js +286 -0
  8. package/dist/classes.d.ts +13 -0
  9. package/dist/classes.js +176 -0
  10. package/dist/cli.js +31 -22
  11. package/dist/client.d.ts +35 -2
  12. package/dist/client.js +77 -14
  13. package/dist/compiler.d.ts +1 -1
  14. package/dist/compiler.js +31 -92
  15. package/dist/component.d.ts +3 -1
  16. package/dist/component.js +123 -104
  17. package/dist/constants.d.ts +42 -0
  18. package/dist/constants.js +292 -0
  19. package/dist/context.d.ts +29 -67
  20. package/dist/context.js +13 -38
  21. package/dist/diagnostics.d.ts +23 -0
  22. package/dist/diagnostics.js +30 -0
  23. package/dist/diff.d.ts +0 -3
  24. package/dist/diff.js +0 -9
  25. package/dist/emitter.d.ts +0 -8
  26. package/dist/emitter.js +0 -12
  27. package/dist/errors.d.ts +867 -0
  28. package/dist/errors.js +330 -0
  29. package/dist/expr.d.ts +1 -70
  30. package/dist/expr.js +142 -934
  31. package/dist/fallthrough.d.ts +9 -0
  32. package/dist/fallthrough.js +78 -0
  33. package/dist/fixture.d.ts +4 -10
  34. package/dist/fixture.js +38 -27
  35. package/dist/hydration.d.ts +15 -0
  36. package/dist/hydration.js +80 -0
  37. package/dist/index.d.ts +3 -0
  38. package/dist/index.js +2 -0
  39. package/dist/islands.d.ts +1 -0
  40. package/dist/islands.js +1 -0
  41. package/dist/link-router.d.ts +24 -0
  42. package/dist/link-router.js +36 -0
  43. package/dist/lists.d.ts +0 -11
  44. package/dist/lists.js +34 -60
  45. package/dist/loops.d.ts +3 -0
  46. package/dist/loops.js +168 -0
  47. package/dist/model.d.ts +46 -144
  48. package/dist/model.js +150 -18
  49. package/dist/narrowing.d.ts +27 -0
  50. package/dist/narrowing.js +157 -0
  51. package/dist/numbers.d.ts +8 -0
  52. package/dist/numbers.js +73 -0
  53. package/dist/parens.d.ts +0 -27
  54. package/dist/parens.js +0 -44
  55. package/dist/plugin.d.ts +84 -0
  56. package/dist/plugin.js +26 -0
  57. package/dist/plugins/client-only.d.ts +8 -0
  58. package/dist/plugins/client-only.js +107 -0
  59. package/dist/plugins/i18n.d.ts +23 -0
  60. package/dist/{i18n.js → plugins/i18n.js} +88 -31
  61. package/dist/plugins/index.d.ts +2 -0
  62. package/dist/plugins/index.js +10 -0
  63. package/dist/plugins/router-link.d.ts +8 -0
  64. package/dist/{router.js → plugins/router-link.js} +52 -91
  65. package/dist/plugins/router.d.ts +42 -0
  66. package/dist/plugins/router.js +256 -0
  67. package/dist/plugins/scoped.d.ts +12 -0
  68. package/dist/plugins/scoped.js +125 -0
  69. package/dist/plugins/shared-types.d.ts +2 -0
  70. package/dist/plugins/shared-types.js +7 -0
  71. package/dist/plugins/stores.d.ts +37 -0
  72. package/dist/plugins/stores.js +379 -0
  73. package/dist/plugins/teleport.d.ts +5 -0
  74. package/dist/plugins/teleport.js +55 -0
  75. package/dist/plugins/twins.d.ts +10 -0
  76. package/dist/plugins/twins.js +164 -0
  77. package/dist/routes.d.ts +10 -0
  78. package/dist/routes.js +6 -0
  79. package/dist/rust.d.ts +1 -7
  80. package/dist/rust.js +56 -174
  81. package/dist/script.d.ts +3 -6
  82. package/dist/script.js +127 -140
  83. package/dist/settle.d.ts +6 -0
  84. package/dist/settle.js +34 -0
  85. package/dist/slots.d.ts +13 -0
  86. package/dist/slots.js +160 -0
  87. package/dist/strings.d.ts +13 -0
  88. package/dist/strings.js +208 -0
  89. package/dist/styles.d.ts +14 -0
  90. package/dist/styles.js +181 -0
  91. package/dist/template.d.ts +1 -42
  92. package/dist/template.js +25 -749
  93. package/dist/testing.d.ts +2 -0
  94. package/dist/testing.js +4 -10
  95. package/dist/types.d.ts +2 -0
  96. package/dist/typescript.d.ts +2 -14
  97. package/dist/typescript.js +53 -59
  98. package/dist/vite.d.ts +2 -1
  99. package/dist/vite.js +11 -32
  100. package/package.json +15 -6
  101. package/dist/i18n.d.ts +0 -27
  102. package/dist/router.d.ts +0 -17
  103. package/dist/scoped.d.ts +0 -24
  104. package/dist/scoped.js +0 -177
  105. package/dist/stores.d.ts +0 -6
  106. package/dist/stores.js +0 -229
package/dist/expr.js CHANGED
@@ -1,146 +1,14 @@
1
- /* Expressions translated to Rust, each with the type it evaluates to. */
2
- import { BOOL, fail, FLOAT, GenError, INT, opt, rustStr, sameTy, snake, STR, UNDEF } from "./model.js";
3
- import { CONFIG_FILE, ctx } from "./context.js";
1
+ import { absence, BOOL, fail, FLOAT, GenError, INT, joinAbsence, nothing, NULL, opt, rustStr, sameTy, snake, STR, UNDEF, withAbsence } from "./model.js";
2
+ import { ctx } from "./context.js";
4
3
  import { lookupStruct, markHome } from "./typescript.js";
5
- import { translate } from "./i18n.js";
6
- import { AS, atom, bare, binary, condition, enclosed, FLIPPED, ifElse, logical, negate, not, occurrences, operand, receiver, strArg, UNARY } from "./parens.js";
7
- import { collected, computed, computedListMethod, items, listMethod, objectCall } from "./lists.js";
8
- /** The refusal for a string that may hold half of a surrogate pair, used where that half matters. */
9
- export function lonely(what) {
10
- return `${what} with a string that may hold half of a surrogate pair (cut by \`slice\`, \`substring\`, \`at\`, \`charAt\`, \`split("")\` and the like): JavaScript keeps the half, which can match, order or join with another where ferrovue holds U+FFFD`;
11
- }
12
- /** Two strings meeting, where a half of a surrogate pair — which ferrovue holds as U+FFFD — would
13
- * change the result:
14
- * - `equal`: two halves may differ, and a half never equals a literal U+FFFD;
15
- * - `order`: a half orders as a surrogate, below U+E000, where U+FFFD orders above — the same only
16
- * against a literal of characters below U+D800, which both order after;
17
- * - `search`: a half searched for (`b`) matches half of a whole pair in `a`;
18
- * - `join`: two halves side by side join into one character.
19
- * A string holding U+FFFD in the data still equals, or is found in, a half: README, "Strings". */
20
- export function meet(comp, a, b, what, n, how) {
21
- const literal = (v) => v.code.startsWith('"');
22
- const fffd = (v) => literal(v) && v.code.includes("\u{FFFD}");
23
- const low = (v) => literal(v) && !/[\u{D800}-\u{10FFFF}]/u.test(v.code);
24
- const refused = how === "order" ? (a.lone && !low(b)) || (b.lone && !low(a))
25
- : how === "join" ? a.lone && b.lone
26
- : how === "search" ? b.lone || (a.lone && fffd(b))
27
- : (a.lone && b.lone) || (a.lone && fffd(b)) || (b.lone && fffd(a));
28
- if (refused)
29
- fail(comp, lonely(what), n);
30
- }
31
- /** `lone` for a value built from these: whether any of them may hold half of a surrogate pair. */
32
- function loneOf(...vs) {
33
- return vs.some((v) => v?.lone) ? { lone: true } : {};
34
- }
35
- /** Whether a string is a non-empty literal: a separator that always parts what it joins. */
36
- function nonEmptyLiteral(v) {
37
- return /^"[^"]/.test(v.code);
38
- }
39
- /** Whether a string expression borrows from a temporary it builds — \`&*format!(…)\`, a call that
40
- * returns a \`String\` — rather than from the props or the state. Such a borrow ends with the block
41
- * it is in, so a branch of \`?:\` or \`||\` must hand back the string itself. */
42
- export function isTemporary(v) {
43
- if (v.ty.k !== "str")
44
- return false;
45
- // A trim borrows from its argument, so it is a temporary when that is.
46
- const trimmed = /^fv::js_trim(?:_start|_end)?\(([^]*)\)$/.exec(v.code);
47
- if (trimmed?.[1] !== undefined)
48
- return isTemporary({ code: trimmed[1].replace(/^&(?!\*)/, "&*"), ty: v.ty });
49
- // A borrow of anything but a field: a string built by \`format!\` or a call, or a \`Cow\` made of
50
- // the branches of \`?:\` or \`||\`.
51
- // So is an optional string with such a fallback: `x.unwrap_or(&*format!(…))`.
52
- return /^&\*(?![\w.]+$)/.test(v.code) || /\.unwrap_or\(&\*(?![\w.]+\)$)/.test(v.code);
53
- }
54
- /** A string as a \`Cow\`: borrowed when it lives on, owned when it is a temporary. The \`Cow\` is
55
- * itself a temporary of the whole statement, so the \`&str\` taken from it lives to its end. A
56
- * \`String\` built for the purpose is moved into it, and one that is already a \`Cow\` — a branch
57
- * of \`?:\` or \`||\` — is taken as it is. */
58
- export function asCow(v) {
59
- if (!isTemporary(v))
60
- return `std::borrow::Cow::<str>::Borrowed(${bare(v.code)})`;
61
- const built = /^&\*(.*)$/s.exec(v.code)?.[1];
62
- if (built === undefined)
63
- return `std::borrow::Cow::<str>::Owned(${atom(v.code)}.to_owned())`;
64
- if (enclosed(built))
65
- return bare(built);
66
- // A routine's `Cow` may borrow a string built in the same branch, which ends with it: owned.
67
- if (yieldsCow(built))
68
- return built.startsWith("fv::") ? `std::borrow::Cow::<str>::Owned(${built}.into_owned())` : bare(built);
69
- // A routine that hands back part of the string it is given, as a `&str`: copied out.
70
- if (/^fv::js_(?:char_at|trim|trim_start|trim_end)\(/.test(built))
71
- return `std::borrow::Cow::<str>::Owned(${built}.to_owned())`;
72
- return `std::borrow::Cow::<str>::Owned(${built})`;
73
- }
74
- /** Whether built code is a `Cow<str>` already: a runtime routine that borrows when it can
75
- * (`js_slice`, `js_replace`, `js_pad_start`, …), or a fallback taken from one (`.unwrap_or(Cow…)`). */
76
- export function yieldsCow(code) {
77
- // The routine's call is the whole of it: `fv::js_slice(…).to_lowercase()` is a `String`.
78
- const routine = /^fv::js_(?:slice|substring|replace|replace_all|pad_start|pad_end)(?=\()/.exec(code);
79
- if (routine !== null)
80
- return enclosed(code.slice(routine[0].length));
81
- // The fallback is the last call of it: `format!("{}a", x.unwrap_or(Cow…))` is a `String`.
82
- const fallback = code.lastIndexOf(".unwrap_or(std::borrow::Cow::<str>::");
83
- return fallback >= 0 && enclosed(code.slice(fallback + ".unwrap_or".length));
84
- }
85
- /** Whether a value is a JavaScript number: an integer or a fraction. */
86
- export function isNumber(ty) {
87
- return ty.k === "int" || ty.k === "float";
88
- }
89
- /** A number as an `f64`, as JavaScript holds every number. */
90
- export function asF64(v) {
91
- if (v.f64 !== undefined)
92
- return v.f64;
93
- return v.ty.k === "float" ? v.code : `${operand(v.code, AS)} as f64`;
94
- }
95
- /** An integer computed on doubles, as JavaScript computes it: the \`i64\` and the double it came from. */
96
- function intFromF64(f64) {
97
- return { code: `${operand(f64, AS)} as i64`, ty: INT, f64 };
98
- }
99
- /** A double as a Rust literal: JavaScript's own spelling, which Rust reads back to the same double. */
100
- function floatLiteral(x) {
101
- if (Number.isNaN(x))
102
- return "f64::NAN";
103
- if (!Number.isFinite(x))
104
- return x > 0 ? "f64::INFINITY" : "f64::NEG_INFINITY";
105
- const spelled = String(Math.abs(x)).replace("e+", "e");
106
- return `${x < 0 || Object.is(x, -0) ? "-" : ""}${/[.e]/.test(spelled) ? spelled : `${spelled}.0`}f64`;
107
- }
108
- /** A number known at generation time — a literal, or literals JavaScript computed — as an integer
109
- * when it is one of the operations that keep integers, a fraction otherwise. */
110
- function numberVal(x, int) {
111
- if (!int)
112
- return { code: floatLiteral(x), ty: FLOAT, num: x };
113
- if (!Number.isSafeInteger(x))
114
- return { ...intFromF64(floatLiteral(x)), num: x };
115
- // `-0` is the integer 0, and the double it came from keeps its sign.
116
- return { code: `${x === 0 ? 0 : x}i64`, ty: INT, f64: floatLiteral(x), num: x };
117
- }
118
- /** `a op b` on two numbers JavaScript computes now, as it would at run time. */
119
- function fold(a, op, b) {
120
- switch (op) {
121
- case "+":
122
- return a + b;
123
- case "-":
124
- return a - b;
125
- case "*":
126
- return a * b;
127
- case "/":
128
- return a / b;
129
- case "%":
130
- return a % b;
131
- case "<":
132
- return a < b;
133
- case ">":
134
- return a > b;
135
- case "<=":
136
- return a <= b;
137
- case ">=":
138
- return a >= b;
139
- default:
140
- return a === b;
141
- }
142
- }
143
- /** A type as an error names it. */
4
+ import { claim } from "./plugin.js";
5
+ import { atom, bare, binary, enclosed, logical, negate, not, occurrences, strArg } from "./parens.js";
6
+ import { collected } from "./lists.js";
7
+ import { asCow, formatted, isTemporary, loneOf, meet, stringsEqual } from "./strings.js";
8
+ import { arithmetic, asF64, compare, intFromF64, isNumber, negatedOrder, numberVal } from "./numbers.js";
9
+ import { boolOf, checkNullTest, choice, known, narrowing, narrowTo, nullTest, pathOf, presence, truthy } from "./narrowing.js";
10
+ import { call, isObjectCall } from "./calls.js";
11
+ import { constOf, constVal } from "./constants.js";
144
12
  export function describeTy(ty) {
145
13
  switch (ty.k) {
146
14
  case "str":
@@ -159,25 +27,27 @@ export function describeTy(ty) {
159
27
  case "child":
160
28
  return "an object";
161
29
  case "opt":
30
+ if (ty.none === "null")
31
+ return `${describeTy(ty.of)} or \`null\``;
32
+ if (ty.none === "either")
33
+ return `${describeTy(ty.of)}, \`null\` or \`undefined\``;
162
34
  return `an optional ${describeTy(ty.of).replace(/^an? /, "")}`;
163
35
  case "undef":
164
36
  return "`undefined`";
165
- case "query":
166
- return "a query value";
37
+ case "null":
38
+ return "`null`";
167
39
  default:
168
- return "a value of another kind";
40
+ return claim((p) => p.values?.describe?.(ty)) ?? "a value of another kind";
169
41
  }
170
42
  }
171
43
  export function fieldVal(comp, base, ty, js, node) {
172
44
  if (ty.k !== "struct")
173
- fail(comp, `\`.${js}\` on a value that is not an object`, node);
45
+ fail(comp, "FV0604", `\`.${js}\` on a value that is not an object`, node);
174
46
  const { st, owner } = lookupStruct(comp, ty);
175
47
  const found = st?.fields.find((x) => x.js === js);
176
48
  if (!found)
177
- fail(comp, `\`${ty.name}\` has no field \`${js}\``, node);
178
- // A field of a type another component declares names that component's types.
49
+ fail(comp, "FV0605", `\`${ty.name}\` has no field \`${js}\``, node);
179
50
  const f = owner === comp ? found : { ...found, ty: markHome(found.ty, owner.name) };
180
- // A scoped slot's props already hold borrows and copies: each field is read as it is.
181
51
  if (st.slot)
182
52
  return { code: `${base}.${f.rust}`, ty: f.ty };
183
53
  const place = `${base}.${f.rust}`;
@@ -202,351 +72,53 @@ export function fieldVal(comp, base, ty, js, node) {
202
72
  return { code: `${place}.as_deref()`, ty: f.ty };
203
73
  if (f.ty.of.k === "int" || f.ty.of.k === "float" || f.ty.of.k === "bool")
204
74
  return { code: place, ty: f.ty };
205
- // An object or a list, borrowed: `Option<&T>`, which a `v-if` narrows to the `&T`.
206
75
  return { code: `${place}.as_ref()`, ty: f.ty };
207
76
  default:
208
77
  return { code: place, ty: f.ty };
209
78
  }
210
79
  }
211
- /** A value's truthiness when it is known at generation time: a boolean constant, a string literal,
212
- * a number JavaScript computed. */
213
- export function known(v) {
214
- if (v.konst !== undefined)
215
- return v.konst;
216
- if (v.ty.k === "str" && /^"(?:[^"\\]|\\.)*"$/.test(v.code))
217
- return v.code !== '""';
218
- if (v.num !== undefined)
219
- return v.num !== 0 && !Number.isNaN(v.num);
220
- return undefined;
80
+ export function holdsNothing(comp, v, want, node, where) {
81
+ const has = absence(v.ty);
82
+ if (has === null)
83
+ return;
84
+ const takes = absence(want);
85
+ if (takes === has || takes === "either")
86
+ return;
87
+ const is = has === "either" ? "may be `null` or `undefined`" : has === "null" ? "may be `null`" : "may be `undefined`";
88
+ const fix = takes === null ? "narrow it with `v-if` first" : takes === "null" ? "write `?? null` after it" : "write `?? undefined` after it";
89
+ fail(comp, "FV0606", `a value that ${is} where ${where} takes ${describeTy(want)}, which Vue would hand it as it is: ${fix}`, node);
221
90
  }
222
- export function truthy(v) {
223
- const k = known(v);
224
- if (k !== undefined)
225
- return String(k);
226
- // Of a value one of two branches gives, each branch's own truthiness.
227
- const branches = v.ty.k === "str" || isNumber(v.ty) ? ifElse(v.code) : null;
228
- if (branches)
229
- return choice(branches.test, truthy({ code: branches.yes, ty: v.ty }), truthy({ code: branches.no, ty: v.ty }));
230
- switch (v.ty.k) {
231
- case "str":
232
- return `!${receiver(v.code)}.is_empty()`;
233
- case "int":
234
- return binary(v.code, "!=", "0");
235
- // JavaScript's falsy numbers: 0, -0 and NaN.
236
- case "float":
237
- return `${binary(v.code, "!=", "0.0")} && !${receiver(v.code)}.is_nan()`;
238
- case "bool":
239
- return v.code;
240
- case "undef":
241
- return "false";
242
- case "query":
243
- return `${atom(v.code)}.truthy()`;
244
- case "opt":
245
- return `${atom(v.code)}.is_some_and(|v| ${truthy({ code: "v", ty: v.ty.of })})`;
246
- default:
247
- return "true";
248
- }
249
- }
250
- /** A value passed where `want` is expected: a present value into an optional slot is wrapped. */
251
91
  export function coerce(comp, v, want, node) {
252
92
  if (sameTy(v.ty, want))
253
93
  return v.code;
254
- if (want.k === "opt" && v.ty.k === "undef")
94
+ holdsNothing(comp, v, want, node, "the function");
95
+ if (want.k === "opt" && nothing(v.ty))
255
96
  return "None";
97
+ if (want.k === "opt" && v.ty.k === "opt" && sameTy(v.ty.of, want.of))
98
+ return v.code;
256
99
  if (want.k === "opt" && sameTy(v.ty, want.of))
257
100
  return `Some(${bare(v.code)})`;
258
- // An integer is a number too, where a fraction is expected.
259
101
  if (want.k === "float" && v.ty.k === "int")
260
102
  return asF64(v);
261
103
  if (want.k === "opt" && want.of.k === "float" && v.ty.k === "int")
262
104
  return `Some(${asF64(v)})`;
263
- return fail(comp, `a ${JSON.stringify(v.ty)} where ${JSON.stringify(want)} is expected`, node);
264
- }
265
- /** The JavaScript path an expression names — `$props.user`, `item.author.name` — or `null` when it
266
- * is not a plain chain of names. */
267
- export function pathOf(n) {
268
- if (n.type === "Identifier")
269
- return n.name;
270
- if (n.type !== "MemberExpression")
271
- return null;
272
- const base = pathOf(n.object);
273
- if (base === null)
274
- return null;
275
- if (!n.computed && n.property.type === "Identifier")
276
- return `${base}.${n.property.name}`;
277
- if (n.computed && n.property.type === "StringLiteral")
278
- return `${base}.${n.property.value}`;
279
- return null;
280
- }
281
- /** `typeof x === "string"` or `typeof x !== "string"`: the `x` tested, and whether the test is
282
- * negated. */
283
- function typeofString(n) {
284
- if (n.type !== "BinaryExpression" || (n.operator !== "===" && n.operator !== "!=="))
285
- return null;
286
- const isTypeof = (m) => m.type === "UnaryExpression" && m.operator === "typeof";
287
- const isString = (m) => m.type === "StringLiteral" && m.value === "string";
288
- const target = isTypeof(n.left) && isString(n.right) ? n.left.argument : isTypeof(n.right) && isString(n.left) ? n.right.argument : null;
289
- return target ? { target, negated: n.operator === "!==" } : null;
290
- }
291
- export function presence(s, n) {
292
- // A query value narrowed to a single string, which an attribute can then be bound to.
293
- const t = typeofString(n);
294
- if (t) {
295
- const path = pathOf(t.target);
296
- const v = expr(s, t.target);
297
- if (path === null || v.ty.k !== "query")
298
- return null;
299
- const option = `${atom(v.code)}.attr_value()`;
300
- return { path, of: STR, negated: t.negated, truthy: false, option, present: `${option}.is_some()`, pattern: (name) => `let Some(${name}) = ${option}` };
301
- }
302
- let target = n;
303
- let negated = false;
304
- let byTruth = true;
305
- if (n.type === "UnaryExpression" && n.operator === "!") {
306
- target = n.argument;
307
- negated = true;
308
- }
309
- else if (n.type === "BinaryExpression" && (n.operator === "===" || n.operator === "!==")) {
310
- const isUndef = (m) => m.type === "Identifier" && m.name === "undefined";
311
- if (isUndef(n.right))
312
- target = n.left;
313
- else if (isUndef(n.left))
314
- target = n.right;
315
- else
316
- return null;
317
- negated = n.operator === "===";
318
- byTruth = false;
319
- }
320
- const path = pathOf(target);
321
- if (path === null)
322
- return null;
323
- const v = expr(s, target);
324
- if (v.ty.k !== "opt")
325
- return null;
326
- const of = v.ty.of;
327
- // A truthiness test keeps JavaScript's: an empty string, a 0 and `false` are not taken — while an
328
- // object and a list, empty or not, always are.
329
- const scalar = of.k === "str" || of.k === "int" || of.k === "float" || of.k === "bool";
330
- const filtered = byTruth && scalar;
331
- const option = filtered ? `${atom(v.code)}.filter(|v| ${truthy({ code: "*v", ty: of })})` : v.code;
332
- const present = filtered ? truthy(v) : `${atom(v.code)}.is_some()`;
333
- return { path, of, negated, truthy: byTruth, option, present, pattern: (name) => `let Some(${name}) = ${option}` };
334
- }
335
- /** The scope with `p`'s value present, bound as `name`. */
336
- export function narrowTo(s, p, name) {
337
- return { ...s, narrowed: new Map(s.narrowed).set(p.path, { code: name, ty: p.of }) };
338
- }
339
- /** `if let Some(name) = … { then } else { otherwise }`, each branch translated in its own scope —
340
- * the value present in one of them — with only the test for a branch that never reads it. */
341
- function narrowing(s, p, present, absent) {
342
- const name = `n${++ctx.narrowCount}`;
343
- const then = bare(present(narrowTo(s, p, name)));
344
- const otherwise = bare(absent(s));
345
- if (occurrences(then, name))
346
- return `if ${p.pattern(name)} { ${then} } else { ${otherwise} }`;
347
- return choice(p.present, then, otherwise);
348
- }
349
- /** `if test { yes } else { no }`, or less when the branches allow: one value when they are the same,
350
- * the test itself when they are `true` and `false`. A test that binds a value keeps its branches. */
351
- function choice(test, yes, no) {
352
- const binds = test.startsWith("let ");
353
- if (yes === no && !binds)
354
- return yes;
355
- if (yes === "true" && no === "false" && !binds)
356
- return test;
357
- if (yes === "false" && no === "true" && !binds)
358
- return not(test);
359
- return `if ${condition(test)} { ${yes} } else { ${no} }`;
360
- }
361
- /* A test, as a Rust boolean. Only its truthiness is used, so `||`, `&&` and `!` combine the truthiness
362
- * of their operands whatever their types — where as a VALUE `a || b` is `a` or `b`, and stays held to
363
- * the stricter rules `expr` applies. `x && …` and `!x || …` read `x` present on the right. */
364
- export function cond(s, n) {
365
- if (n.type === "LogicalExpression" && (n.operator === "||" || n.operator === "&&")) {
366
- const p = presence(s, n.left);
367
- if (p && p.negated === (n.operator === "||")) {
368
- return narrowing(s, p, (inner) => cond(inner, n.right), () => String(n.operator === "||"));
369
- }
370
- return logical(cond(s, n.left), n.operator, cond(s, n.right));
371
- }
372
- if (n.type === "UnaryExpression" && n.operator === "!")
373
- return negatedOrder(s, n.argument)?.code ?? not(cond(s, n.argument));
374
- return truthy(expr(s, n));
105
+ return fail(comp, "FV0607", `a ${JSON.stringify(v.ty)} where ${JSON.stringify(want)} is expected`, node);
375
106
  }
376
107
  export function childOf(name) {
377
108
  const c = ctx.components.get(name);
378
109
  if (!c)
379
- throw new GenError(`\`Props\` is imported from ${name}.vue, which is not among the components compiled`);
110
+ throw new GenError("FV0512", `\`Props\` is imported from ${name}.vue, which is not among the components compiled`);
380
111
  return c;
381
112
  }
382
- /** The reader's route, which the component then takes. */
383
- export function theRoute(s, n) {
384
- if (!ctx.routes)
385
- fail(s.comp, `reading the route needs \`routes\` in ${CONFIG_FILE}`, n);
386
- s.comp.readsRoute = true;
387
- return { code: "fv_route", ty: { k: "route" } };
388
- }
389
- /** A field of the route: what `useRoute()` gives that the server knows as vue-router does. */
390
- export function routeField(s, base, prop, n) {
391
- if (base.ty.k === "params") {
392
- // Every parameter is a string; absent when the route has none of that name.
393
- return { code: `fv_route.param(${rustStr(prop)})`, ty: opt(STR) };
394
- }
395
- if (base.ty.k === "queryobj")
396
- return { code: `fv_route.query(${rustStr(prop)})`, ty: { k: "query" } };
397
- switch (prop) {
398
- case "path":
399
- return { code: "fv_route.path()", ty: STR };
400
- case "hash":
401
- return { code: "fv_route.hash()", ty: STR };
402
- case "name":
403
- return { code: "fv_route.name()", ty: opt(STR) };
404
- case "params":
405
- return { code: "fv_route", ty: { k: "params" } };
406
- case "query":
407
- return { code: "fv_route", ty: { k: "queryobj" } };
408
- case "fullPath":
409
- return { code: "fv_route.full_path()", ty: STR };
410
- }
411
- return fail(s.comp, `\`route.${prop}\` is not available on the server: \`path\`, \`fullPath\`, \`hash\`, \`name\`, \`params\` and \`query\` are`, n);
412
- }
413
- /** The getters being translated, so that two reading each other is an error, not a loop. */
414
- const inProgress = new Set();
415
- /** Whether an expression names \`name\` as an identifier. */
416
- function mentions(n, name) {
417
- if (!n || typeof n !== "object")
418
- return false;
419
- if (n.type === "Identifier" && n.name === name)
420
- return true;
421
- return Object.entries(n).some(([k, v]) => k !== "loc" && k !== "__fv" && (Array.isArray(v) ? v.some((x) => mentions(x, name)) : typeof v === "object" && mentions(v, name)));
422
- }
423
- /** A Pinia getter read from a store's state, `prefs.doubled`: its expression, translated with the
424
- * state it takes bound to that state. `null` when `name` is not a getter of that store. */
425
- export function storeGetter(s, base, name, node) {
426
- if (base.ty.k !== "struct" || !base.ty.store)
427
- return null;
428
- const stateName = base.ty.name;
429
- const store = [...ctx.stores.values()].find((st) => st.state === stateName);
430
- const g = store?.getters.get(name);
431
- if (!g)
432
- return null;
433
- const where = `getter \`${name}\` in ${g.file}`;
434
- if (!g.body)
435
- fail(s.comp, `${where} returns a single expression`, node);
436
- const uses = (n, type) => !!n && typeof n === "object" && (n.type === type || Object.entries(n).some(([k, v]) => k !== "loc" && (Array.isArray(v) ? v.some((x) => uses(x, type)) : typeof v === "object" && uses(v, type))));
437
- if (uses(g.body, "ThisExpression"))
438
- fail(s.comp, `${where} reads \`this\`; read the state through the getter's parameter`, node);
439
- if (g.body.type === "ArrowFunctionExpression" || g.body.type === "FunctionExpression") {
440
- fail(s.comp, `${where} returns a function, which takes arguments only the client passes`, node);
441
- }
442
- const locals = new Map();
443
- if (g.param)
444
- locals.set(g.param, { code: base.code, ty: base.ty });
445
- // A setup store's computed reads the state's refs, and the other getters, by name and `.value`.
446
- const setup = new Map();
447
- const refs = new Set();
448
- if (g.setup) {
449
- const fields = ctx.storeStructs.get(stateName)?.fields ?? [];
450
- for (const f of fields) {
451
- setup.set(f.js, fieldVal(s.comp, base.code, base.ty, f.js, node));
452
- refs.add(f.js);
453
- }
454
- for (const other of store.getters.keys()) {
455
- if (other === name || !mentions(g.body, other))
456
- continue;
457
- if (inProgress.has(`${stateName}.${other}`))
458
- fail(s.comp, `${where} and \`${other}\` read each other`, node);
459
- inProgress.add(`${stateName}.${name}`);
460
- try {
461
- setup.set(other, storeGetter(s, base, other, node));
462
- }
463
- finally {
464
- inProgress.delete(`${stateName}.${name}`);
465
- }
466
- refs.add(other);
467
- }
468
- }
469
- try {
470
- return expr({ ...s, locals, narrowed: new Map(), setup, refs, propsIdent: null }, g.body);
471
- }
472
- catch (e) {
473
- if (e instanceof GenError)
474
- throw new GenError(`${s.comp.file}: ${where}: ${e.message.replace(/^[^:]*: /, "")}`);
475
- throw e;
476
- }
477
- }
478
- /** `a op b` on two numbers, on doubles as JavaScript computes it — now, when both are known. `int`
479
- * keeps the result an integer. */
480
- function arithmetic(a, op, b, int) {
481
- if (a.num !== undefined && b.num !== undefined)
482
- return numberVal(fold(a.num, op, b.num), int);
483
- const f64 = binary(asF64(a), op, asF64(b));
484
- return int ? intFromF64(f64) : { code: f64, ty: FLOAT };
485
- }
486
- /** A comparison of two numbers, as doubles. */
487
- function compare(a, op, b) {
488
- if (a.num !== undefined && b.num !== undefined) {
489
- const konst = fold(a.num, op, b.num);
490
- return { code: String(konst), ty: BOOL, konst };
491
- }
492
- return { code: binary(asF64(a), op, asF64(b)), ty: BOOL };
493
- }
494
- /** `!(a < b)` of two integers: `a >= b`, as neither is ever NaN. `null` for anything else. */
495
- function negatedOrder(s, n) {
496
- if (n.type !== "BinaryExpression" || !(n.operator in FLIPPED))
113
+ function slotsObject(s, n) {
114
+ if (n.type === "Identifier")
115
+ return n.name === "$slots" || (s.slotsBindings.has(n.name) && !s.locals.has(n.name)) ? n.name : null;
116
+ if (n.type !== "MemberExpression" || n.computed || n.object.type !== "Identifier")
497
117
  return null;
498
- const a = expr(s, n.left);
499
- const b = expr(s, n.right);
500
- return a.ty.k === "int" && b.ty.k === "int" ? compare(a, FLIPPED[n.operator], b) : null;
501
- }
502
- /** A Rust string literal's text. */
503
- export function unquote(literal) {
504
- const escapes = { n: "\n", r: "\r", t: "\t" };
505
- return literal.slice(1, -1).replace(/\\(?:u\{([0-9a-f]+)\}|(.))/g, (_, hex, c) => (hex ? String.fromCodePoint(parseInt(hex, 16)) : (escapes[c] ?? c)));
506
- }
507
- /** Literal text and values joined into one string, each value written as JavaScript writes it into
508
- * a string: `format!`, with string literals among the values part of its text, and a string another
509
- * `format!` built part of its text and arguments. */
510
- function formatted(comp, parts, n, what) {
511
- let fmt = "";
512
- const args = [];
513
- // The value before, when nothing lies between it and the next: two halves of a pair would join.
514
- let before;
515
- const lone = loneOf(...parts.map((p) => (typeof p === "string" ? undefined : p)));
516
- for (const part of parts) {
517
- if (typeof part === "string" || (part.ty.k === "str" && known(part) !== undefined)) {
518
- const text = typeof part === "string" ? part : unquote(part.code);
519
- if (text !== "")
520
- before = undefined;
521
- fmt += text.replace(/[{}]/g, (c) => c + c);
522
- continue;
523
- }
524
- if (before)
525
- meet(comp, before, part, what, n, "join");
526
- before = part;
527
- if (part.format) {
528
- fmt += part.format.text;
529
- args.push(...part.format.args);
530
- continue;
531
- }
532
- // A string written by `Display` is written as it is: `fv::Js(n)` rather than its `to_string()`.
533
- if (part.ty.k === "str")
534
- args.push(receiver(part.code).replace(/^(fv::Js\(.*\))\.to_string\(\)$/s, "$1"));
535
- else if (isNumber(part.ty))
536
- args.push(`fv::Js(${bare(part.code)})`);
537
- else if (part.ty.k === "bool")
538
- args.push(`if ${condition(part.code)} { "true" } else { "false" }`);
539
- else
540
- fail(comp, "a template literal interpolates strings, numbers and booleans that are present", n);
541
- fmt += "{}";
542
- }
543
- if (!args.length)
544
- return { code: rustStr(fmt.replace(/\{\{|\}\}/g, (c) => c[0])), ty: STR };
545
- // One string and nothing else is that string.
546
- const one = parts.filter((p) => (typeof p === "string" ? p !== "" : p.code !== '""'));
547
- if (fmt === "{}" && one.length === 1 && typeof one[0] !== "string" && one[0].ty.k === "str")
548
- return one[0];
549
- return { code: `&*format!(${rustStr(fmt)}, ${args.join(", ")})`, ty: STR, format: { text: fmt, args }, ...lone };
118
+ const [owner, name] = [n.object.name, n.property.name];
119
+ if (owner === "_ctx" && name === "$slots")
120
+ return "$slots";
121
+ return (owner === "$setup" || owner === "_ctx") && s.slotsBindings.has(name) ? name : null;
550
122
  }
551
123
  export function expr(s, n) {
552
124
  const comp = s.comp;
@@ -556,8 +128,10 @@ export function expr(s, n) {
556
128
  if (narrowed)
557
129
  return narrowed;
558
130
  }
131
+ const named = constOf(s, n);
132
+ if (named)
133
+ return constVal(named.c, { comp, node: n, what: named.what });
559
134
  if (n.type === "MemberExpression" && !n.computed && n.property.type === "Identifier" && n.property.name === "length") {
560
- // `Object.entries(r).length`: as many as the record has keys.
561
135
  if (isObjectCall(n.object, "entries") && n.object.arguments.length === 1) {
562
136
  const r = expr(s, n.object.arguments[0]);
563
137
  if (r.ty.k === "record")
@@ -565,13 +139,10 @@ export function expr(s, n) {
565
139
  }
566
140
  const base = expr(s, n.object);
567
141
  if (base.ty.k === "list" && base.iter !== undefined) {
568
- // A list split out is a `Vec` already, whose length is known.
569
142
  const vec = /^(.*)\.into_iter\(\)$/s.exec(base.iter)?.[1];
570
- // Nor does a `map` at the end change how many there are.
571
143
  if (vec === undefined) {
572
144
  const at = base.iter.lastIndexOf(".map(");
573
145
  const mapped = at > 0 && enclosed(base.iter.slice(at + 4)) ? base.iter.slice(0, at) : base.iter;
574
- // What is left may walk a `Vec` that is held, whose length is known.
575
146
  const held = /^(.*)\.iter\(\)$/s.exec(mapped)?.[1];
576
147
  return { code: held !== undefined ? `${atom(held)}.len() as i64` : `${atom(mapped)}.count() as i64`, ty: INT };
577
148
  }
@@ -579,31 +150,25 @@ export function expr(s, n) {
579
150
  }
580
151
  if (base.ty.k === "list")
581
152
  return { code: `${atom(base.code)}.len() as i64`, ty: INT };
582
- // A JavaScript string's length counts UTF-16 code units, not the bytes Rust's `len` counts.
583
153
  if (base.ty.k === "str")
584
154
  return { code: `fv::js_length(${strArg(base.code)})`, ty: INT };
585
155
  }
586
156
  if (n.type === "BinaryExpression" && n.operator === "+") {
587
157
  const a = expr(s, n.left);
588
158
  const b = expr(s, n.right);
589
- // JavaScript's `+` concatenates as soon as one side is a string, writing a number in decimal —
590
- // which is what `{}` does with an `i64`. Two numbers would be arithmetic, which is not here.
591
159
  const joinable = (t) => t.k === "str" || isNumber(t);
592
160
  if ((a.ty.k === "str" || b.ty.k === "str") && joinable(a.ty) && joinable(b.ty)) {
593
161
  meet(comp, a, b, "`+`", n, "join");
594
- // A number is written as JavaScript writes it, rounded beyond 2⁵³.
595
162
  return formatted(comp, [a, b], n, "`+`");
596
163
  }
597
- // Two numbers: arithmetic, as `n + 1` in a template means.
598
164
  if (isNumber(a.ty) && isNumber(b.ty))
599
165
  return arithmetic(a, "+", b, a.ty.k === "int" && b.ty.k === "int");
600
- return fail(comp, "`+` joins a string to a string or a number, or adds two numbers", n);
166
+ return fail(comp, "FV0608", "`+` joins a string to a string or a number, or adds two numbers", n);
601
167
  }
602
168
  if (n.type === "BinaryExpression" && ["-", "*", "%", "/", "<", ">", "<=", ">="].includes(n.operator)) {
603
169
  const a = expr(s, n.left);
604
170
  const b = expr(s, n.right);
605
171
  const comparison = ["<", ">", "<=", ">="].includes(n.operator);
606
- // Two strings, ordered as JavaScript orders them: by UTF-16 code unit.
607
172
  if (comparison && a.ty.k === "str" && b.ty.k === "str") {
608
173
  meet(comp, a, b, `\`${n.operator}\``, n, "order");
609
174
  const is = { "<": "lt", ">": "gt", "<=": "le", ">=": "ge" }[n.operator];
@@ -614,20 +179,16 @@ export function expr(s, n) {
614
179
  ? "narrow an optional one with `v-if` first"
615
180
  : `the other is ${describeTy(isNumber(a.ty) ? b.ty : a.ty)}`;
616
181
  const between = comparison ? "two numbers, or two strings," : "two numbers";
617
- return fail(comp, `\`${n.operator}\` is supported between ${between} that are present: ${why}`, n);
182
+ return fail(comp, "FV0609", `\`${n.operator}\` is supported between ${between} that are present: ${why}`, n);
618
183
  }
619
184
  if (["<", ">", "<=", ">="].includes(n.operator))
620
185
  return compare(a, n.operator, b);
621
- // Two integers stay integers — but for `/`, which gives a fraction in JavaScript, and a `%` whose
622
- // divisor may be zero, which gives NaN.
623
186
  const intDivisor = n.right.type === "NumericLiteral" && Number.isInteger(n.right.value) && n.right.value !== 0;
624
187
  const int = a.ty.k === "int" && b.ty.k === "int" && n.operator !== "/" && (n.operator !== "%" || intDivisor);
625
- // Doubles, as JavaScript computes: Rust's `%` on `f64` is JavaScript's, and `/` by zero is ±∞.
626
188
  return arithmetic(a, n.operator, b, int);
627
189
  }
628
190
  switch (n.type) {
629
191
  case "TemplateLiteral": {
630
- // `${a}-${b}`: each part written as JavaScript writes it into a string.
631
192
  const parts = [];
632
193
  n.quasis.forEach((q, i) => {
633
194
  parts.push(q.value.cooked);
@@ -637,44 +198,40 @@ export function expr(s, n) {
637
198
  return formatted(comp, parts, n, "a template literal");
638
199
  }
639
200
  case "ArrayExpression": {
640
- // A list of literals or values of one scalar type, as a Rust array.
641
201
  if (n.elements.length === 0)
642
202
  return { code: "[]", ty: { k: "list", of: UNDEF } };
643
203
  const values = n.elements.map((el) => {
644
204
  if (!el || el.type === "SpreadElement")
645
- fail(comp, "an array literal holds plain values", n);
205
+ fail(comp, "FV0610", "an array literal holds plain values", n);
646
206
  return expr(s, el);
647
207
  });
648
208
  const of = values[0].ty;
649
209
  if (!(of.k === "str" || of.k === "int" || of.k === "float" || of.k === "bool") || values.some((v) => !sameTy(v.ty, of))) {
650
- fail(comp, "an array literal holds strings, numbers or booleans, all of one type", n);
210
+ fail(comp, "FV0611", "an array literal holds strings, numbers or booleans, all of one type", n);
651
211
  }
652
212
  return { code: `[${values.map((v) => bare(v.code)).join(", ")}]`, ty: { k: "list", of }, ...loneOf(...values) };
653
213
  }
654
214
  case "OptionalMemberExpression": {
655
- // `a?.b`: the field of an optional object when it is present.
656
215
  if (n.computed)
657
- return fail(comp, "computed member access", n);
216
+ return fail(comp, "FV0612", "computed member access", n);
658
217
  const base = expr(s, n.object);
218
+ if (nothing(base.ty))
219
+ return { code: "None", ty: UNDEF };
659
220
  if (base.ty.k !== "opt")
660
221
  return fieldVal(comp, base.code, base.ty, n.property.name, n);
661
222
  const f = fieldVal(comp, "v", base.ty.of, n.property.name, n);
662
223
  if (f.ty.k === "opt")
663
- return { code: `${atom(base.code)}.and_then(|v| ${f.code})`, ty: f.ty };
224
+ return { code: `${atom(base.code)}.and_then(|v| ${f.code})`, ty: opt(f.ty) };
664
225
  return { code: `${atom(base.code)}.map(|v| ${f.code})`, ty: opt(f.ty) };
665
226
  }
666
227
  case "StringLiteral":
667
228
  return { code: rustStr(n.value), ty: STR };
668
229
  case "NumericLiteral":
669
- // JavaScript's own spelling of the number is a valid Rust float literal: `0.5`, `1e-7`. An
670
- // integer beyond what a double holds exactly is a double too, as it is in JavaScript.
671
230
  return numberVal(n.value, Number.isSafeInteger(n.value));
672
231
  case "BooleanLiteral":
673
232
  return { code: String(n.value), ty: BOOL, konst: n.value };
674
233
  case "NullLiteral":
675
- // An absent prop is `undefined`, and `null` is a different value: `x === null` is false for
676
- // it in Vue and would be `is_none()` here.
677
- return fail(comp, "`null`: compare with `undefined`, which is what an absent prop is", n);
234
+ return { code: "None", ty: NULL };
678
235
  case "Identifier": {
679
236
  if (n.name === "undefined")
680
237
  return { code: "None", ty: UNDEF };
@@ -682,14 +239,13 @@ export function expr(s, n) {
682
239
  if (local)
683
240
  return local;
684
241
  if (s.clientOnly.has(n.name)) {
685
- return fail(comp, `\`${n.name}\` is set up in a way the server cannot evaluate: ${s.clientOnly.get(n.name)}`, n);
242
+ return fail(comp, "FV0613", `\`${n.name}\` is set up in a way the server cannot evaluate: ${s.clientOnly.get(n.name)}`, n);
686
243
  }
687
244
  if (n.name === s.propsIdent)
688
245
  return { code: "props", ty: { k: "struct", name: "Props" } };
689
- return fail(comp, `\`${n.name}\` is not available when rendering on the server`, n);
246
+ return fail(comp, "FV0601", `\`${n.name}\` is not available when rendering on the server`, n);
690
247
  }
691
248
  case "MemberExpression": {
692
- // `count.value` in the script: the ref's value, which is what the binding already reads.
693
249
  if (!n.computed && n.property.name === "value" && n.object.type === "Identifier" && s.refs.has(n.object.name) && !s.locals.has(n.object.name)) {
694
250
  return expr(s, n.object);
695
251
  }
@@ -699,19 +255,17 @@ export function expr(s, n) {
699
255
  }
700
256
  if (n.property.type === "StringLiteral") {
701
257
  const base = expr(s, n.object);
702
- if (base.ty.k === "params" || base.ty.k === "queryobj")
703
- return routeField(s, base, n.property.value, n);
258
+ const own = claim((p) => p.member?.(s, base, n.property.value, n, true));
259
+ if (own)
260
+ return own;
704
261
  }
705
- return fail(comp, "computed member access", n);
262
+ return fail(comp, "FV0612", "computed member access", n);
706
263
  }
707
264
  const prop = n.property.name;
708
- // `$slots.side`: whether the parent gave that slot any content.
709
- const slotsObject = (n.object.type === "Identifier" && n.object.name === "$slots") ||
710
- (n.object.type === "MemberExpression" && !n.object.computed && n.object.object.type === "Identifier" &&
711
- n.object.object.name === "_ctx" && n.object.property.name === "$slots");
712
- if (slotsObject) {
265
+ const slots = slotsObject(s, n.object);
266
+ if (slots !== null) {
713
267
  if (!comp.slotNames.includes(prop))
714
- fail(comp, `\`$slots.${prop}\` names a slot this template does not render`, n);
268
+ fail(comp, "FV0907", `\`${slots}.${prop}\` names a slot this template does not render`, n);
715
269
  return { code: `fv_slots.${snake(prop)}.is_some()`, ty: BOOL };
716
270
  }
717
271
  if (n.object.type === "Identifier") {
@@ -720,34 +274,33 @@ export function expr(s, n) {
720
274
  return fieldVal(comp, "props", { k: "struct", name: "Props" }, prop, n);
721
275
  case "$setup":
722
276
  case "_ctx": {
723
- if (n.object.name === "_ctx" && prop === "$route")
724
- return theRoute(s, n);
277
+ const global = n.object.name === "_ctx" ? claim((p) => p.global?.(s, prop, n)) : undefined;
278
+ if (global)
279
+ return global;
725
280
  if (n.object.name === "_ctx" && prop === "$attrs") {
726
- return fail(comp, "`$attrs` is bound whole, with `v-bind=\"$attrs\"`; a value read from it has no type: declare it as a prop", n);
281
+ return fail(comp, "FV0415", "`$attrs` is bound whole, with `v-bind=\"$attrs\"`; a value read from it has no type: declare it as a prop", n);
727
282
  }
728
283
  const v = s.setup.get(prop);
729
284
  if (v)
730
285
  return v;
286
+ if (prop === s.propsIdent)
287
+ return { code: "props", ty: { k: "struct", name: "Props" } };
731
288
  if (s.clientOnly.has(prop)) {
732
- return fail(comp, `\`${prop}\` is set up in a way the server cannot evaluate: ${s.clientOnly.get(prop)}`, n);
289
+ return fail(comp, "FV0613", `\`${prop}\` is set up in a way the server cannot evaluate: ${s.clientOnly.get(prop)}`, n);
733
290
  }
734
291
  if (n.object.name === "_ctx" && comp.props.fields.some((f) => f.js === prop)) {
735
292
  return fieldVal(comp, "props", { k: "struct", name: "Props" }, prop, n);
736
293
  }
737
- return fail(comp, `\`${prop}\` is not available when rendering on the server`, n);
294
+ return fail(comp, "FV0601", `\`${prop}\` is not available when rendering on the server`, n);
738
295
  }
739
296
  }
740
297
  }
741
298
  const base = expr(s, n.object);
742
- if (base.ty.k === "route" || base.ty.k === "params" || base.ty.k === "queryobj")
743
- return routeField(s, base, prop, n);
744
- return storeGetter(s, base, prop, n) ?? fieldVal(comp, base.code, base.ty, prop, n);
299
+ return claim((p) => p.member?.(s, base, prop, n, false)) ?? fieldVal(comp, base.code, base.ty, prop, n);
745
300
  }
746
301
  case "CallExpression":
747
302
  return call(s, n);
748
303
  case "LogicalExpression": {
749
- // `x !== undefined && …` and `!x || …` / `x === undefined || …`: booleans, with `x` present on
750
- // the right.
751
304
  if (n.operator === "&&" || n.operator === "||") {
752
305
  const p = presence(s, n.left);
753
306
  if (p && p.negated === (n.operator === "||") && (p.negated || !p.truthy)) {
@@ -755,26 +308,23 @@ export function expr(s, n) {
755
308
  const code = narrowing(s, p, (inner) => (right = expr(inner, n.right)).code, () => String(n.operator === "||"));
756
309
  if (right?.ty.k === "bool")
757
310
  return { code, ty: BOOL };
758
- return fail(comp, `\`${n.operator}\` is supported between booleans only`, n);
311
+ return fail(comp, "FV0614", `\`${n.operator}\` is supported between booleans only`, n);
759
312
  }
760
313
  }
761
314
  const a = expr(s, n.left);
762
315
  const b = expr(s, n.right);
763
316
  if (n.operator === "??") {
764
- // A query value falls back for `undefined` and `null`, and stays a query value: an array
765
- // given more than once stays an array.
766
- if (a.ty.k === "query") {
767
- if (b.ty.k !== "str")
768
- fail(comp, "`??` after a query value takes a string", n);
769
- return { code: `${atom(a.code)}.or(${bare(b.code)})`, ty: a.ty };
770
- }
317
+ const own = claim((p) => p.values?.nullish?.(s, a, b, n));
318
+ if (own)
319
+ return own;
320
+ if (nothing(a.ty))
321
+ return b;
771
322
  if (a.ty.k !== "opt")
772
323
  return a;
773
- if (b.ty.k === "undef")
774
- return a;
324
+ if (nothing(b.ty))
325
+ return { ...a, ty: withAbsence(a.ty.of, absence(b.ty)) };
775
326
  if (b.iter !== undefined)
776
- fail(comp, "`??` falling back to a computed list", n);
777
- // A string a temporary owns: the result is one too, borrowed from the `Cow` either side gives.
327
+ fail(comp, "FV0615", "`??` falling back to a computed list", n);
778
328
  if (a.held !== undefined && b.ty.k === "str")
779
329
  return { code: `&*${atom(a.held)}.unwrap_or(${asCow(b)})`, ty: STR, ...loneOf(a, b) };
780
330
  if (a.ty.of.k === "str" && b.ty.k === "str" && isTemporary(b)) {
@@ -782,20 +332,18 @@ export function expr(s, n) {
782
332
  }
783
333
  if (sameTy(a.ty.of, b.ty))
784
334
  return { code: `${atom(a.code)}.unwrap_or(${bare(b.code)})`, ty: b.ty, ...loneOf(a, b) };
785
- if (sameTy(a.ty, b.ty))
786
- return { code: `${atom(a.code)}.or(${bare(b.code)})`, ty: a.ty, ...loneOf(a, b) };
787
- // An integer and a fraction: both numbers in JavaScript, so a fraction here.
335
+ if (b.ty.k === "opt" && sameTy(a.ty.of, b.ty.of))
336
+ return { code: `${atom(a.code)}.or(${bare(b.code)})`, ty: b.ty, ...loneOf(a, b) };
788
337
  if (a.ty.of.k === "float" && b.ty.k === "int")
789
338
  return { code: `${atom(a.code)}.unwrap_or(${bare(asF64(b))})`, ty: FLOAT };
790
339
  if (a.ty.of.k === "int" && b.ty.k === "float")
791
340
  return { code: `${atom(a.code)}.map(|v| v as f64).unwrap_or(${bare(b.code)})`, ty: FLOAT };
792
- return fail(comp, "`??` between different types", n);
341
+ return fail(comp, "FV0616", "`??` between different types", n);
793
342
  }
794
343
  if (n.operator === "||") {
795
344
  if (a.ty.k === "bool" && b.ty.k === "bool")
796
345
  return boolOf(logical(a.code, "||", b.code));
797
346
  if (b.ty.k === "undef") {
798
- // `x || undefined`: the value when it is truthy, nothing otherwise.
799
347
  const inner = a.ty.k === "opt" ? a.ty.of : a.ty;
800
348
  const src = a.ty.k === "opt" ? atom(a.code) : `Some(${bare(a.code)})`;
801
349
  return { code: `${src}.filter(|v| ${truthy({ code: "*v", ty: inner })})`, ty: opt(inner) };
@@ -812,11 +360,11 @@ export function expr(s, n) {
812
360
  const otherwise = a.ty.k === "str" ? strArg(b.code) : bare(b.code);
813
361
  return { code: `{ let a = ${bare(a.code)}; if ${truthy({ code: "a", ty: a.ty })} { a } else { ${otherwise} } }`, ty: a.ty, ...loneOf(a, b) };
814
362
  }
815
- return fail(comp, "`||` between these types", n);
363
+ return fail(comp, "FV0617", "`||` between these types", n);
816
364
  }
817
365
  if (n.operator === "&&" && a.ty.k === "bool" && b.ty.k === "bool")
818
366
  return boolOf(logical(a.code, "&&", b.code));
819
- return fail(comp, `\`${n.operator}\` is supported between booleans only`, n);
367
+ return fail(comp, "FV0614", `\`${n.operator}\` is supported between booleans only`, n);
820
368
  }
821
369
  case "UnaryExpression":
822
370
  if (n.operator === "!") {
@@ -831,18 +379,31 @@ export function expr(s, n) {
831
379
  if (a.ty.k === "float")
832
380
  return { code: negate(a.code), ty: FLOAT };
833
381
  }
834
- return fail(comp, `unary \`${n.operator}\``, n);
382
+ return fail(comp, "FV0618", `unary \`${n.operator}\``, n);
835
383
  case "BinaryExpression": {
836
- if (n.operator !== "===" && n.operator !== "!==")
837
- fail(comp, `\`${n.operator}\``, n);
838
- // `typeof route.query.q === "string"`: a single value, not `null`, absent or repeated.
839
- const tested = typeofString(n);
840
- if (tested) {
841
- const v = expr(s, tested.target);
842
- if (v.ty.k !== "query")
843
- fail(comp, '`typeof` tests a query value only, as `typeof route.query.q === "string"`', n);
844
- const one = `${atom(v.code)}.attr_value().is_some()`;
845
- return boolOf(tested.negated ? not(one) : one);
384
+ const test = nullTest(n);
385
+ if (n.operator !== "===" && n.operator !== "!==" && !test)
386
+ fail(comp, "FV0619", `\`${n.operator}\`: \`==\` and \`!=\` compare with \`null\` or \`undefined\` only; use \`===\``, n);
387
+ const whole = claim((p) => p.equality?.(s, n));
388
+ if (whole)
389
+ return whole;
390
+ if (test) {
391
+ const v = expr(s, test.target);
392
+ const none = absence(v.ty);
393
+ if (v.ty.k === "opt") {
394
+ checkNullTest(s, test, v);
395
+ const is = `${atom(v.code)}.is_none()`;
396
+ return boolOf(test.is ? is : not(is));
397
+ }
398
+ if (none !== null) {
399
+ const konst = (!test.strict || none === test.literal) === test.is;
400
+ return { code: String(konst), ty: BOOL, konst };
401
+ }
402
+ if (!test.strict && claim((p) => p.values?.describe?.(v.ty)) === undefined) {
403
+ return { code: String(!test.is), ty: BOOL, konst: !test.is };
404
+ }
405
+ if (!test.strict)
406
+ fail(comp, "FV0620", `\`${n.operator}\` of ${describeTy(v.ty)}: compare with \`${test.is ? "===" : "!=="} undefined\``, n);
846
407
  }
847
408
  const a = expr(s, n.left);
848
409
  const b = expr(s, n.right);
@@ -851,36 +412,28 @@ export function expr(s, n) {
851
412
  const strish = (t) => t.k === "str" || (t.k === "opt" && t.of.k === "str");
852
413
  if (strish(a.ty) && strish(b.ty))
853
414
  meet(comp, a, b, `\`${n.operator}\``, n, "equal");
854
- // A query value equals a string only when it is that single value.
855
- if (a.ty.k === "query" && b.ty.k === "str")
856
- eq = `${atom(a.code)}.is(${strArg(b.code)})`;
857
- else if (b.ty.k === "query" && a.ty.k === "str")
858
- eq = `${atom(b.code)}.is(${strArg(a.code)})`;
859
- else if (a.ty.k === "query" && b.ty.k === "undef")
860
- eq = `${atom(a.code)}.is_undefined()`;
861
- else if (b.ty.k === "query" && a.ty.k === "undef")
862
- eq = `${atom(b.code)}.is_undefined()`;
863
- else if (b.ty.k === "undef" && a.ty.k === "opt")
864
- eq = `${atom(a.code)}.is_none()`;
865
- else if (a.ty.k === "undef" && b.ty.k === "opt")
866
- eq = `${atom(b.code)}.is_none()`;
867
- else if (a.ty.k === "undef" || b.ty.k === "undef") {
868
- // A value that is always present — or narrowed to present — is never \`undefined\`.
415
+ const own = claim((p) => p.values?.equals?.(a, b));
416
+ if (own !== undefined)
417
+ eq = own;
418
+ else if ((nothing(b.ty) && a.ty.k === "opt") || (nothing(a.ty) && b.ty.k === "opt")) {
419
+ const [v, literal] = a.ty.k === "opt" ? [a, b] : [b, a];
420
+ checkNullTest(s, { target: n, literal: literal.ty.k === "null" ? "null" : "undefined", strict: true, is: n.operator === "===" }, v);
421
+ eq = `${atom(v.code)}.is_none()`;
422
+ }
423
+ else if (nothing(a.ty) || nothing(b.ty)) {
424
+ const other = nothing(a.ty) ? b.ty : a.ty;
425
+ const opaque = nothing(other) ? undefined : claim((p) => p.values?.describe?.(other));
426
+ if (opaque !== undefined)
427
+ fail(comp, "FV0621", `\`${n.operator}\` between ${opaque} and ${describeTy(nothing(a.ty) ? a.ty : b.ty)}`, n);
869
428
  const same = a.ty.k === b.ty.k;
870
429
  const konst = n.operator === "===" ? same : !same;
871
430
  return { code: String(konst), ty: BOOL, konst };
872
431
  }
873
432
  else if (isNumber(a.ty) && isNumber(b.ty))
874
433
  eq = compare(a, "==", b).code;
875
- // Two string literals are compared now.
876
- else if (a.ty.k === "str" && b.ty.k === "str" && known(a) !== undefined && known(b) !== undefined)
877
- eq = String(unquote(a.code) === unquote(b.code));
878
- else if (a.ty.k === "str" && b.ty.k === "str" && (a.code === '""' || b.code === '""')) {
879
- // A string compared with the empty one: whether it is empty.
880
- eq = `${receiver(a.code === '""' ? b.code : a.code)}.is_empty()`;
881
- }
434
+ else if (a.ty.k === "str" && b.ty.k === "str")
435
+ eq = stringsEqual(a, b);
882
436
  else if (a.ty.k === "bool" && b.ty.k === "bool" && (a.konst !== undefined || b.konst !== undefined)) {
883
- // A boolean compared with `true` is itself, with `false` its negation.
884
437
  const [k, other] = a.konst !== undefined ? [a.konst, b.code] : [b.konst, a.code];
885
438
  eq = k ? other : not(other);
886
439
  }
@@ -892,7 +445,7 @@ export function expr(s, n) {
892
445
  else if (b.ty.k === "opt" && sameTy(b.ty.of, a.ty) && scalar(a.ty))
893
446
  eq = binary(`Some(${bare(a.code)})`, "==", b.code);
894
447
  else
895
- return fail(comp, "`===` between these types", n);
448
+ return fail(comp, "FV0622", "`===` between these types", n);
896
449
  return boolOf(n.operator === "===" ? eq : not(eq));
897
450
  }
898
451
  case "ConditionalExpression": {
@@ -900,26 +453,23 @@ export function expr(s, n) {
900
453
  const k = known(t);
901
454
  if (k !== undefined)
902
455
  return expr(s, k ? n.consequent : n.alternate);
903
- // A test for presence narrows the branch where the value is present, as TypeScript does.
904
456
  const p = presence(s, n.test);
905
457
  const name = p ? `n${++ctx.narrowCount}` : "";
906
458
  const a = expr(p && !p.negated ? narrowTo(s, p, name) : s, n.consequent);
907
459
  const b = expr(p && p.negated ? narrowTo(s, p, name) : s, n.alternate);
908
- // Two branches alike are one value, whatever the test.
909
460
  if (sameTy(a.ty, b.ty) && a.code === b.code && (!name || !occurrences(a.code, name)))
910
461
  return a;
911
- // A string in the second branch is coerced to the `&str` of the first.
912
462
  const second = (code) => (a.ty.k === "str" ? strArg(code) : bare(code));
913
463
  const choose = (yes, no) => {
914
464
  if (!p)
915
465
  return choice(truthy(t), bare(yes), second(no));
916
466
  const [present, absent] = p.negated ? [bare(no), second(yes)] : [bare(yes), second(no)];
917
- // `x ? x : undefined` is the `Option` itself.
918
467
  if (present === `Some(${name})` && absent === "None")
919
468
  return p.option;
920
- // `x ? x : y`: the value, or the fallback.
921
469
  if (present === name)
922
470
  return `${atom(p.option)}.unwrap_or(${absent})`;
471
+ if (absent === "None" && present.startsWith("Some(") && enclosed(present.slice(4)))
472
+ return `${atom(p.option)}.map(|${name}| ${bare(present.slice(5, -1))})`;
923
473
  if (occurrences(present, name))
924
474
  return `if ${p.pattern(name)} { ${present} } else { ${absent} }`;
925
475
  return choice(p.present, present, absent);
@@ -928,22 +478,22 @@ export function expr(s, n) {
928
478
  if (sameTy(a.ty, b.ty) && a.ty.k === "str" && (isTemporary(a) || isTemporary(b))) {
929
479
  return { code: `&*(${choose(asCow(a), asCow(b))})`, ty: STR, ...lone };
930
480
  }
931
- // Two lists, one of them computed: both branches collect their items, to have one type.
932
481
  if (sameTy(a.ty, b.ty) && a.ty.k === "list" && (a.iter !== undefined || b.iter !== undefined)) {
933
482
  const both = `(${choose(collected(a), collected(b))})`;
934
483
  return { code: both, ty: a.ty, iter: `${both}.into_iter()`, ...lone };
935
484
  }
936
- const optStr = (v) => v.ty.k === "undef" || (v.ty.k === "opt" && v.ty.of.k === "str") || v.ty.k === "str";
485
+ const optStr = (v) => nothing(v.ty) || (v.ty.k === "opt" && v.ty.of.k === "str") || v.ty.k === "str";
937
486
  if (sameTy(a.ty, b.ty) && a.ty.k !== "opt")
938
487
  return { code: choose(a.code, b.code), ty: a.ty, ...lone };
939
- // An integer and a fraction: both numbers in JavaScript, so a fraction here.
940
488
  if (isNumber(a.ty) && isNumber(b.ty))
941
489
  return { code: choose(asF64(a), asF64(b)), ty: FLOAT };
942
- if (sameTy(a.ty, b.ty) || a.ty.k === "undef" || b.ty.k === "undef" || (a.ty.k === "opt" && sameTy(a.ty.of, b.ty)) || (b.ty.k === "opt" && sameTy(b.ty.of, a.ty))) {
943
- const ty = opt(a.ty.k === "undef" || b.ty.k === "opt" ? b.ty : a.ty);
490
+ const base = (ty) => (ty.k === "opt" ? ty.of : nothing(ty) ? null : ty);
491
+ const [baseA, baseB] = [base(a.ty), base(b.ty)];
492
+ const of = baseA ?? baseB;
493
+ if (of !== null && (baseA === null || baseB === null || sameTy(baseA, baseB))) {
494
+ const ty = withAbsence(of, joinAbsence(absence(a.ty), absence(b.ty)));
944
495
  if (optStr(a) && optStr(b) && (isTemporary(a) || isTemporary(b) || a.held !== undefined || b.held !== undefined)) {
945
- // A string built in a branch, held by an `Option<Cow>` the statement keeps.
946
- const held = (v) => v.held ?? (v.ty.k === "undef" ? "None" : v.ty.k === "opt" ? `${atom(v.code)}.map(std::borrow::Cow::<str>::Borrowed)` : `Some(${asCow(v)})`);
496
+ const held = (v) => v.held ?? (nothing(v.ty) ? "None" : v.ty.k === "opt" ? `${atom(v.code)}.map(std::borrow::Cow::<str>::Borrowed)` : `Some(${asCow(v)})`);
947
497
  const both = atom(choose(held(a), held(b)));
948
498
  return { code: `${both}.as_deref()`, ty, held: both, ...lone };
949
499
  }
@@ -951,355 +501,13 @@ export function expr(s, n) {
951
501
  return { code: choose(a.code, b.code), ty: a.ty, ...lone };
952
502
  return { code: choose(coerce(comp, a, ty, n), coerce(comp, b, ty, n)), ty, ...lone };
953
503
  }
954
- return fail(comp, "the two branches of `?:` differ in type", n);
955
- }
956
- default:
957
- return fail(comp, `\`${n.type}\` is not supported in an island template`, n);
958
- }
959
- }
960
- /** A boolean computed at run time, or known now when it folded to a constant. */
961
- export function boolOf(code) {
962
- return code === "true" || code === "false" ? { code, ty: BOOL, konst: code === "true" } : { code, ty: BOOL };
963
- }
964
- export function call(s, n) {
965
- const comp = s.comp;
966
- const callee = n.callee;
967
- const args = n.arguments;
968
- if (callee.type === "Identifier") {
969
- switch (callee.name) {
970
- case "_ssrLooseEqual": {
971
- const a = expr(s, args[0]);
972
- const b = expr(s, args[1]);
973
- if (a.ty.k === "str" && b.ty.k === "str") {
974
- meet(comp, a, b, "`v-model`", n, "equal");
975
- return boolOf(binary(a.code, "==", b.code));
976
- }
977
- return fail(comp, "`v-model` comparison between these types", n);
978
- }
979
- case "_ssrIncludeBooleanAttr": {
980
- // `!!value || value === ""`: every string is included, empty or not.
981
- const a = expr(s, args[0]);
982
- if (a.konst !== undefined)
983
- return a;
984
- if (a.ty.k === "str")
985
- return { code: "true", ty: BOOL, konst: true };
986
- if (a.ty.k === "opt" && a.ty.of.k === "str")
987
- return { code: `${atom(a.code)}.is_some()`, ty: BOOL };
988
- return boolOf(truthy(a));
989
- }
990
- case "_ssrLooseContain":
991
- return fail(comp, "`v-model` over an array", n);
992
- }
993
- if (s.i18nT.has(callee.name))
994
- return translate(s, args, n);
995
- const helper = s.helpers.get(callee.name);
996
- if (helper)
997
- return helperCall(s, helper, args, n);
998
- if (callee.name === "String" && args.length === 1) {
999
- const a = expr(s, args[0]);
1000
- if (a.ty.k === "str")
1001
- return a;
1002
- if (isNumber(a.ty))
1003
- return { code: `&*fv::Js(${bare(a.code)}).to_string()`, ty: STR };
1004
- if (a.ty.k === "bool")
1005
- return { code: `if ${condition(a.code)} { "true" } else { "false" }`, ty: STR };
1006
- }
1007
- // Strings read as numbers, as JavaScript reads them: a fraction, `NaN` when there is no number.
1008
- if (callee.name === "Number" && args.length === 1) {
1009
- const a = expr(s, args[0]);
1010
- if (a.ty.k === "str")
1011
- return { code: `fv::js_number(${strArg(a.code)})`, ty: FLOAT };
1012
- if (isNumber(a.ty))
1013
- return a;
1014
- if (a.ty.k === "bool")
1015
- return { code: `i64::from(${bare(a.code)})`, ty: INT };
1016
- return fail(comp, "`Number()` takes a string, a number or a boolean that is present", n);
1017
- }
1018
- if ((callee.name === "parseInt" && (args.length === 1 || args.length === 2)) || (callee.name === "parseFloat" && args.length === 1)) {
1019
- const a = expr(s, args[0]);
1020
- // Not a number: `parseInt` reads it as a string, so `parseInt(0.0000005)` is 5.
1021
- if (a.ty.k !== "str")
1022
- fail(comp, `\`${callee.name}()\` takes a string`, args[0]);
1023
- if (callee.name === "parseFloat")
1024
- return { code: `fv::js_parse_float(${strArg(a.code)})`, ty: FLOAT };
1025
- const radix = args[1];
1026
- if (radix && !(radix.type === "NumericLiteral" && (radix.value === 10 || radix.value === 16))) {
1027
- fail(comp, "`parseInt()` takes a radix of 10 or 16, written as a literal", radix);
1028
- }
1029
- return { code: `fv::js_parse_int(${strArg(a.code)}, ${radix ? radix.value : 0})`, ty: FLOAT };
1030
- }
1031
- return fail(comp, `\`${callee.name}()\` is not available when rendering on the server`, n);
1032
- }
1033
- if (callee.type === "MemberExpression" && !callee.computed) {
1034
- const method = callee.property.name;
1035
- if (callee.object.type === "Identifier" && callee.object.name === "Array" && method === "isArray") {
1036
- const a = expr(s, args[0]);
1037
- if (a.ty.k === "query")
1038
- return { code: `${atom(a.code)}.is_array()`, ty: BOOL };
1039
- const is = a.ty.k === "list";
1040
- return { code: String(is), ty: BOOL, konst: is };
1041
- }
1042
- if (callee.object.type === "Identifier" && callee.object.name === "Object")
1043
- return objectCall(s, method, args, n);
1044
- if (callee.object.type === "Identifier" && callee.object.name === "JSON" && method === "stringify" && args.length === 1) {
1045
- const v = expr(s, args[0]);
1046
- // A boolean is one of two literals, which need no `String`.
1047
- if (v.ty.k === "bool")
1048
- return { code: `if ${condition(v.code)} { "true" } else { "false" }`, ty: STR };
1049
- return { code: `&*${json(s, v, args[0])}`, ty: STR };
1050
- }
1051
- // `$t(…)` in the template, and \`t(…)\` from \`useI18n()\`.
1052
- if (callee.object.type === "Identifier" && callee.object.name === "_ctx" && method === "$t")
1053
- return translate(s, args, n);
1054
- if (callee.object.type === "Identifier" && callee.object.name === "$setup" && s.i18nT.has(method))
1055
- return translate(s, args, n);
1056
- if (callee.object.type === "Identifier" && (callee.object.name === "$setup" || callee.object.name === "_ctx")) {
1057
- const helper = s.helpers.get(method);
1058
- if (helper)
1059
- return helperCall(s, helper, args, n);
1060
- }
1061
- // `Math`, on numbers, as JavaScript computes it.
1062
- if (callee.object.type === "Identifier" && callee.object.name === "Math") {
1063
- const vals = args.map((a) => expr(s, a));
1064
- if (vals.length && vals.every((v) => isNumber(v.ty))) {
1065
- const ints = vals.every((v) => v.ty.k === "int");
1066
- if ((method === "max" || method === "min") && vals.length >= 2) {
1067
- if (ints)
1068
- return { code: vals.slice(1).reduce((acc, v) => `${atom(acc)}.${method}(${bare(v.code)})`, vals[0].code), ty: INT };
1069
- return { code: vals.slice(1).reduce((acc, v) => `fv::js_${method}(${bare(acc)}, ${bare(asF64(v))})`, asF64(vals[0])), ty: FLOAT };
1070
- }
1071
- if (vals.length === 1) {
1072
- const x = vals[0];
1073
- if (method === "abs")
1074
- return ints ? intFromF64(`${receiver(asF64(x))}.abs()`) : { code: `${receiver(x.code)}.abs()`, ty: FLOAT };
1075
- if (method === "round")
1076
- return { code: `fv::js_round(${bare(asF64(x))})`, ty: FLOAT };
1077
- if (method === "floor" || method === "ceil" || method === "trunc")
1078
- return { code: `${receiver(asF64(x))}.${method}()`, ty: FLOAT };
1079
- }
1080
- }
1081
- return fail(comp, `\`Math.${method}()\` is supported on numbers as \`max\`, \`min\`, \`abs\`, \`round\`, \`floor\`, \`ceil\` and \`trunc\``, n);
1082
- }
1083
- const target = expr(s, callee.object);
1084
- if (target.ty.k === "str") {
1085
- const lone = loneOf(target);
1086
- switch (args.length === 0 ? method : "") {
1087
- case "trim":
1088
- return { code: `fv::js_trim(${strArg(target.code)})`, ty: STR, ...lone };
1089
- case "trimStart":
1090
- return { code: `fv::js_trim_start(${strArg(target.code)})`, ty: STR, ...lone };
1091
- case "trimEnd":
1092
- return { code: `fv::js_trim_end(${strArg(target.code)})`, ty: STR, ...lone };
1093
- // Unicode's default case mappings, which JavaScript and Rust both apply, final sigma included.
1094
- case "toUpperCase":
1095
- return { code: `&*${receiver(target.code)}.to_uppercase()`, ty: STR, ...lone };
1096
- case "toLowerCase":
1097
- return { code: `&*${receiver(target.code)}.to_lowercase()`, ty: STR, ...lone };
1098
- case "toString":
1099
- return target;
1100
- }
1101
- const m = stringMethod(s, target, method, args, n);
1102
- if (m)
1103
- return m;
1104
- }
1105
- if (isNumber(target.ty) && method === "toFixed" && args.length <= 1) {
1106
- // The digits are a literal, as they almost always are: 0 to 100.
1107
- const d = args.length ? args[0] : { type: "NumericLiteral", value: 0 };
1108
- if (d.type !== "NumericLiteral" || !Number.isInteger(d.value) || d.value < 0 || d.value > 100) {
1109
- fail(comp, "`.toFixed()` takes a literal number of digits, from 0 to 100", n);
1110
- }
1111
- return { code: `&*fv::js_to_fixed(${bare(asF64(target))}, ${d.value})`, ty: STR };
1112
- }
1113
- if (isNumber(target.ty) && method === "toString" && args.length === 0) {
1114
- return { code: `&*fv::Js(${bare(target.code)}).to_string()`, ty: STR };
1115
- }
1116
- if (target.ty.k === "list") {
1117
- // A list the props hold, of strings or integers, is searched and joined in place below.
1118
- const inPlace = target.iter === undefined && !target.lone && (target.ty.of.k === "str" || target.ty.of.k === "int");
1119
- const listed = listMethod(s, target, method, args, n) ?? (inPlace ? null : computedListMethod(s, target, method, args, n));
1120
- if (listed)
1121
- return listed;
1122
- }
1123
- if (target.ty.k === "list" && (target.ty.of.k === "str" || target.ty.of.k === "int")) {
1124
- const of = target.ty.of;
1125
- if (method === "includes" && args.length === 1) {
1126
- const v = expr(s, args[0]);
1127
- if (!sameTy(v.ty, of))
1128
- fail(comp, "`.includes()` looks for a value of the list's own type", args[0]);
1129
- if (of.k === "int")
1130
- return { code: `${atom(target.code)}.contains(&${operand(v.code, UNARY)})`, ty: BOOL };
1131
- const test = v.code === '""' ? "v.is_empty()" : binary("&**v", "==", v.code);
1132
- return { code: `${atom(target.code)}.iter().any(|v| ${test})`, ty: BOOL };
1133
- }
1134
- if (method === "join" && args.length <= 1) {
1135
- // JavaScript joins with a comma when given no separator.
1136
- const sep = args.length ? expr(s, args[0]) : { code: '","', ty: STR };
1137
- if (sep.ty.k !== "str")
1138
- fail(comp, "`.join()` takes a string", args[0]);
1139
- const each = of.k === "str" ? `${atom(target.code)}.iter().map(|v| &**v)` : `${atom(target.code)}.iter().map(|v| fv::Js(*v).to_string())`;
1140
- return { code: `&*${each}.collect::<Vec<_>>().join(${strArg(sep.code)})`, ty: STR, ...loneOf(sep) };
1141
- }
1142
- }
1143
- return fail(comp, `\`.${method}()\` is not supported`, n);
1144
- }
1145
- return fail(comp, "this call is not supported", n);
1146
- }
1147
- /** Whether `n` is `Object.<method>(…)`. */
1148
- export function isObjectCall(n, method) {
1149
- return (n?.type === "CallExpression" && n.callee.type === "MemberExpression" && !n.callee.computed &&
1150
- n.callee.object.type === "Identifier" && n.callee.object.name === "Object" && n.callee.property.name === method);
1151
- }
1152
- /** A string method beyond trimming and case mapping, or `null` when `method` is none of them.
1153
- * Indices and lengths count UTF-16 code units, as JavaScript's do; a result that may hold half of a
1154
- * surrogate pair is marked `lone`. */
1155
- function stringMethod(s, target, method, args, n) {
1156
- const comp = s.comp;
1157
- // As an argument, where a `&str` parameter coerces the borrow.
1158
- const t = strArg(target.code);
1159
- const arity = (least, most) => {
1160
- if (args.length < least || args.length > most) {
1161
- fail(comp, `\`.${method}()\` takes ${least === most ? least : `${least} to ${most}`} argument${most === 1 ? "" : "s"} here`, n);
1162
- }
1163
- };
1164
- const str = (i) => {
1165
- if (args[i]?.type === "RegExpLiteral")
1166
- fail(comp, `\`.${method}()\` with a regular expression, which the server does not run: give it a string`, args[i]);
1167
- const v = expr(s, args[i]);
1168
- if (v.ty.k !== "str")
1169
- fail(comp, `\`.${method}()\` takes a string that is present`, args[i]);
1170
- return v;
1171
- };
1172
- /** A number argument as an `f64`; `fallback` when it is left out or `undefined`. */
1173
- const num = (i, fallback) => {
1174
- if (args[i] === undefined)
1175
- return fallback;
1176
- const v = expr(s, args[i]);
1177
- if (v.ty.k === "undef")
1178
- return fallback;
1179
- if (!isNumber(v.ty))
1180
- fail(comp, `\`.${method}()\` takes a number that is present`, args[i]);
1181
- return asF64(v);
1182
- };
1183
- const cut = { lone: true };
1184
- switch (method) {
1185
- case "includes":
1186
- case "startsWith":
1187
- case "endsWith": {
1188
- // Without a position: `includes(x, 3)` would start the search part way.
1189
- arity(1, 1);
1190
- const x = str(0);
1191
- meet(comp, target, x, `\`.${method}()\``, n, "search");
1192
- const rust = { includes: "contains", startsWith: "starts_with", endsWith: "ends_with" }[method];
1193
- return { code: `${receiver(target.code)}.${rust}(${bare(x.code)})`, ty: BOOL };
1194
- }
1195
- case "indexOf":
1196
- case "lastIndexOf": {
1197
- arity(1, 1);
1198
- const x = str(0);
1199
- meet(comp, target, x, `\`.${method}()\``, n, "search");
1200
- return { code: `fv::js_${method === "indexOf" ? "index_of" : "last_index_of"}(${t}, ${strArg(x.code)})`, ty: INT };
1201
- }
1202
- case "slice":
1203
- case "substring": {
1204
- arity(0, 2);
1205
- const end = num(1, "");
1206
- return { code: `&*fv::js_${method}(${t}, ${num(0, "0.0")}, ${end ? `Some(${end})` : "None"})`, ty: STR, ...cut };
1207
- }
1208
- case "at": {
1209
- arity(1, 1);
1210
- const at = `fv::js_at(${t}, ${num(0, "0.0")})`;
1211
- if (!isTemporary(target))
1212
- return { code: at, ty: opt(STR), ...cut };
1213
- // Of a string built here, the character is copied out, to outlive it.
1214
- const held = `${at}.map(|v| std::borrow::Cow::<str>::Owned(v.to_owned()))`;
1215
- return { code: `${atom(held)}.as_deref()`, ty: opt(STR), held, ...cut };
1216
- }
1217
- case "charAt":
1218
- arity(0, 1);
1219
- // It borrows from the string, so it is a temporary when the string is.
1220
- return { code: `${isTemporary(target) ? "&*" : ""}fv::js_char_at(${t}, ${num(0, "0.0")})`, ty: STR, ...cut };
1221
- case "split": {
1222
- // Without a limit, and with a string separator: `split()` alone gives the whole string.
1223
- arity(1, 1);
1224
- const sep = str(0);
1225
- meet(comp, target, sep, "`.split()`", n, "search");
1226
- // An empty separator cuts between code units, so a pair in two.
1227
- return computed(`fv::js_split(${t}, ${strArg(sep.code)}).into_iter()`, STR, target.lone || !nonEmptyLiteral(sep));
1228
- }
1229
- case "replace":
1230
- case "replaceAll": {
1231
- arity(2, 2);
1232
- if (args[1].type === "ArrowFunctionExpression" || args[1].type === "FunctionExpression") {
1233
- fail(comp, `\`.${method}()\` with a function, which the server does not run: give it a string`, args[1]);
1234
- }
1235
- const [pattern, replacement] = [str(0), str(1)];
1236
- meet(comp, target, pattern, `\`.${method}()\``, n, "search");
1237
- meet(comp, target, replacement, `\`.${method}()\``, n, "join");
1238
- // `replaceAll("", …)` matches between code units, which cuts every pair in two.
1239
- const lone = target.lone || replacement.lone || (method === "replaceAll" && !nonEmptyLiteral(pattern));
1240
- return { code: `&*fv::js_${method === "replace" ? "replace" : "replace_all"}(${t}, ${strArg(pattern.code)}, ${strArg(replacement.code)})`, ty: STR, ...(lone ? cut : {}) };
1241
- }
1242
- case "padStart":
1243
- case "padEnd": {
1244
- arity(1, 2);
1245
- const fill = args.length > 1 ? str(1) : { code: '" "', ty: STR };
1246
- // The fill repeats itself, and is cut short where a pair may be: before a string starting
1247
- // with a half, the two would join.
1248
- const whole = fill.code.startsWith('"') && !/[\u{10000}-\u{10FFFF}]/u.test(fill.code);
1249
- if (fill.lone || (method === "padStart" && target.lone && !whole))
1250
- fail(comp, lonely(`\`.${method}()\``), n);
1251
- return { code: `&*fv::js_${method === "padStart" ? "pad_start" : "pad_end"}(${t}, ${num(0, "0.0")}, ${strArg(fill.code)})`, ty: STR, ...(target.lone || !whole ? cut : {}) };
1252
- }
1253
- case "repeat": {
1254
- arity(1, 1);
1255
- // JavaScript throws a `RangeError` for a negative or infinite count.
1256
- const c = args[0];
1257
- if ((c.type === "UnaryExpression" && c.operator === "-" && c.argument.type === "NumericLiteral" && c.argument.value > 0) || (c.type === "Identifier" && c.name === "Infinity")) {
1258
- fail(comp, "`.repeat()` with a negative or infinite count, which throws a `RangeError`", c);
1259
- }
1260
- // Repeated, a string ending with one half and starting with the other joins them.
1261
- if (target.lone)
1262
- fail(comp, lonely("`.repeat()`"), n);
1263
- return { code: `&*fv::js_repeat(${t}, ${num(0, "0.0")})`, ty: STR };
504
+ return fail(comp, "FV0623", "the two branches of `?:` differ in type", n);
1264
505
  }
1265
- case "toLocaleUpperCase":
1266
- case "toLocaleLowerCase":
1267
- return fail(comp, `\`.${method}()\` maps case by the locale the server runs in, which the browser need not share: use \`.${method.replace("Locale", "")}()\``, n);
1268
- }
1269
- return null;
1270
- }
1271
- /** `JSON.stringify(v)` as a Rust `String`: of a string, a number, a boolean, or a list of those. */
1272
- function json(s, v, n) {
1273
- // A half of a pair is written as an escape, `"\ud83e"`, which ferrovue cannot know to write.
1274
- if (v.lone)
1275
- fail(s.comp, lonely("`JSON.stringify()`"), n);
1276
- const one = (code, ty) => {
1277
- switch (ty.k) {
1278
- case "str":
1279
- return `fv::js_json_string(${code === "v" ? "&v" : strArg(code)})`;
1280
- case "int":
1281
- return `fv::Js(${bare(code)}).to_string()`;
1282
- case "float":
1283
- return `fv::js_json_number(${bare(code)})`;
1284
- case "bool":
1285
- return `(if ${condition(code)} { "true" } else { "false" }).to_owned()`;
1286
- default:
1287
- return fail(s.comp, "`JSON.stringify()` of a string, a number, a boolean or a list of those, present", n);
506
+ case "NewExpression": {
507
+ const made = n.callee.type === "Identifier" ? n.callee.name : n.callee.type === "MemberExpression" && !n.callee.computed ? `${n.callee.object.name ?? "…"}.${n.callee.property.name}` : "…";
508
+ return fail(comp, "FV0624", `\`new ${made}(…)\` builds an object the server has no twin for: compute the value in Rust and pass it as a prop`, n);
1288
509
  }
1289
- };
1290
- if (v.ty.k === "list") {
1291
- // A routine of the item alone is mapped as itself, without a closure around it.
1292
- const each = one("v", v.ty.of);
1293
- const f = /^([\w:]+)\(v\)$/.exec(each)?.[1];
1294
- return `format!("[{}]", ${items(v)}.map(${f ?? `|v| ${each}`}).collect::<Vec<_>>().join(","))`;
510
+ default:
511
+ return fail(comp, "FV0625", `\`${n.type}\` is not supported in a template`, n);
1295
512
  }
1296
- return one(v.code, v.ty);
1297
- }
1298
- export function helperCall(s, name, args, n) {
1299
- const h = ctx.helpers[name];
1300
- if (args.length !== h.params.length)
1301
- fail(s.comp, `\`${name}\` takes ${h.params.length} argument(s)`, n);
1302
- const code = args.map((a, i) => bare(coerce(s.comp, expr(s, a), h.params[i], a))).join(", ");
1303
- s.helperBytes.n += h.maxLen;
1304
- return { code: `${h.rust}(${code})`, ty: h.ret };
1305
513
  }