visaljs 0.0.9 → 0.0.10

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.
@@ -31,6 +31,7 @@ JSValue js_host_fs_read(JSContext *ctx, JSValue callee, JSValue this_val, uint32
31
31
  int js_node_uv_error(int e);
32
32
  JSValue js_host_errno_name(JSContext *ctx, JSValue callee, JSValue this_val, uint32_t argc, const JSValue *argv, JSValue new_target);
33
33
  JSValue js_host_timer_unref(JSContext *ctx, JSValue callee, JSValue this_val, uint32_t argc, const JSValue *argv, JSValue new_target);
34
+ JSValue js_host_loop_now(JSContext *ctx, JSValue callee, JSValue this_val, uint32_t argc, const JSValue *argv, JSValue new_target);
34
35
  JSValue js_host_timer_start(JSContext *ctx, JSValue callee, JSValue this_val, uint32_t argc, const JSValue *argv, JSValue new_target);
35
36
  JSValue js_host_timer_ref(JSContext *ctx, JSValue callee, JSValue this_val, uint32_t argc, const JSValue *argv, JSValue new_target);
36
37
  JSValue js_host_async_context_get(JSContext *ctx, JSValue callee, JSValue this_val, uint32_t argc, const JSValue *argv, JSValue new_target);
@@ -7,6 +7,7 @@
7
7
  // upgrade (or CONNECT) hands the socket over with 'upgrade' ('connect'). Idle keep-alive
8
8
  // connections close after keepAliveTimeout; server.timeout and setTimeout are the sockets'.
9
9
  // Not yet: the client, headersTimeout and requestTimeout, trailers.
10
+ import { hasInvalidHeaderChar, isHttpToken } from "./internal/http_chars.ts";
10
11
  import {
11
12
  httpAttach, httpBusy, httpDate, httpPending, httpWatchDrain, httpDetach, httpExpired, httpFedClose, httpFedOpen, httpFeed, httpFlush, httpParsers, httpWrite, timerUnref,
12
13
  } from "visaljs:host";
@@ -183,18 +184,16 @@ function addHeader(headers, name, value, join) {
183
184
  /* ---- OutgoingMessage: a response's (and a request's) headers ------------------------------------ */
184
185
 
185
186
  /* Node's checks: a header name is an HTTP token; a value has no control characters */
186
- const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/;
187
- const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
188
187
 
189
188
  export function validateHeaderName(name, label = "Header name") {
190
- if (typeof name !== "string" || !name || !tokenRegExp.test(name)) {
189
+ if (typeof name !== "string" || !isHttpToken(name)) {
191
190
  throw codeError(TypeError, "ERR_INVALID_HTTP_TOKEN", label + " must be a valid HTTP token [\"" + name + "\"]");
192
191
  }
193
192
  }
194
193
 
195
194
  export function validateHeaderValue(name, value) {
196
195
  if (value === undefined) throw codeError(TypeError, "ERR_HTTP_INVALID_HEADER_VALUE", "Invalid value \"" + value + "\" for header \"" + name + "\"");
197
- if (headerCharRegex.test(value)) throw codeError(TypeError, "ERR_INVALID_CHAR", "Invalid character in header content [\"" + name + "\"]");
196
+ if (hasInvalidHeaderChar(String(value))) throw codeError(TypeError, "ERR_INVALID_CHAR", "Invalid character in header content [\"" + name + "\"]");
198
197
  }
199
198
 
200
199
  const headersSent = (what) => codeError(Error, "ERR_HTTP_HEADERS_SENT", "Cannot " + what + " headers after they are sent to the client");
@@ -584,7 +583,7 @@ export class OutgoingMessage extends Stream {
584
583
  validateHeaderName(field, "Trailer name");
585
584
  const values = Array.isArray(value) && value.length > 1 ? value : [Array.isArray(value) ? value.join("; ") : value];
586
585
  for (const v of values) {
587
- if (headerCharRegex.test(v)) throw codeError(TypeError, "ERR_INVALID_CHAR", "Invalid character in trailer content [\"" + field + "\"]");
586
+ if (hasInvalidHeaderChar(String(v))) throw codeError(TypeError, "ERR_INVALID_CHAR", "Invalid character in trailer content [\"" + field + "\"]");
588
587
  this._trailer += field + ": " + v + "\r\n";
589
588
  }
590
589
  }
@@ -1176,7 +1175,7 @@ class ServerClass extends NetServer {
1176
1175
  } else {
1177
1176
  state.res = res;
1178
1177
  }
1179
- res.once("finish", () => this._resOnFinish(state, req, res));
1178
+ res.on("finish", () => this._resOnFinish(state, req, res)); /* Node's resOnFinish, an `on` listener too */
1180
1179
  if (this.requireHostHeader && major === 1 && minor === 1 && !req.headers.host) { /* Node: a 400, and the connection ends */
1181
1180
  res.writeHead(400, ["Connection", "close"]);
1182
1181
  res.end();
@@ -1189,8 +1188,11 @@ class ServerClass extends NetServer {
1189
1188
  /* Node's resOnFinish: the request is done with; the next response's turn, or the idle keep-alive
1190
1189
  * timeout */
1191
1190
  _resOnFinish(state, req, res) {
1192
- const i = state.incoming.indexOf(req);
1193
- if (i !== -1) state.incoming.splice(i, 1);
1191
+ if (state.incoming[0] === req) state.incoming.shift();
1192
+ else {
1193
+ const i = state.incoming.indexOf(req);
1194
+ if (i !== -1) state.incoming.splice(i, 1);
1195
+ }
1194
1196
  if (state.req === req && req.complete) state.req = null;
1195
1197
  if (state.res === res) state.res = null;
1196
1198
  if (res._last || !res._keepAlive) return; /* the socket is ending */
@@ -1625,7 +1627,7 @@ export class ClientRequest extends OutgoingMessage {
1625
1627
  let method = options.method;
1626
1628
  if (method !== null && method !== undefined && typeof method !== "string") throw invalidArgType("options.method", "of type string", method);
1627
1629
  if (method) {
1628
- if (!tokenRegExp.test(method)) throw codeError(TypeError, "ERR_INVALID_HTTP_TOKEN", "Method must be a valid HTTP token [\"" + method + "\"]");
1630
+ if (!isHttpToken(method)) throw codeError(TypeError, "ERR_INVALID_HTTP_TOKEN", "Method must be a valid HTTP token [\"" + method + "\"]");
1629
1631
  method = this.method = method.toUpperCase();
1630
1632
  } else {
1631
1633
  method = this.method = "GET";
@@ -0,0 +1,22 @@
1
+ "use static";
2
+ // The characters HTTP allows in header names (a token, RFC 9110 §5.6.2) and values: Node's
3
+ // tokenRegExp and headerCharRegex as loops, typed (setHeader checks both on every call).
4
+
5
+ export function isHttpToken(s: string): boolean {
6
+ for (let i = 0; i < s.length; i++) {
7
+ const c = s.charCodeAt(i);
8
+ const alnum = (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
9
+ /* ! # $ % & ' * + - . ^ _ ` | ~ */
10
+ if (!alnum && c !== 33 && !(c >= 35 && c <= 39) && c !== 42 && c !== 43 && c !== 45 && c !== 46 && c !== 94 && c !== 95 && c !== 96 && c !== 124 && c !== 126) return false;
11
+ }
12
+ return s.length > 0;
13
+ }
14
+
15
+ /** A character outside tab, 0x20-0x7e and 0x80-0xff. */
16
+ export function hasInvalidHeaderChar(s: string): boolean {
17
+ for (let i = 0; i < s.length; i++) {
18
+ const c = s.charCodeAt(i);
19
+ if ((c < 32 && c !== 9) || c === 127 || c > 255) return true;
20
+ }
21
+ return false;
22
+ }
@@ -9,7 +9,7 @@
9
9
  // Ported from Node.js (Copyright Node.js contributors, MIT): node/third_party/nodejs/LICENSE.
10
10
  import {
11
11
  errnoMessage, errnoName, netAddress, netBind, netCallback, netChmod, netClose, netConnect, netGuessHandle, netKeepAlive, netListen,
12
- netFd, netNoDelay, netOpen, netOpenFd, netReadStart, netReadStop, netRef, netReset, netShutdown, netWrite, timerUnref,
12
+ loopNow, netFd, netNoDelay, netOpen, netOpenFd, netReadStart, netReadStop, netRef, netReset, netShutdown, netWrite, timerUnref,
13
13
  } from "visaljs:host";
14
14
  import { ADDRCONFIG, lookup } from "./dns.js";
15
15
  import { EventEmitter } from "./events.js";
@@ -30,12 +30,6 @@ const UV_EOF = -4095;
30
30
  const UV_EINVAL = -22;
31
31
  const TIMEOUT_MAX = 2 ** 31 - 1;
32
32
 
33
- /* a monotonic clock in ms */
34
- const now = () => {
35
- const [seconds, nanoseconds] = process.hrtime();
36
- return seconds * 1e3 + nanoseconds / 1e6;
37
- };
38
-
39
33
  /* ---- Node's error shapes ------------------------------------------------------------------- */
40
34
 
41
35
  /** `read ECONNRESET` */
@@ -210,7 +204,8 @@ class SocketClass extends Duplex {
210
204
  this._keepAlive = options.keepAlive === true ? [true, ~~((options.keepAliveInitialDelay ?? 0) / 1000)] : null;
211
205
  this._unref = false;
212
206
  this._timer = null; /* the timeout: an unref'd timer, re-armed for the idle time left when it fires */
213
- this._timeoutMs = 0;
207
+ this._timerDue = 0; /* when _timer fires (loopNow's clock) */
208
+ this._timeoutMs = 0; /* 0: off; a pending _timer then finds nothing to do */
214
209
  this._lastActive = 0;
215
210
  this._onread = null;
216
211
  if (options.typeOfService !== undefined) feature("validateTypeOfService")(options.typeOfService);
@@ -468,16 +463,19 @@ class SocketClass extends Duplex {
468
463
  if (typeof msecs !== "number") throw invalidArgType("msecs", "of type number", msecs);
469
464
  if (!(msecs >= 0 && msecs !== Infinity)) throw outOfRange("msecs", "a non-negative finite number", msecs);
470
465
  if (msecs > TIMEOUT_MAX) msecs = TIMEOUT_MAX;
471
- this._clearTimeout();
466
+ /* the pending timer stays when it fires no later than the new deadline: _onTimer re-arms it
467
+ * for the rest, so a keep-alive socket, off for each request and on after it, sets no timer */
472
468
  if (msecs === 0) {
469
+ this._timeoutMs = 0;
473
470
  if (callback !== undefined) {
474
471
  validateFunction(callback, "callback");
475
472
  this.removeListener("timeout", callback);
476
473
  }
477
474
  } else {
478
475
  this._timeoutMs = msecs;
479
- this._lastActive = now();
480
- this._armTimeout(msecs);
476
+ this._lastActive = loopNow();
477
+ if (this._timer !== null && this._timerDue > this._lastActive + msecs) this._stopTimer();
478
+ if (this._timer === null) this._armTimeout(msecs);
481
479
  if (callback !== undefined) {
482
480
  validateFunction(callback, "callback");
483
481
  this.once("timeout", callback);
@@ -487,26 +485,32 @@ class SocketClass extends Duplex {
487
485
  }
488
486
 
489
487
  _armTimeout(ms) {
488
+ this._timerDue = loopNow() + ms;
490
489
  this._timer = timerUnref(() => this._onTimer(), ms);
491
490
  }
492
491
 
493
492
  _onTimer() {
494
493
  this._timer = null;
495
- const idle = now() - this._lastActive;
494
+ if (this._timeoutMs === 0) return;
495
+ const idle = loopNow() - this._lastActive;
496
496
  if (idle < this._timeoutMs - 1) this._armTimeout(this._timeoutMs - idle);
497
497
  else this.emit("timeout");
498
498
  }
499
499
 
500
- _clearTimeout() {
500
+ _stopTimer() {
501
501
  if (this._timer !== null) clearTimeout(this._timer);
502
502
  this._timer = null;
503
+ }
504
+
505
+ _clearTimeout() {
506
+ this._stopTimer();
503
507
  this._timeoutMs = 0;
504
508
  }
505
509
 
506
510
  /* activity: the timeout counts from now (Node's timer.refresh(), which re-arms a fired one) */
507
511
  _unrefTimer() {
508
512
  if (this._timeoutMs) {
509
- this._lastActive = now();
513
+ this._lastActive = loopNow();
510
514
  if (this._timer === null) this._armTimeout(this._timeoutMs);
511
515
  }
512
516
  }
@@ -19,6 +19,7 @@
19
19
  #include "jscontext.h"
20
20
  #include "js_ops.h"
21
21
  #include "jsstring.h"
22
+ #include "js_uv.h"
22
23
 
23
24
  /* Each error by its C errno and its libuv code: the same number on POSIX, but on Windows libuv
24
25
  * has codes of its own (UV_ECONNREFUSED is -4078) while the C library's errno has the C values. */
@@ -155,6 +156,14 @@ JSValue js_host_timer_unref(JSContext *ctx, JSValue callee, JSValue this_val, ui
155
156
  return js_int32((int32_t)js_add_timer(ctx, argv[0], js_as_number(argv[1]), true));
156
157
  }
157
158
 
159
+ /* loopNow() → libuv's time in ms, as of the last poll (Node's getLibuvNow): what a socket's
160
+ * activity is measured with, without a clock read or an allocation per read and write */
161
+ JSValue js_host_loop_now(JSContext *ctx, JSValue callee, JSValue this_val, uint32_t argc, const JSValue *argv,
162
+ JSValue new_target) {
163
+ (void)callee, (void)this_val, (void)argc, (void)argv, (void)new_target;
164
+ return js_number((double)uv_now(js_uv_loop(ctx)));
165
+ }
166
+
158
167
  /* the id a timer primitive takes: a positive int32, else 0 */
159
168
  static uint32_t timer_id(uint32_t argc, const JSValue *argv, uint32_t i) {
160
169
  return i < argc && js_is_int32(argv[i]) && js_as_int32(argv[i]) > 0 ? (uint32_t)js_as_int32(argv[i]) : 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "visaljs",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
4
4
  "description": "Ahead-of-time JavaScript to C compiler: the command line",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -10,7 +10,9 @@
10
10
  #include <stdint.h>
11
11
  #include <string.h>
12
12
 
13
+ #include "js_convert.h"
13
14
  #include "js_object.h"
15
+ #include "js_ops.h"
14
16
 
15
17
  #define JS_BUFFER_RESIZABLE 0x01u
16
18
  #define JS_BUFFER_DETACHED 0x02u
@@ -76,4 +78,187 @@ int js_typed_array_type(JSValue v);
76
78
  /* A new, zeroed Uint8Array of `length` bytes; its bytes are js_buffer_source_bytes'. */
77
79
  JS_WARN_UNUSED JSValue js_new_uint8_array(JSContext *ctx, size_t length);
78
80
 
81
+ /* ---- Generated code: a typed array's elements inline ------------------------------------------ */
82
+
83
+ /* The bytes of element i of a typed array generated code may read or write inline: a view of a
84
+ * fixed-size buffer (it can't shrink below the view, so i < length is in bounds), not detached,
85
+ * not immutable (for a write). NULL for anything else, which takes js_get_elem / js_set_elem. */
86
+ static JS_FAST_PATH uint8_t *js_ta_inline_elem(JSContext *ctx, JSValue obj, int32_t i, bool write) {
87
+ if (!js_is_object(obj) || js_as_object(obj)->shape->cls != ctx->rt->typed_array_class) return NULL;
88
+ const JSTypedArray *ta = (const JSTypedArray *)js_as_object(obj);
89
+ const JSArrayBuffer *b = js_as_array_buffer(ta->buffer);
90
+ uint32_t bad = JS_BUFFER_DETACHED | JS_BUFFER_RESIZABLE | (write ? JS_BUFFER_IMMUTABLE : 0);
91
+ if (ta->length_tracking || i < 0 || (size_t)i >= ta->length || (b->flags & bad)) return NULL;
92
+ return b->data + ta->byte_offset;
93
+ }
94
+
95
+ /* obj[i]: a dense array's element or a typed array's (Int8, Uint8, Int32, Float64) inline. */
96
+ static JS_FAST_PATH JSValue js_get_index_ta(JSContext *ctx, JSValue obj, JSValue key) {
97
+ if (JS_LIKELY(js_is_int32(key)) && !js_is_array(obj)) {
98
+ int32_t i = js_as_int32(key);
99
+ const uint8_t *p = js_ta_inline_elem(ctx, obj, i, false);
100
+ if (p) switch (((const JSTypedArray *)js_as_object(obj))->type) {
101
+ case JS_TA_UINT8: case JS_TA_UINT8C: return js_int32(p[i]);
102
+ case JS_TA_INT8: return js_int32((int8_t)p[i]);
103
+ case JS_TA_INT32: { int32_t v; memcpy(&v, p + 4 * (size_t)i, 4); return js_int32(v); }
104
+ case JS_TA_FLOAT64: { double v; memcpy(&v, p + 8 * (size_t)i, 8); return js_number(v); }
105
+ default: break;
106
+ }
107
+ }
108
+ return js_get_index(ctx, obj, key);
109
+ }
110
+
111
+ /* obj[i] = v: the same, for a Number v (no ToNumber code to run). */
112
+ static JS_FAST_PATH int js_set_index_ta(JSContext *ctx, JSValue obj, JSValue key, JSValue v, bool strict) {
113
+ if (JS_LIKELY(js_is_int32(key)) && js_is_number(v) && !js_is_array(obj)) {
114
+ int32_t i = js_as_int32(key);
115
+ uint8_t *p = js_ta_inline_elem(ctx, obj, i, true);
116
+ if (p) switch (((const JSTypedArray *)js_as_object(obj))->type) {
117
+ case JS_TA_UINT8: case JS_TA_INT8: p[i] = (uint8_t)(js_is_int32(v) ? js_as_int32(v) : js_double_to_int32(js_as_number(v))); return 1;
118
+ case JS_TA_INT32: { int32_t x = js_is_int32(v) ? js_as_int32(v) : js_double_to_int32(js_as_number(v)); memcpy(p + 4 * (size_t)i, &x, 4); return 1; }
119
+ case JS_TA_FLOAT64: { double x = js_as_number(v); memcpy(p + 8 * (size_t)i, &x, 8); return 1; }
120
+ default: break;
121
+ }
122
+ }
123
+ return js_set_index(ctx, obj, key, v, strict);
124
+ }
125
+
126
+ /* The same with a double key (an unboxed index): an integral one is the int32 key (-0 too: "0"). */
127
+ static inline JSValue js_get_index_ta_f64(JSContext *ctx, JSValue obj, double key) {
128
+ int32_t i = (int32_t)key;
129
+ if (key >= -2147483648.0 && key <= 2147483647.0 && (double)i == key) return js_get_index_ta(ctx, obj, js_int32(i));
130
+ return js_get_index_f64(ctx, obj, key);
131
+ }
132
+ static inline int js_set_index_ta_f64(JSContext *ctx, JSValue obj, double key, JSValue v, bool strict) {
133
+ int32_t i = (int32_t)key;
134
+ if (key >= -2147483648.0 && key <= 2147483647.0 && (double)i == key) return js_set_index_ta(ctx, obj, js_int32(i), v, strict);
135
+ return js_set_index_f64(ctx, obj, key, v, strict);
136
+ }
137
+
138
+ /* A typed array's elements as generated code holds them (the typed-arrays pass): taken once,
139
+ * for an array nothing else can reach, so nothing detaches or resizes its buffer. Empty (length
140
+ * 0) when the value isn't a typed array of that type: every access then takes the generic path. */
141
+ typedef struct JSTAView {
142
+ uint8_t *base;
143
+ size_t length;
144
+ int type; /* the element type it's for: a slow path that may have run code takes it again */
145
+ } JSTAView;
146
+
147
+ static inline JSTAView js_ta_view(JSContext *ctx, JSValue obj, int type) {
148
+ JSTAView v = { NULL, 0, type };
149
+ if (!js_is_object(obj) || js_as_object(obj)->shape->cls != ctx->rt->typed_array_class) return v;
150
+ const JSTypedArray *ta = (const JSTypedArray *)js_as_object(obj);
151
+ const JSArrayBuffer *b = js_as_array_buffer(ta->buffer);
152
+ if (ta->type != type || ta->length_tracking || (b->flags & (JS_BUFFER_DETACHED | JS_BUFFER_RESIZABLE | JS_BUFFER_IMMUTABLE)) || !b->data) return v;
153
+ v.base = b->data + ta->byte_offset;
154
+ v.length = ta->length;
155
+ return v;
156
+ }
157
+
158
+ /* Whether v is a typed array of that element type (a typed function's typed array parameter). */
159
+ static inline bool js_ta_is(JSContext *ctx, JSValue v, int type) {
160
+ return js_is_object(v) && js_as_object(v)->shape->cls == ctx->rt->typed_array_class && ((const JSTypedArray *)js_as_object(v))->type == type;
161
+ }
162
+
163
+ /* The index a key names when it's in the view, else false. */
164
+ static JS_FAST_PATH bool js_tav_index(const JSTAView *v, JSValue key, size_t *i) {
165
+ if (!js_is_int32(key) || js_as_int32(key) < 0 || (size_t)js_as_int32(key) >= v->length) return false;
166
+ *i = (size_t)js_as_int32(key);
167
+ return true;
168
+ }
169
+ static JS_FAST_PATH bool js_tav_index_d(const JSTAView *v, double key, size_t *i) {
170
+ if (!(key >= 0 && key < (double)v->length) || (double)(size_t)key != key) return false;
171
+ *i = (size_t)key;
172
+ return true;
173
+ }
174
+
175
+ /* Each element type's read and write (a Number, converted as the spec's NumericToRawBytes). */
176
+ #define JS_TAV_ACCESS(name, ctype, box, unbox) \
177
+ static JS_FAST_PATH JSValue js_tav_get_##name(JSContext *ctx, JSTAView *v, JSValue obj, JSValue key) { \
178
+ size_t i; \
179
+ if (JS_LIKELY(js_tav_index(v, key, &i))) { ctype x; memcpy(&x, v->base + i * sizeof x, sizeof x); return box(x); } \
180
+ JSValue r = js_get_elem(ctx, obj, key); \
181
+ *v = js_ta_view(ctx, obj, v->type); /* a getter may have run */ \
182
+ return r; \
183
+ } \
184
+ static JS_FAST_PATH JSValue js_tav_get_##name##_d(JSContext *ctx, JSTAView *v, JSValue obj, double key) { \
185
+ size_t i; \
186
+ if (JS_LIKELY(js_tav_index_d(v, key, &i))) { ctype x; memcpy(&x, v->base + i * sizeof x, sizeof x); return box(x); } \
187
+ JSValue r = js_get_elem(ctx, obj, js_number(key)); \
188
+ *v = js_ta_view(ctx, obj, v->type); \
189
+ return r; \
190
+ } \
191
+ static JS_FAST_PATH JSValue js_tav_get_##name##_i(JSContext *ctx, JSTAView *v, JSValue obj, int32_t key) { \
192
+ if (JS_LIKELY((uint32_t)key < v->length)) { ctype x; memcpy(&x, v->base + (size_t)(uint32_t)key * sizeof x, sizeof x); return box(x); } \
193
+ JSValue r = js_get_elem(ctx, obj, js_int32(key)); \
194
+ *v = js_ta_view(ctx, obj, v->type); \
195
+ return r; \
196
+ } \
197
+ static JS_FAST_PATH int js_tav_set_##name##_i(JSContext *ctx, JSTAView *v, JSValue obj, int32_t key, JSValue val, bool strict) { \
198
+ if (JS_LIKELY(js_is_number(val) && (uint32_t)key < v->length)) { ctype x = unbox(val); memcpy(v->base + (size_t)(uint32_t)key * sizeof x, &x, sizeof x); return 1; } \
199
+ int r = js_set_elem(ctx, obj, js_int32(key), val, strict); \
200
+ *v = js_ta_view(ctx, obj, v->type); \
201
+ return r; \
202
+ } \
203
+ static JS_FAST_PATH JSValue js_tav_get_##name##_l(JSContext *ctx, JSTAView *v, JSValue obj, int64_t key) { \
204
+ if (JS_LIKELY((uint64_t)key < v->length)) { ctype x; memcpy(&x, v->base + (size_t)key * sizeof x, sizeof x); return box(x); } \
205
+ JSValue r = js_get_elem(ctx, obj, js_number((double)key)); \
206
+ *v = js_ta_view(ctx, obj, v->type); \
207
+ return r; \
208
+ } \
209
+ static JS_FAST_PATH int js_tav_set_##name##_l(JSContext *ctx, JSTAView *v, JSValue obj, int64_t key, JSValue val, bool strict) { \
210
+ if (JS_LIKELY(js_is_number(val) && (uint64_t)key < v->length)) { ctype x = unbox(val); memcpy(v->base + (size_t)key * sizeof x, &x, sizeof x); return 1; } \
211
+ int r = js_set_elem(ctx, obj, js_number((double)key), val, strict); \
212
+ *v = js_ta_view(ctx, obj, v->type); \
213
+ return r; \
214
+ } \
215
+ static JS_FAST_PATH int js_tav_set_##name(JSContext *ctx, JSTAView *v, JSValue obj, JSValue key, JSValue val, bool strict) { \
216
+ size_t i; \
217
+ if (JS_LIKELY(js_is_number(val) && js_tav_index(v, key, &i))) { ctype x = unbox(val); memcpy(v->base + i * sizeof x, &x, sizeof x); return 1; } \
218
+ int r = js_set_elem(ctx, obj, key, val, strict); /* valueOf, a setter: they may have run */ \
219
+ *v = js_ta_view(ctx, obj, v->type); \
220
+ return r; \
221
+ } \
222
+ static JS_FAST_PATH int js_tav_set_##name##_d(JSContext *ctx, JSTAView *v, JSValue obj, double key, JSValue val, bool strict) { \
223
+ size_t i; \
224
+ if (JS_LIKELY(js_is_number(val) && js_tav_index_d(v, key, &i))) { ctype x = unbox(val); memcpy(v->base + i * sizeof x, &x, sizeof x); return 1; } \
225
+ int r = js_set_elem(ctx, obj, js_number(key), val, strict); \
226
+ *v = js_ta_view(ctx, obj, v->type); \
227
+ return r; \
228
+ }
229
+ static JS_FAST_PATH int32_t js_tav_to_int32(JSValue v) { return js_is_int32(v) ? js_as_int32(v) : js_double_to_int32(js_as_number(v)); }
230
+ #define JS_TAV_INT(x) js_int32((int32_t)(x))
231
+ JS_TAV_ACCESS(i8, int8_t, JS_TAV_INT, (int8_t)js_tav_to_int32)
232
+ JS_TAV_ACCESS(u8, uint8_t, JS_TAV_INT, (uint8_t)js_tav_to_int32)
233
+ JS_TAV_ACCESS(i32, int32_t, JS_TAV_INT, js_tav_to_int32)
234
+ JS_TAV_ACCESS(f64, double, js_number, js_as_number)
235
+
236
+ /* A Float64Array's element as a double, for typed code ("use static": its type is number):
237
+ * past the end, undefined as a number (NaN). False with an exception pending. And a store of a
238
+ * double, boxed only on the slow path. */
239
+ static inline bool js_tav_num_slow(JSContext *ctx, JSTAView *v, JSValue obj, JSValue key, double *out) {
240
+ JSValue r = js_get_elem(ctx, obj, key);
241
+ *v = js_ta_view(ctx, obj, v->type);
242
+ if (js_is_exception(r)) return false;
243
+ if (js_is_number(r)) { *out = js_as_number(r); return true; }
244
+ return js_to_number(ctx, out, r) == 0;
245
+ }
246
+ #define JS_TAV_F64(suffix, ktype, in_view, boxed_key) \
247
+ static JS_FAST_PATH bool js_tav_num_f64##suffix(JSContext *ctx, JSTAView *v, JSValue obj, ktype key, double *out) { \
248
+ size_t i; \
249
+ if (JS_LIKELY(in_view)) { memcpy(out, v->base + i * 8, 8); return true; } \
250
+ return js_tav_num_slow(ctx, v, obj, boxed_key, out); \
251
+ } \
252
+ static JS_FAST_PATH int js_tav_put_f64##suffix(JSContext *ctx, JSTAView *v, JSValue obj, ktype key, double x, bool strict) { \
253
+ size_t i; \
254
+ if (JS_LIKELY(in_view)) { memcpy(v->base + i * 8, &x, 8); return 1; } \
255
+ int r = js_set_elem(ctx, obj, boxed_key, js_number(x), strict); \
256
+ *v = js_ta_view(ctx, obj, v->type); \
257
+ return r; \
258
+ }
259
+ JS_TAV_F64(, JSValue, js_tav_index(v, key, &i), key)
260
+ JS_TAV_F64(_d, double, js_tav_index_d(v, key, &i), js_number(key))
261
+ JS_TAV_F64(_i, int32_t, ((i = (size_t)(uint32_t)key) < v->length), js_int32(key))
262
+ JS_TAV_F64(_l, int64_t, ((i = (size_t)(uint64_t)key) < v->length), js_number((double)key))
263
+
79
264
  #endif /* JS_BUFFER_H */
@@ -211,6 +211,59 @@ static inline JSValue js_call_char_code_at(JSContext *ctx, JSValue f, JSValue s,
211
211
  return js_call_site(ctx, f, s, 1, &i, site);
212
212
  }
213
213
 
214
+ /* s.charCodeAt(i) in typed code ("use static"), which trusts the built-ins to be the standard
215
+ * ones (char_code_at): s is a string; its unit read inline, else (a rope, an index out of
216
+ * range) the built-in's answer. */
217
+ static inline double js_string_char_code_at(JSContext *ctx, JSValue s, double i) {
218
+ JSStrView v;
219
+ if (JS_LIKELY(i >= 0 && i < 4294967295.0 && js_string_units(s, &v) && (uint32_t)i < v.length && (double)(uint32_t)i == i))
220
+ return (double)js_view_at(v, (uint32_t)i);
221
+ JSValue index = js_number(i);
222
+ return js_as_number(js_core_string_proto_char_code_at(ctx, JS_UNDEFINED, s, 1, &index, JS_UNDEFINED));
223
+ }
224
+
225
+ /* s.charCodeAt(i) in typed code for an index the optimizer proved in s: the unit, an int32 (a
226
+ * rope not yet flattened takes the built-in). */
227
+ static inline int32_t js_string_unit_at(JSContext *ctx, JSValue s, uint32_t i) {
228
+ JSStrView v;
229
+ if (JS_LIKELY(js_string_units(s, &v))) return (int32_t)js_view_at(v, i);
230
+ return (int32_t)js_string_char_code_at(ctx, s, (double)i);
231
+ }
232
+
233
+ /* Function.prototype.apply and call: generated code tells them by their entry. */
234
+ JSValue js_function_proto_apply(JSContext *ctx, JSValue callee, JSValue this_val, uint32_t argc, const JSValue *argv, JSValue new_target);
235
+ JSValue js_function_proto_call(JSContext *ctx, JSValue callee, JSValue this_val, uint32_t argc, const JSValue *argv, JSValue new_target);
236
+
237
+ /* f.apply(t, args), `m` the value of f.apply: when m is the built-in and f callable, f is called
238
+ * without the built-in in between, with a short dense array's elements copied to the stack (its
239
+ * elements are its own data properties: reading them runs no code; copied, as f may change the
240
+ * array). Anything else is the call of m. */
241
+ static inline JSValue js_call_apply(JSContext *ctx, JSValue m, JSValue f, JSValue t, JSValue args, const char *site) {
242
+ if (JS_LIKELY(js_is_function(m) && js_as_function(m)->entry == js_function_proto_apply && js_is_callable(f))) {
243
+ if (js_is_nullish(args)) return js_call(ctx, f, t, 0, NULL);
244
+ if (js_is_array(args)) {
245
+ JSObject *a = js_as_object(args);
246
+ JSElements *e = a->elements;
247
+ uint32_t n = js_array_length(a);
248
+ JSValue copy[8];
249
+ if (e->kind == JS_ELEMENTS_DENSE && e->length == n && n <= 8) {
250
+ uint32_t i = 0;
251
+ while (i < n && !js_is_empty(e->data[i])) copy[i] = e->data[i], i++;
252
+ if (i == n) return js_call(ctx, f, t, n, copy);
253
+ }
254
+ }
255
+ }
256
+ return js_call_site(ctx, m, f, 2, (const JSValue[]){ t, args }, site);
257
+ }
258
+
259
+ /* f.call(t, …), `m` the value of f.call: f called directly when m is the built-in and f callable.
260
+ * argv: t, then the arguments. */
261
+ static inline JSValue js_call_call(JSContext *ctx, JSValue m, JSValue f, uint32_t argc, const JSValue *argv, const char *site) {
262
+ if (JS_LIKELY(js_is_function(m) && js_as_function(m)->entry == js_function_proto_call && js_is_callable(f)))
263
+ return js_call(ctx, f, argc ? argv[0] : JS_UNDEFINED, argc ? argc - 1 : 0, argc ? argv + 1 : NULL);
264
+ return js_call_site(ctx, m, f, argc, argv, site);
265
+ }
266
+
214
267
  /* String.fromCharCode(c): a unit up to 0xFF is a static one-unit string. */
215
268
  static inline JSValue js_call_from_char_code(JSContext *ctx, JSValue f, JSValue this_val, JSValue c, const char *site) {
216
269
  if (JS_LIKELY(js_is_function(f) && js_as_function(f)->entry == js_core_string_from_char_code && js_is_int32(c)
@@ -28,6 +28,9 @@ JS_WARN_UNUSED JSValue js_throw_reference_error(JSContext *ctx, const char *fmt,
28
28
  JS_WARN_UNUSED JSValue js_throw_syntax_error(JSContext *ctx, const char *fmt, ...);
29
29
  JS_WARN_UNUSED JSValue js_throw_uri_error(JSContext *ctx, const char *fmt, ...);
30
30
  JS_WARN_UNUSED JSValue js_throw_stack_overflow(JSContext *ctx); /* RangeError: Maximum call stack size exceeded */
31
+ /* ERR_INVALID_ARG_TYPE: `The "dest" argument must be <expected>. Received …` (Node's wording
32
+ * of the value). Generated code calls it: a "use static" function's checked entry. */
33
+ JS_WARN_UNUSED JSValue js_throw_invalid_arg_type(JSContext *ctx, const char *name, const char *expected, JSValue value);
31
34
 
32
35
  /* ---- Catching ---------------------------------------------------------- */
33
36
 
@@ -79,7 +79,7 @@ typedef struct JSFunction { /* kind = FUNCTION */
79
79
  JSContext *realm; /* the realm the function was created in */
80
80
  uint32_t flags;
81
81
  uint32_t pad_;
82
- struct JSShape *instance_shape; /* a class's instances' root shape, made at its first `new` (js_new_class_instance) */
82
+ struct JSShape *instance_shape; /* the root shape of the objects `new` makes with it as new.target: inline slots for all their constructors add */
83
83
  } JSFunction;
84
84
 
85
85
  extern const JSClass js_class_function;
@@ -296,10 +296,10 @@ JS_WARN_UNUSED JSValue js_own_keys(JSContext *ctx, JSObject *o);
296
296
  #define JS_IC_EMPTY 0
297
297
  #define JS_IC_OWN 1 /* get: an own data property; set: an own writable data property */
298
298
  #define JS_IC_PROTO 2 /* get: a data property of `holder`, `depth` prototypes up */
299
- #define JS_IC_ADD 3 /* set: adding the key takes the receiver from `shape` to `next` */
299
+ #define JS_IC_ADD 3 /* set: adding the key takes the receiver from `shape` to `next`; `depth` prototypes up to null, or to one whose writable data property it shadows */
300
300
  #define JS_IC_GETTER 4 /* get: an accessor of `holder` (NULL: the receiver), `depth` prototypes up */
301
301
  #define JS_IC_ABSENT 5 /* get: no such property on the receiver or its `depth` prototypes (the last's proto is null) */
302
- #define JS_IC_MAX_DEPTH 4
302
+ #define JS_IC_MAX_DEPTH 8 /* prototypes a cache can check: Node's sockets are 6 deep (Socket, Duplex, Readable, Stream, EventEmitter, Object) */
303
303
 
304
304
  /* One per property access site with a constant named key; a site is either a get or a
305
305
  * set. Monomorphic: a miss refills it. Never caches dictionary shapes (their layout
@@ -314,7 +314,7 @@ typedef struct JSPropCache {
314
314
  JSShape *fast; /* OWN, inline slot: the receiver shape; else NULL */
315
315
  uint16_t fast_off; /* with `fast`: the slot's byte offset in the object */
316
316
  uint8_t kind; /* JS_IC_* */
317
- uint8_t depth; /* PROTO: hops to the holder; ADD: prototypes up to null */
317
+ uint8_t depth; /* PROTO: hops to the holder; ADD: prototypes checked (JS_IC_ADD) */
318
318
  uint32_t slot; /* OWN, PROTO: the slot */
319
319
  JSShape *shape; /* receiver shape; NULL = empty */
320
320
  JSObject *holder; /* PROTO */
@@ -326,6 +326,8 @@ typedef struct JSPropCache {
326
326
  /* A module's caches, once at startup (the GC resets them weakly). */
327
327
  void js_register_prop_caches(JSRuntime *rt, JSPropCache *ics, size_t n);
328
328
 
329
+ /* The slow paths of a named access: `ic` is the site's cache, or NULL for a computed key's access
330
+ * (the runtime's shared caches only). */
329
331
  JS_WARN_UNUSED JSValue js_get_prop_slow(JSContext *ctx, JSValue obj, JSValue key, JSPropCache *ic);
330
332
  JS_WARN_UNUSED int js_set_prop_slow(JSContext *ctx, JSValue obj, JSValue key, JSValue v, bool strict, JSPropCache *ic);
331
333
 
@@ -373,6 +375,22 @@ static inline int js_set_prop(JSContext *ctx, JSValue obj, JSValue key, JSValue
373
375
  return js_set_prop_slow(ctx, obj, key, v, strict, ic);
374
376
  }
375
377
 
378
+ /* obj[key] and obj[key] = v at a site whose key is most likely always the same symbol or string
379
+ * (the optimizer's guess: a module binding stored once, as Node's kState). `site` holds the key
380
+ * the site's cache is for (EMPTY: none yet): while the key is that one, the access is a named
381
+ * access's, inline cache and all. Another key the slow path makes the site's, or, when it isn't
382
+ * a property key already (an index, a string not interned), accesses generically. */
383
+ JS_WARN_UNUSED JSValue js_get_keyed_slow(JSContext *ctx, JSValue obj, JSValue key, JSValue *site, JSPropCache *ic);
384
+ JS_WARN_UNUSED int js_set_keyed_slow(JSContext *ctx, JSValue obj, JSValue key, JSValue v, bool strict, JSValue *site, JSPropCache *ic);
385
+ static inline JSValue js_get_keyed(JSContext *ctx, JSValue obj, JSValue key, JSValue *site, JSPropCache *ic) {
386
+ if (JS_LIKELY(js_same_bits(key, *site))) return js_get_prop(ctx, obj, key, ic);
387
+ return js_get_keyed_slow(ctx, obj, key, site, ic);
388
+ }
389
+ static inline int js_set_keyed(JSContext *ctx, JSValue obj, JSValue key, JSValue v, bool strict, JSValue *site, JSPropCache *ic) {
390
+ if (JS_LIKELY(js_same_bits(key, *site))) return js_set_prop(ctx, obj, key, v, strict, ic);
391
+ return js_set_keyed_slow(ctx, obj, key, v, strict, site, ic);
392
+ }
393
+
376
394
  /* An object's new shape. When the object is a prototype, caches that checked the chain it's on
377
395
  * may be stale: the runtime's proto_epoch moves on. */
378
396
  static JS_FAST_PATH void js_object_set_shape(JSContext *ctx, JSObject *o, JSShape *s) {
@@ -46,6 +46,33 @@ JS_WARN_UNUSED JSValue js_ge(JSContext *ctx, JSValue a, JSValue b);
46
46
  /* ===, !==: never throw (strings compare by content). */
47
47
  bool js_strict_equals(JSContext *ctx, JSValue a, JSValue b);
48
48
  static inline JSValue js_strict_eq(JSContext *ctx, JSValue a, JSValue b) { return js_bool(js_strict_equals(ctx, a, b)); }
49
+ /* A Number as a typed file's ("use static") int, an int64_t: truncated toward zero and wrapped
50
+ * modulo 2^64, as ToInt32 is for 32 bits; NaN and the infinities 0 (a plain C conversion of those
51
+ * would be undefined behaviour). */
52
+ static inline int64_t js_f64_to_i64(double d) {
53
+ if (d >= -9223372036854775808.0 && d < 9223372036854775808.0) return (int64_t)d;
54
+ if (d != d || d == INFINITY || d == -INFINITY) return 0;
55
+ double m = fmod(trunc(d), 18446744073709551616.0); /* exact: d is an integer this large */
56
+ if (m < 0) m += 18446744073709551616.0;
57
+ return (int64_t)(uint64_t)m;
58
+ }
59
+ /* A Number value as an int; anything else (typed code's caller passed it unchecked) 0. */
60
+ static inline int64_t js_value_to_i64(JSValue v) {
61
+ if (js_is_int32(v)) return js_as_int32(v);
62
+ return js_is_number(v) ? js_f64_to_i64(js_as_number(v)) : 0;
63
+ }
64
+
65
+ /* v === d, d a number literal (not NaN): v is a Number of that value (0 and -0 alike). */
66
+ static inline bool js_strict_eq_num(JSValue v, double d) {
67
+ if (js_is_int32(v)) return (double)js_as_int32(v) == d;
68
+ return js_is_number(v) && js_as_number(v) == d;
69
+ }
70
+
71
+ /* a === s, s a string literal: an atom, so a string with its units is s itself unless it isn't
72
+ * interned */
73
+ static inline bool js_strict_eq_atom(JSContext *ctx, JSValue a, JSValue s) {
74
+ return js_same_bits(a, s) || (js_is_string(a) && !js_is_atom(a) && js_string_equals(ctx, a, s));
75
+ }
49
76
  static inline JSValue js_strict_ne(JSContext *ctx, JSValue a, JSValue b) { return js_bool(!js_strict_equals(ctx, a, b)); }
50
77
 
51
78
  /* A switch whose cases are all string literals: the index of the first case `v` is === to, or
@@ -17,6 +17,7 @@
17
17
  #include "js_console.h"
18
18
  #include "js_ops.h"
19
19
  #include "js_object.h"
20
+ #include "js_buffer.h"
20
21
  #include "js_function.h"
21
22
  #include "js_error.h"
22
23
  #include "js_generator.h"
@@ -13,9 +13,6 @@
13
13
  JS_WARN_UNUSED JSValue js_throw_node_error(JSContext *ctx, JSErrorKind kind, const char *code, const char *fmt, ...);
14
14
  /* ERR_INVALID_THIS: `Value of "this" must be of type TextDecoder`. */
15
15
  JS_WARN_UNUSED JSValue js_throw_invalid_this(JSContext *ctx, const char *type);
16
- /* ERR_INVALID_ARG_TYPE: `The "dest" argument must be <expected>. Received …` (Node's wording
17
- * of the value). */
18
- JS_WARN_UNUSED JSValue js_throw_invalid_arg_type(JSContext *ctx, const char *name, const char *expected, JSValue value);
19
16
  /* Node's "Received …" tail for a value: " Received type number (1)", " Received an instance of
20
17
  * Array", " Received undefined". */
21
18
  void js_node_received(JSContext *ctx, JSValue v, char *buf, size_t cap);