json-as 1.0.0-beta.9 → 1.0.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 (39) hide show
  1. package/{CHANGELOG → CHANGELOG.md} +41 -0
  2. package/README.md +102 -96
  3. package/assembly/__tests__/array.spec.ts +42 -0
  4. package/assembly/__tests__/float.spec.ts +3 -3
  5. package/assembly/__tests__/map.spec.ts +7 -0
  6. package/assembly/__tests__/raw.spec.ts +4 -5
  7. package/assembly/__tests__/struct.spec.ts +2 -2
  8. package/assembly/deserialize/simple/arbitrary.ts +8 -4
  9. package/assembly/deserialize/simple/array/arbitrary.ts +6 -6
  10. package/assembly/deserialize/simple/array/array.ts +4 -3
  11. package/assembly/deserialize/simple/array/bool.ts +7 -7
  12. package/assembly/deserialize/simple/array/float.ts +2 -2
  13. package/assembly/deserialize/simple/array/integer.ts +1 -1
  14. package/assembly/deserialize/simple/array/map.ts +1 -1
  15. package/assembly/deserialize/simple/array/string.ts +3 -3
  16. package/assembly/deserialize/simple/array/struct.ts +14 -3
  17. package/assembly/deserialize/simple/array.ts +3 -0
  18. package/assembly/deserialize/simple/map.ts +93 -75
  19. package/assembly/deserialize/simple/object.ts +26 -16
  20. package/assembly/deserialize/simple/struct.ts +31 -19
  21. package/assembly/index.ts +14 -11
  22. package/assembly/serialize/simple/array.ts +1 -0
  23. package/assembly/serialize/simple/bool.ts +1 -0
  24. package/assembly/serialize/simple/date.ts +1 -0
  25. package/assembly/serialize/simple/float.ts +1 -0
  26. package/assembly/serialize/simple/integer.ts +1 -0
  27. package/assembly/serialize/simple/map.ts +1 -0
  28. package/assembly/serialize/simple/object.ts +1 -0
  29. package/assembly/serialize/simple/raw.ts +1 -0
  30. package/assembly/serialize/simple/string.ts +1 -0
  31. package/assembly/test.ts +18 -0
  32. package/index.ts +1 -1
  33. package/package.json +4 -3
  34. package/run-tests.sh +1 -1
  35. package/transform/lib/index.js +29 -69
  36. package/transform/lib/index.js.map +1 -1
  37. package/transform/src/index.ts +55 -71
  38. package/.gitmodules +0 -0
  39. package/assembly/as-bs.d.ts +0 -53
@@ -1,4 +1,4 @@
1
- import { ClassDeclaration, FieldDeclaration, IdentifierExpression, Parser, Source, NodeKind, CommonFlags, ImportStatement, Node, Tokenizer, SourceKind, NamedTypeNode, Range, FEATURE_SIMD, FunctionExpression, MethodDeclaration } from "assemblyscript/dist/assemblyscript.js";
1
+ import { ClassDeclaration, FieldDeclaration, IdentifierExpression, Parser, Source, NodeKind, CommonFlags, ImportStatement, Node, Tokenizer, SourceKind, NamedTypeNode, Range, FEATURE_SIMD, FunctionExpression, MethodDeclaration, Statement } from "assemblyscript/dist/assemblyscript.js";
2
2
  import { Transform } from "assemblyscript/dist/transform.js";
3
3
  import { Visitor } from "./visitor.js";
4
4
  import { SimpleParser, toString } from "./util.js";
@@ -16,11 +16,7 @@ class JSONTransform extends Visitor {
16
16
  public sources = new Set<Source>();
17
17
  public imports: ImportStatement[] = [];
18
18
 
19
- public jsonImport: string | null = null;
20
- public bsImport: string | null = null;
21
- public newStmts: {
22
- simd: string[];
23
- } = { simd: [] };
19
+ public topStatements: Statement[] = [];
24
20
 
25
21
  visitClassDeclaration(node: ClassDeclaration): void {
26
22
  if (!node.decorators?.length) return;
@@ -352,7 +348,7 @@ class JSONTransform extends Visitor {
352
348
  if (memberLen == 2) DESERIALIZE += `${indent}switch (load<u16>(keyStart)) {\n`;
353
349
  else if (memberLen == 4) DESERIALIZE += `${indent}switch (load<u32>(keyStart)) {\n`;
354
350
  else if (memberLen == 6) DESERIALIZE += `${indent}let code = load<u64>(keyStart) & 0x0000FFFFFFFFFFFF;\n`;
355
- else if (memberLen == 6) DESERIALIZE += `${indent}let code = load<u64>(keyStart);\n`;
351
+ else if (memberLen == 8) DESERIALIZE += `${indent}let code = load<u64>(keyStart);\n`;
356
352
  else DESERIALIZE += toMemCDecl(memberLen, indent);
357
353
  for (let i = 0; i < memberGroup.length; i++) {
358
354
  const member = memberGroup[i];
@@ -474,8 +470,6 @@ class JSONTransform extends Visitor {
474
470
  // }
475
471
  visitImportStatement(node: ImportStatement): void {
476
472
  super.visitImportStatement(node);
477
- const source = this.parser.sources.find((src) => src.internalPath == node.internalPath);
478
- if (!source) return;
479
473
  this.imports.push(node);
480
474
  }
481
475
  visitSource(node: Source): void {
@@ -483,37 +477,50 @@ class JSONTransform extends Visitor {
483
477
  super.visitSource(node);
484
478
  }
485
479
  addRequiredImports(node: Source): void {
486
- const bsImport = this.imports.find((i) => i.declarations.find((d) => d.foreignName.text == "bs"));
487
- if (bsImport) {
488
- const txt = `import { bs } from "as-bs";`;
489
- if (!this.bsImport) {
490
- this.bsImport = txt;
491
- if (process.env["JSON_DEBUG"]) console.log("Added as-bs import: " + txt + "\n");
492
- }
493
- } else {
494
- const txt = `import { bs } from "as-bs";`;
495
- if (!this.bsImport) {
496
- this.bsImport = txt;
497
- if (process.env["JSON_DEBUG"]) console.log("Added as-bs import: " + txt + "\n");
498
- }
499
- }
480
+ const filePath = fileURLToPath(import.meta.url);
481
+ const fileDir = path.dirname(filePath);
500
482
 
501
- if (!this.imports.find((i) => i.declarations.find((d) => d.foreignName.text == "JSON"))) {
502
- const __filename = fileURLToPath(import.meta.url);
503
- const __dirname = path.dirname(__filename);
483
+ const bsImport = this.imports.find((i) => i.declarations?.find((d) => d.foreignName.text == "bs" || d.name.text == "bs"));
484
+ const jsonImport = this.imports.find((i) => i.declarations?.find((d) => d.foreignName.text == "JSON" || d.name.text == "JSON"));
504
485
 
505
- let relativePath = path.relative(path.dirname(node.range.source.normalizedPath), path.resolve(__dirname, "../../assembly/index.ts"));
486
+ let pkgRel = path.relative(
487
+ path.dirname(node.range.source.normalizedPath),
488
+ path.resolve(fileDir, "../../")
489
+ );
506
490
 
507
- if (!relativePath.startsWith(".") && !relativePath.startsWith("/")) relativePath = "./" + relativePath;
508
- // if (!existsSync(relativePath)) {
509
- // throw new Error("Could not find a valid json-as library to import from! Please add import { JSON } from \"path-to-json-as\"; in " + node.range.source.normalizedPath + "!");
510
- // }
491
+ if (!pkgRel.startsWith(".") && !pkgRel.startsWith("/")) pkgRel = "./" + pkgRel;
492
+ pkgRel = pkgRel.replace(/^.*json-as/, "json-as");
511
493
 
512
- const txt = `import { JSON } from "${relativePath}";`;
513
- if (!this.jsonImport) {
514
- this.jsonImport = txt;
515
- if (process.env["JSON_DEBUG"]) console.log("Added json-as import: " + txt + "\n");
516
- }
494
+ if (!bsImport) {
495
+ const replaceNode = Node.createImportStatement(
496
+ [
497
+ Node.createImportDeclaration(
498
+ Node.createIdentifierExpression("bs", node.range, false),
499
+ null,
500
+ node.range
501
+ )
502
+ ],
503
+ Node.createStringLiteralExpression(path.join(pkgRel, "./lib/as-bs"), node.range),
504
+ node.range
505
+ );
506
+ this.topStatements.push(replaceNode);
507
+ if (process.env["JSON_DEBUG"]) console.log("Added as-bs import: " + toString(replaceNode) + "\n");
508
+ }
509
+
510
+ if (!jsonImport) {
511
+ const replaceNode = Node.createImportStatement(
512
+ [
513
+ Node.createImportDeclaration(
514
+ Node.createIdentifierExpression("JSON", node.range, false),
515
+ null,
516
+ node.range
517
+ )
518
+ ],
519
+ Node.createStringLiteralExpression(path.join(pkgRel, "./assembly"), node.range),
520
+ node.range
521
+ );
522
+ this.topStatements.push(replaceNode);
523
+ if (process.env["JSON_DEBUG"]) console.log("Added json-as import: " + toString(replaceNode) + "\n");
517
524
  }
518
525
  }
519
526
 
@@ -522,14 +529,14 @@ class JSONTransform extends Visitor {
522
529
  const sizes = strToNum(data, simd);
523
530
  let offset = 0;
524
531
  for (const [size, num] of sizes) {
525
- if (size == "v128") {
526
- // This could be put in its own file
527
- let index = this.newStmts.simd.findIndex((v) => v.includes(num));
528
- let name = "SIMD_" + (index == -1 ? this.newStmts.simd.length : index);
529
- if (index && !this.newStmts.simd.includes(`const ${name} = ${num};`)) this.newStmts.simd.push(`const ${name} = ${num};`);
530
- out.push("store<v128>(bs.offset, " + name + ", " + offset + "); // " + data.slice(offset >> 1, (offset >> 1) + 8));
531
- offset += 16;
532
- }
532
+ // if (size == "v128") {
533
+ // // This could be put in its own file
534
+ // let index = this.newStmts.simd.findIndex((v) => v.includes(num));
535
+ // let name = "SIMD_" + (index == -1 ? this.newStmts.simd.length : index);
536
+ // if (index && !this.newStmts.simd.includes(`const ${name} = ${num};`)) this.newStmts.simd.push(`const ${name} = ${num};`);
537
+ // out.push("store<v128>(bs.offset, " + name + ", " + offset + "); // " + data.slice(offset >> 1, (offset >> 1) + 8));
538
+ // offset += 16;
539
+ // }
533
540
  if (size == "u64") {
534
541
  out.push("store<u64>(bs.offset, " + num + ", " + offset + "); // " + data.slice(offset >> 1, (offset >> 1) + 4));
535
542
  offset += 8;
@@ -616,28 +623,9 @@ export default class Transformer extends Transform {
616
623
  // Ignore all lib and std. Visit everything else.
617
624
  transformer.visit(source);
618
625
 
619
- if (transformer.newStmts.simd) {
620
- const tokenizer = new Tokenizer(new Source(SourceKind.User, source.normalizedPath, transformer.newStmts.simd.join("\n")));
621
- parser.currentSource = tokenizer.source;
622
- for (let i = 0; i < transformer.newStmts.simd.length; i++) source.statements.unshift(parser.parseTopLevelStatement(tokenizer)!);
623
- parser.currentSource = source;
624
- transformer.newStmts.simd = [];
625
- }
626
-
627
- if (transformer.jsonImport) {
628
- const tokenizer = new Tokenizer(new Source(SourceKind.User, source.normalizedPath, transformer.jsonImport));
629
- parser.currentSource = tokenizer.source;
630
- source.statements.unshift(parser.parseTopLevelStatement(tokenizer)!);
631
- parser.currentSource = source;
632
- transformer.jsonImport = null;
633
- }
634
-
635
- if (transformer.bsImport) {
636
- const tokenizer = new Tokenizer(new Source(SourceKind.User, source.normalizedPath, transformer.bsImport));
637
- parser.currentSource = tokenizer.source;
638
- source.statements.unshift(parser.parseTopLevelStatement(tokenizer)!);
639
- parser.currentSource = source;
640
- transformer.bsImport = null;
626
+ if (transformer.topStatements.length) {
627
+ source.statements.unshift(...transformer.topStatements);
628
+ transformer.topStatements = [];
641
629
  }
642
630
  }
643
631
  // Check that every parent and child class is hooked up correctly
@@ -760,7 +748,7 @@ function strToNum(data: string, simd: boolean = false, offset: number = 0): stri
760
748
 
761
749
  function isPrimitive(type: string): boolean {
762
750
  const primitiveTypes = ["u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64", "f32", "f64", "bool", "boolean"];
763
- return primitiveTypes.some((v) => type.includes(v));
751
+ return primitiveTypes.some((v) => type.startsWith(v));
764
752
  }
765
753
 
766
754
  function throwError(message: string, range: Range): never {
@@ -797,7 +785,3 @@ function sizeof(type: string): number {
797
785
  else if (type == "bool" || type == "boolean") return 10;
798
786
  else return 0;
799
787
  }
800
-
801
- function allPrimitive(schema: Schema): boolean {
802
- return !schema.members.some((p) => p.byteSize == 0);
803
- }
package/.gitmodules DELETED
File without changes
@@ -1,53 +0,0 @@
1
- /**
2
- * Central buffer namespace for managing memory operations.
3
- */
4
- declare namespace bs {
5
- /** Current buffer pointer. */
6
- export let buffer: ArrayBuffer;
7
-
8
- /** Current offset within the buffer. */
9
- export let offset: usize;
10
-
11
- /** Proposed size of output. */
12
- export let stackSize: usize;
13
-
14
- /**
15
- * Ensures the buffer size is at least the proposed size.
16
- * If necessary, reallocates the buffer to the exact new size.
17
- * @param size - The size to propose.
18
- */
19
- export function ensureSize(size: u32): void;
20
-
21
- /**
22
- * Proposes that the buffer size should be at least the given size.
23
- * If necessary, reallocates the buffer to the exact new size.
24
- * @param size - The size to propose.
25
- */
26
- export function proposeSize(size: u32): void;
27
-
28
- /**
29
- * Increases the proposed size by nextPowerOf2(n + 64) if necessary.
30
- * If necessary, reallocates the buffer to the exact new size.
31
- * @param size - The size to grow by.
32
- */
33
- export function growSize(size: u32): void;
34
-
35
- /**
36
- * Resizes the buffer to the specified size.
37
- * @param newSize - The new buffer size.
38
- */
39
- export function resize(newSize: u32): void;
40
-
41
- /**
42
- * Copies the buffer's content to a new object of a specified type.
43
- * @returns The new object containing the buffer's content.
44
- */
45
- export function out<T>(): T;
46
-
47
- /**
48
- * Copies the buffer's content to a given destination pointer.
49
- * @param dst - The destination pointer.
50
- * @returns The destination pointer cast to the specified type.
51
- */
52
- export function outTo<T>(dst: usize): T;
53
- }