@tbela99/rust-css-parser-wasm 0.0.0-stage → 2.3.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.
@@ -0,0 +1,742 @@
1
+ // Port of the public API of src/ast/arena.ts over the rust arenas.
2
+ //
3
+ // The columns (dataTypes, parents, ...) are typed arrays over the rust memory: reads and writes go to the arena
4
+ // without a copy. They are created again when the arena reallocates its columns (its generation changes) or when the
5
+ // memory moves (WASM memory growth). The other methods are rust calls.
6
+ //
7
+ // An arena exported with toTransferableArenaObject() or created with fromTransferableArenaObjects() uses javascript
8
+ // buffers as its columns, like the typescript arenas: the buffers can be transferred to another thread. Rust memory
9
+ // cannot be transferred, so the buffers are copied into the rust arena before each call and copied back after it,
10
+ // until the arena grows (or until the buffers are transferred: the arena can no longer be used).
11
+
12
+ import { classes, columnTypes, rt } from "../core.js";
13
+ import { ARENA, ARENAID, AstArenaNode } from "./arena-node.js";
14
+ import { EnumToken } from "./types.js";
15
+
16
+ export const TokenField = Object.freeze({
17
+ L: 0,
18
+ R: 1,
19
+ Op: 2,
20
+ Op2: 3,
21
+ Val: 4,
22
+ 0: "L",
23
+ 1: "R",
24
+ 2: "Op",
25
+ 3: "Op2",
26
+ 4: "Val",
27
+ });
28
+
29
+ export const arenaColumns = Object.freeze([
30
+ "dataTypes",
31
+ "parents",
32
+ "nextSibling",
33
+ "previousSibling",
34
+ "firstToken",
35
+ "lastToken",
36
+ "firstChild",
37
+ "lastChild",
38
+ "name",
39
+ "stringValue",
40
+ "numericValue",
41
+ "unit",
42
+ "flags",
43
+ "colorType",
44
+ "spans",
45
+ ]);
46
+
47
+ export const numericTokenTypes = new Set([
48
+ EnumToken.NumberTokenType,
49
+ EnumToken.DimensionTokenType,
50
+ EnumToken.LengthTokenType,
51
+ EnumToken.AngleTokenType,
52
+ EnumToken.TimeTokenType,
53
+ EnumToken.FrequencyTokenType,
54
+ EnumToken.ResolutionTokenType,
55
+ EnumToken.PercentageTokenType,
56
+ EnumToken.FlexTokenType,
57
+ EnumToken.UserDefinedDimensionTokenType,
58
+ ]);
59
+
60
+ export const structuredTokenTypes = new Set([
61
+ EnumToken.BinaryExpressionTokenType,
62
+ EnumToken.MatchExpressionTokenType,
63
+ EnumToken.MediaQueryConditionTokenType,
64
+ EnumToken.MediaQueryUnaryFeatureTokenType,
65
+ EnumToken.SupportsQueryConditionTokenType,
66
+ EnumToken.SupportsQueryUnaryConditionTokenType,
67
+ EnumToken.WhenElseQueryConditionTokenType,
68
+ EnumToken.WhenElseUnaryConditionTokenType,
69
+ EnumToken.IfConditionTokenType,
70
+ EnumToken.IfElseConditionTokenType,
71
+ EnumToken.ContainerStyleRangeTokenType,
72
+ EnumToken.MediaRangeQueryTokenType,
73
+ EnumToken.ComposesSelectorNodeType,
74
+ EnumToken.NameSpaceAttributeTokenType,
75
+ ]);
76
+
77
+ const structuredFieldsCache = [];
78
+ const noFields = Object.freeze([]);
79
+
80
+ export function structuredFields(typ) {
81
+ let fields = structuredFieldsCache[typ];
82
+
83
+ if (fields != null) {
84
+ return fields;
85
+ }
86
+
87
+ if (!structuredTokenTypes.has(typ)) {
88
+ fields = noFields;
89
+ } else {
90
+ const single =
91
+ typ === EnumToken.BinaryExpressionTokenType ||
92
+ typ === EnumToken.IfElseConditionTokenType ||
93
+ typ === EnumToken.MatchExpressionTokenType ||
94
+ typ === EnumToken.NameSpaceAttributeTokenType;
95
+ const singleLeft =
96
+ single ||
97
+ typ === EnumToken.MediaQueryConditionTokenType ||
98
+ typ === EnumToken.MediaQueryUnaryFeatureTokenType ||
99
+ typ === EnumToken.SupportsQueryUnaryConditionTokenType ||
100
+ typ === EnumToken.WhenElseUnaryConditionTokenType;
101
+ const singleRight = single || typ === EnumToken.ComposesSelectorNodeType;
102
+
103
+ fields = [
104
+ ["l", TokenField.L, singleLeft],
105
+ ["r", TokenField.R, singleRight],
106
+ [typ === EnumToken.MediaRangeQueryTokenType ? "op1" : "op", TokenField.Op, typ !== EnumToken.ContainerStyleRangeTokenType],
107
+ ["op2", TokenField.Op2, true],
108
+ ["val", TokenField.Val, false],
109
+ ];
110
+ }
111
+
112
+ structuredFieldsCache[typ] = fields;
113
+ return fields;
114
+ }
115
+
116
+ // ---- arena registry ------------------------------------------------------------------------------------------------
117
+
118
+ /**
119
+ * state of an arena wrapper: rust handle, cached column views, javascript columns (transfer)
120
+ */
121
+ const states = new WeakMap();
122
+ // the wrappers by handle are `runtime.arenas`: an arena returned twice by rust is the same object
123
+ const registry = new FinalizationRegistry(({ runtime, handle }) => {
124
+ runtime.arenas.delete(handle);
125
+
126
+ try {
127
+ runtime.call("freeArena", handle);
128
+ } catch {}
129
+ });
130
+
131
+ let creating = null;
132
+
133
+ function register(arena, handle, runtime) {
134
+ states.set(arena, { handle, runtime, views: new Array(arenaColumns.length).fill(null), gen: null, genValue: -1, exported: null });
135
+ runtime.arenas.set(handle, new WeakRef(arena));
136
+ registry.register(arena, { runtime, handle });
137
+ }
138
+
139
+ function wrapArena(handle, runtime) {
140
+ const existing = runtime.arenas.get(handle)?.deref();
141
+
142
+ if (existing !== undefined) {
143
+ return existing;
144
+ }
145
+
146
+ if (creating !== null) {
147
+ const arena = creating;
148
+
149
+ creating = null;
150
+ register(arena, handle, runtime);
151
+ return arena;
152
+ }
153
+
154
+ const arena = Object.create(AstArena.prototype);
155
+
156
+ register(arena, handle, runtime);
157
+ return arena;
158
+ }
159
+
160
+ function state(arena) {
161
+ const st = states.get(arena);
162
+
163
+ if (st === undefined) {
164
+ throw new TypeError("not an arena");
165
+ }
166
+
167
+ return st;
168
+ }
169
+
170
+ function handleOf(arena, runtime) {
171
+ const st = state(arena);
172
+
173
+ if (runtime !== undefined && st.runtime !== runtime) {
174
+ throw new TypeError(`the arena belongs to the ${st.runtime.name} backend, it cannot be used by the ${runtime.name} backend`);
175
+ }
176
+
177
+ return st.handle;
178
+ }
179
+
180
+ /**
181
+ * a column view
182
+ */
183
+ function column(arena, index) {
184
+ const st = state(arena);
185
+
186
+ if (st.exported !== null) {
187
+ return st.exported[index];
188
+ }
189
+
190
+ const backend = st.runtime.backend;
191
+ let gen = st.gen;
192
+
193
+ if (gen === null || backend.stale(gen)) {
194
+ gen = st.gen = backend.generation(st.handle);
195
+ st.genValue = -1;
196
+ }
197
+
198
+ if (gen[0] !== st.genValue) {
199
+ st.views.fill(null);
200
+ st.genValue = gen[0];
201
+ }
202
+
203
+ let view = st.views[index];
204
+
205
+ if (view === null || backend.stale(view)) {
206
+ view = st.views[index] = backend.column(st.handle, index);
207
+ }
208
+
209
+ return view;
210
+ }
211
+
212
+ function isTransferred(st) {
213
+ return st.exported !== null && st.exported[0].buffer.byteLength === 0;
214
+ }
215
+
216
+ function currentGeneration(st) {
217
+ const backend = st.runtime.backend;
218
+
219
+ if (st.gen === null || backend.stale(st.gen)) {
220
+ st.gen = backend.generation(st.handle);
221
+ }
222
+
223
+ return st.gen[0];
224
+ }
225
+
226
+ function isExported(arena) {
227
+ return states.get(arena)?.exported != null;
228
+ }
229
+
230
+ /**
231
+ * copy the javascript columns into the rust arenas
232
+ */
233
+ function beforeCall(arenas) {
234
+ for (const arena of arenas) {
235
+ const st = state(arena);
236
+
237
+ if (isTransferred(st)) {
238
+ // the buffers were moved to another thread: the rust arena is no longer used
239
+ continue;
240
+ }
241
+
242
+ st.runtime.call("a.writeColumns", arena, st.exported.map((view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength)));
243
+ st.syncGen = currentGeneration(st);
244
+ }
245
+ }
246
+
247
+ /**
248
+ * copy the rust columns back into the javascript columns. the arena uses the rust memory again when it grew
249
+ */
250
+ function afterCall(arenas) {
251
+ for (const arena of arenas) {
252
+ const st = state(arena);
253
+
254
+ if (isTransferred(st)) {
255
+ continue;
256
+ }
257
+
258
+ if (currentGeneration(st) !== st.syncGen) {
259
+ st.exported = null;
260
+ st.views.fill(null);
261
+ st.genValue = -1;
262
+ continue;
263
+ }
264
+
265
+ for (let i = 0; i < arenaColumns.length; i++) {
266
+ const view = st.runtime.backend.column(st.handle, i);
267
+
268
+ if (view.length !== st.exported[i].length) {
269
+ st.exported = null;
270
+ st.views.fill(null);
271
+ st.genValue = -1;
272
+ break;
273
+ }
274
+
275
+ st.exported[i].set(view);
276
+ }
277
+ }
278
+ }
279
+
280
+ Object.assign(classes, {
281
+ AstArenaNode,
282
+ runtimeOf: (value) => states.get(value instanceof AstArenaNode ? value[ARENA] : value)?.runtime,
283
+ wrapArena,
284
+ handleOf,
285
+ isArena: (value) => states.has(value),
286
+ isExported,
287
+ beforeCall,
288
+ afterCall,
289
+ });
290
+
291
+ // ---- walkers -------------------------------------------------------------------------------------------------------
292
+
293
+ class Walker {
294
+ #handle;
295
+ #runtime;
296
+
297
+ constructor(handle, runtime) {
298
+ this.#handle = handle;
299
+ this.#runtime = runtime;
300
+ }
301
+
302
+ next() {
303
+ if (this.#handle === 0) {
304
+ return { done: true, value: undefined };
305
+ }
306
+
307
+ const value = this.#runtime.call("walkerNext", this.#handle);
308
+
309
+ if (value === null) {
310
+ this.#handle = 0;
311
+ return { done: true, value: undefined };
312
+ }
313
+
314
+ return { done: false, value };
315
+ }
316
+
317
+ return(value) {
318
+ if (this.#handle !== 0) {
319
+ this.#runtime.call("walkerFree", this.#handle);
320
+ this.#handle = 0;
321
+ }
322
+
323
+ return { done: true, value };
324
+ }
325
+
326
+ [Symbol.iterator]() {
327
+ return this;
328
+ }
329
+ }
330
+
331
+ // ---- arenas --------------------------------------------------------------------------------------------------------
332
+
333
+ const epochs = new Map();
334
+
335
+ function call(arena, method, ...args) {
336
+ return state(arena).runtime.call("a." + method, arena, ...args);
337
+ }
338
+
339
+ export class Arena {
340
+ constructor(size = 4096) {
341
+ creating = this;
342
+
343
+ try {
344
+ rt.call("newArena", size);
345
+ } finally {
346
+ creating = null;
347
+ }
348
+
349
+ }
350
+
351
+ get root() {
352
+ return 1;
353
+ }
354
+
355
+ get current() {
356
+ return call(this, "current");
357
+ }
358
+
359
+ get transferred() {
360
+ const st = state(this);
361
+ return isTransferred(st) || (st.exported === null && call(this, "transferred"));
362
+ }
363
+
364
+ get stringTable() {
365
+ const arena = this;
366
+
367
+ return {
368
+ get cache() {
369
+ return call(arena, "stringCache");
370
+ },
371
+ get count() {
372
+ return call(arena, "getStringCount");
373
+ },
374
+ };
375
+ }
376
+
377
+ get stringEpoch() {
378
+ const epoch = call(this, "stringEpoch");
379
+ let object = epochs.get(epoch);
380
+
381
+ if (object === undefined) {
382
+ object = {};
383
+ epochs.set(epoch, object);
384
+ }
385
+
386
+ return object;
387
+ }
388
+
389
+ get errors() {
390
+ return new Map(call(this, "errors"));
391
+ }
392
+
393
+ static toTransferableArenaObject(arena) {
394
+ const st = state(arena);
395
+ const properties = call(arena, "exportProperties", arena instanceof AstArena);
396
+ const views = arenaColumns.map((_, i) => column(arena, i).slice());
397
+
398
+ st.exported = views;
399
+ st.syncGen = currentGeneration(st);
400
+
401
+ return [properties, views.map((view) => view.buffer)];
402
+ }
403
+
404
+ static fromTransferableArenaObjects(properties, transferables) {
405
+ creating = Object.create(this.prototype);
406
+
407
+ let arena;
408
+
409
+ try {
410
+ arena = rt.call("arenaFromTransferables", properties, transferables.map((buffer) => new Uint8Array(buffer)));
411
+ } finally {
412
+ creating = null;
413
+ }
414
+
415
+ const st = state(arena);
416
+
417
+ st.exported = transferables.map((buffer, i) => new columnTypes[i](buffer));
418
+ st.syncGen = currentGeneration(st);
419
+ return arena;
420
+ }
421
+
422
+ // -- columns
423
+
424
+ getType(id) {
425
+ return this.dataTypes[id];
426
+ }
427
+
428
+ typeOf(id) {
429
+ return id == null ? null : this.dataTypes[id];
430
+ }
431
+
432
+ setType(id, type) {
433
+ this.dataTypes[id] = type;
434
+ }
435
+
436
+ setName(id, nameId) {
437
+ this.name[id] = nameId;
438
+ }
439
+
440
+ setValue(id, valueId) {
441
+ this.stringValue[id] = valueId;
442
+ }
443
+
444
+ setNumericValue(id, numericValue) {
445
+ this.numericValue[id] = numericValue;
446
+ }
447
+
448
+ setUnit(id, unit) {
449
+ this.unit[id] = unit;
450
+ }
451
+
452
+ getNumericValue(id) {
453
+ return this.numericValue[id];
454
+ }
455
+
456
+ setParent(id, parentId) {
457
+ this.parents[id] = parentId;
458
+ }
459
+
460
+ getParent(id) {
461
+ return this.parents[id];
462
+ }
463
+
464
+ getFirstChild(id) {
465
+ return this.firstChild[id];
466
+ }
467
+
468
+ getLastChild(id) {
469
+ return this.lastChild[id];
470
+ }
471
+
472
+ getNextSibling(id) {
473
+ return this.nextSibling[id];
474
+ }
475
+
476
+ getPreviousSibling(id) {
477
+ return this.previousSibling[id];
478
+ }
479
+
480
+ getFirstToken(id) {
481
+ return this.firstToken[id];
482
+ }
483
+
484
+ getLastToken(id) {
485
+ return this.lastToken[id];
486
+ }
487
+
488
+ setColorType(id, colorType) {
489
+ this.colorType[id] = colorType;
490
+ }
491
+
492
+ getColorType(id) {
493
+ return this.colorType[id];
494
+ }
495
+
496
+ setFlags(id, flags) {
497
+ this.flags[id] = flags;
498
+ }
499
+
500
+ getFlags(id) {
501
+ return this.flags[id];
502
+ }
503
+
504
+ hasFlags(id, flag) {
505
+ return (this.flags[id] & flag) === flag;
506
+ }
507
+
508
+ getCapacity() {
509
+ return this.dataTypes.length;
510
+ }
511
+
512
+ getLastId() {
513
+ return this.current;
514
+ }
515
+
516
+ // -- strings
517
+
518
+ internRange(codes, start, end, source) {
519
+ if (typeof codes === "string") {
520
+ return call(this, "internRange", codes, start, end, source, false);
521
+ }
522
+
523
+ return call(this, "internRange", new Uint8Array(codes.buffer, codes.byteOffset, codes.byteLength), start, end, source, codes.BYTES_PER_ELEMENT === 2);
524
+ }
525
+
526
+ setSourceText(source, text, codes = null) {
527
+ if (codes == null) {
528
+ return call(this, "setSourceText", source, text);
529
+ }
530
+
531
+ return call(this, "setSourceText", source, text, new Uint8Array(codes.buffer, codes.byteOffset, codes.byteLength), codes.BYTES_PER_ELEMENT === 2);
532
+ }
533
+
534
+ copyStringAscii(id, target, offset) {
535
+ const bytes = call(this, "copyStringAscii", id);
536
+
537
+ if (typeof bytes === "number") {
538
+ return bytes;
539
+ }
540
+
541
+ target.set(bytes, offset);
542
+ return bytes.length;
543
+ }
544
+
545
+ appendString(builder, id) {
546
+ return builder.appendString(call(this, "stringText", id));
547
+ }
548
+
549
+ internBuilder(builder) {
550
+ return this.internString(builder.toString());
551
+ }
552
+
553
+ // -- walkers
554
+
555
+ walk(node, filter, reverse) {
556
+ return new Walker(call(this, "walk", node, filter, reverse), state(this).runtime);
557
+ }
558
+
559
+ walkValues(tokens, filter, reverse) {
560
+ return new Walker(call(this, "walkValues", tokens, filter, reverse), state(this).runtime);
561
+ }
562
+
563
+ compact(errors) {
564
+ return Uint32Array.from(call(this, "compact", errors));
565
+ }
566
+
567
+ trim(errors) {
568
+ return Uint32Array.from(call(this, "trim", errors));
569
+ }
570
+ }
571
+
572
+ for (let i = 0; i < arenaColumns.length; i++) {
573
+ Object.defineProperty(Arena.prototype, arenaColumns[i], {
574
+ configurable: true,
575
+ get() {
576
+ return column(this, i);
577
+ },
578
+ });
579
+ }
580
+
581
+ // the methods implemented by rust
582
+ for (const method of [
583
+ "allocate",
584
+ "recycle",
585
+ "internString",
586
+ "stringId",
587
+ "stringLength",
588
+ "stringCodeAt",
589
+ "stringIndexOf",
590
+ "stringEquals",
591
+ "stringEqualsIgnoreCase",
592
+ "stringStartsWith",
593
+ "lowerStringId",
594
+ "stringFlag",
595
+ "releaseSourceCodes",
596
+ "getName",
597
+ "getValue",
598
+ "getUnit",
599
+ "getStringCount",
600
+ "setFirstChild",
601
+ "setLastChild",
602
+ "setNextSibling",
603
+ "setPreviousSibling",
604
+ "setFirstToken",
605
+ "getChildAt",
606
+ "getTokenAt",
607
+ "setChildAt",
608
+ "fieldList",
609
+ "hasField",
610
+ "field",
611
+ "fieldTokens",
612
+ "setField",
613
+ "appendField",
614
+ "setLeft",
615
+ "getLeft",
616
+ "setRight",
617
+ "getRight",
618
+ "setOp",
619
+ "getOp",
620
+ "setSpan",
621
+ "copySpan",
622
+ "getSourceId",
623
+ "getSpanStart",
624
+ "getSpanEnd",
625
+ "setSpanEnd",
626
+ "resolveString",
627
+ "detach",
628
+ "getValueParent",
629
+ "getValueOwner",
630
+ "find",
631
+ "findAll",
632
+ "findLast",
633
+ "findByValue",
634
+ "findValue",
635
+ "subTokens",
636
+ "findChild",
637
+ "findToken",
638
+ "siblings",
639
+ "children",
640
+ "tokens",
641
+ "tokenCount",
642
+ "setChildren",
643
+ "setChildList",
644
+ "setTokens",
645
+ "setTokenList",
646
+ "moveChildren",
647
+ "appendChildren",
648
+ "appendChildList",
649
+ "appendTokens",
650
+ "appendTokenList",
651
+ "appendChild",
652
+ "appendToken",
653
+ "prependTokens",
654
+ "equalsIgnoreCase",
655
+ "startsWith",
656
+ "resize",
657
+ "compactStrings",
658
+ "mark",
659
+ "isMarked",
660
+ "release",
661
+ "getErrors",
662
+ "childCount",
663
+ ]) {
664
+ Arena.prototype[method] = function (...args) {
665
+ return call(this, method, ...args);
666
+ };
667
+ }
668
+
669
+ export class AstArena extends Arena {
670
+ get inputLengths() {
671
+ return call(this, "inputLengths");
672
+ }
673
+
674
+ toObject(id) {
675
+ return new AstArenaNode(this, id);
676
+ }
677
+
678
+ import(source, id, deep = true) {
679
+ return call(this, "import", source, id, deep);
680
+ }
681
+ }
682
+
683
+ for (const method of [
684
+ "getState",
685
+ "setState",
686
+ "isInvalid",
687
+ "sourceIndex",
688
+ "setLocation",
689
+ "setTokenLocation",
690
+ "copyLocation",
691
+ "spanLocation",
692
+ "hasLocation",
693
+ "getLocation",
694
+ "getSource",
695
+ "createStyleSheet",
696
+ "createRule",
697
+ "createAtRule",
698
+ "createDeclaration",
699
+ "createComment",
700
+ "createToken",
701
+ "createColor",
702
+ "createFunction",
703
+ "createList",
704
+ "createBinaryExpression",
705
+ "createFraction",
706
+ "hasFraction",
707
+ "getFraction",
708
+ "setFraction",
709
+ "numerator",
710
+ "denominator",
711
+ "str",
712
+ "setStr",
713
+ "setUnitString",
714
+ "isNumeric",
715
+ "replaceToken",
716
+ "take",
717
+ "copyToken",
718
+ "resetToken",
719
+ "fromObject",
720
+ "toPlainObject",
721
+ "tokenToObject",
722
+ "cloneNode",
723
+ "clone",
724
+ "indexOf",
725
+ "insertBefore",
726
+ "insertAfter",
727
+ "prependChildren",
728
+ "replaceChild",
729
+ "hasChildren",
730
+ "getSelector",
731
+ "setSelector",
732
+ "setNameString",
733
+ "setValueString",
734
+ "expand",
735
+ "replaceCompound",
736
+ ]) {
737
+ AstArena.prototype[method] = function (...args) {
738
+ return call(this, method, ...args);
739
+ };
740
+ }
741
+
742
+ export { ARENA, ARENAID };