mirror of
https://github.com/fluencelabs/assemblyscript-json
synced 2025-04-24 22:32:20 +00:00
Update AS syntax
This commit is contained in:
parent
843f5eb9e4
commit
029af648b5
73
as-pect.config.js
Normal file
73
as-pect.config.js
Normal file
@ -0,0 +1,73 @@
|
||||
module.exports = {
|
||||
/**
|
||||
* A set of globs passed to the glob package that qualify typescript files for testing.
|
||||
*/
|
||||
include: ["assembly/__tests__/**/*.spec.ts"],
|
||||
/**
|
||||
* A set of globs passed to the glob package that quality files to be added to each test.
|
||||
*/
|
||||
add: ["assembly/__tests__/**/*.include.ts"],
|
||||
/**
|
||||
* All the compiler flags needed for this test suite. Make sure that a binary file is output.
|
||||
*/
|
||||
flags: {
|
||||
"--validate": [],
|
||||
"--debug": [],
|
||||
/** This is required. Do not change this. The filename is ignored, but required by the compiler. */
|
||||
"--binaryFile": ["output.wasm"],
|
||||
/** To enable wat file output, use the following flag. The filename is ignored, but required by the compiler. */
|
||||
// "--textFile": ["output.wat"],
|
||||
/** To select an appropriate runtime, use the --runtime compiler flag. */
|
||||
"--runtime": ["stub"] // Acceptable values are: full, half, stub (arena), and none
|
||||
},
|
||||
/**
|
||||
* A set of regexp that will disclude source files from testing.
|
||||
*/
|
||||
disclude: [/node_modules/],
|
||||
/**
|
||||
* Add your required AssemblyScript imports here.
|
||||
*/
|
||||
imports: {},
|
||||
/**
|
||||
* All performance statistics reporting can be configured here.
|
||||
*/
|
||||
performance: {
|
||||
/** Enable performance statistics gathering for every test. */
|
||||
enabled: false,
|
||||
/** Set the maximum number of samples to run for every test. */
|
||||
maxSamples: 10000,
|
||||
/** Set the maximum test run time in milliseconds for every test. */
|
||||
maxTestRunTime: 2000,
|
||||
/** Report the median time in the default reporter for every test. */
|
||||
reportMedian: true,
|
||||
/** Report the average time in milliseconds for every test. */
|
||||
reportAverage: true,
|
||||
/** Report the standard deviation for every test. */
|
||||
reportStandardDeviation: false,
|
||||
/** Report the maximum run time in milliseconds for every test. */
|
||||
reportMax: false,
|
||||
/** Report the minimum run time in milliseconds for every test. */
|
||||
reportMin: false,
|
||||
},
|
||||
/**
|
||||
* Add a custom reporter here if you want one. The following example is in typescript.
|
||||
*
|
||||
* @example
|
||||
* import { TestReporter, TestGroup, TestResult, TestContext } from "as-pect";
|
||||
*
|
||||
* export class CustomReporter extends TestReporter {
|
||||
* // implement each abstract method here
|
||||
* public abstract onStart(suite: TestContext): void;
|
||||
* public abstract onGroupStart(group: TestGroup): void;
|
||||
* public abstract onGroupFinish(group: TestGroup): void;
|
||||
* public abstract onTestStart(group: TestGroup, result: TestResult): void;
|
||||
* public abstract onTestFinish(group: TestGroup, result: TestResult): void;
|
||||
* public abstract onFinish(suite: TestContext): void;
|
||||
* }
|
||||
*/
|
||||
// reporter: new CustomReporter(),
|
||||
/**
|
||||
* Specify if the binary wasm file should be written to the file system.
|
||||
*/
|
||||
outputBinary: false,
|
||||
};
|
641
assembly/__tests__/as-pect.d.ts
vendored
Normal file
641
assembly/__tests__/as-pect.d.ts
vendored
Normal file
@ -0,0 +1,641 @@
|
||||
/**
|
||||
* This function creates a test group in the test loader.
|
||||
*
|
||||
* @param {string} description - This is the name of the test group.
|
||||
* @param {() => void} callback - A function that contains all of the closures for this test group.
|
||||
*
|
||||
* @example
|
||||
* describe("my test suite", (): void => {
|
||||
* // put your tests here
|
||||
* });
|
||||
*/
|
||||
declare function describe(description: string, callback: () => void): void;
|
||||
|
||||
/**
|
||||
* This function creates a test inside the given test group. It must be placed inside a describe
|
||||
* block.
|
||||
*
|
||||
* @param {string} description - This is the name of the test, and should describe a behavior.
|
||||
* @param {() => void} callback - A function that contains a set of expectations for this test.
|
||||
*
|
||||
* @example
|
||||
* describe("the meaning of life", (): void => {
|
||||
* it("should be 42", (): void => {
|
||||
* // put your expectations here
|
||||
* expect<i32>(29 + 13).toBe(42);
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
declare function it(description: string, callback: () => void): void;
|
||||
|
||||
/**
|
||||
* A test that does not run, and is longhand equivalent to using todo function without a
|
||||
* callback. This test does not get run and is reported like a todo.
|
||||
*
|
||||
* @param {string} description - This is the name of the test, and should describe a behavior.
|
||||
* @param {() => void} callback - A function that contains a set of expectations for this test.
|
||||
*/
|
||||
declare function xit(description: string, callback: () => void): void;
|
||||
|
||||
/**
|
||||
* A test that does not run, and is longhand equivalent to using todo function without a
|
||||
* callback. This test does not get run and is reported like a todo.
|
||||
*
|
||||
* @param {string} description - This is the name of the test, and should describe a behavior.
|
||||
* @param {() => void} callback - A function that contains a set of expectations for this test.
|
||||
*/
|
||||
declare function xtest(description: string, callback: () => void): void;
|
||||
|
||||
/**
|
||||
* This function creates a test inside the given test group. It must be placed inside a describe
|
||||
* block.
|
||||
*
|
||||
* @param {string} description - This is the name of the test, and should describe a behavior.
|
||||
* @param {() => void} callback - A function that contains a set of expectations for this test.
|
||||
*
|
||||
* @example
|
||||
* describe("the meaning of life", (): void => {
|
||||
* test("the value should be 42", (): void => {
|
||||
* // put your expectations here
|
||||
* expect<i32>(29 + 13).toBe(42);
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
declare function test(description: string, callback: () => void): void;
|
||||
|
||||
/**
|
||||
* This function creates a test that is expected to fail. This is useful to verify if a given
|
||||
* behavior is expected to throw.
|
||||
*
|
||||
* @param {string} description - This is the name of the test, and should describe a behavior.
|
||||
* @param {() => void} callback - A function that contains a set of expectations for this test.
|
||||
* @param {string?} message - A message that describes why the test should fail.
|
||||
* @example
|
||||
* describe("the meaning of life", (): void => {
|
||||
* throws("the value should be 42", (): void => {
|
||||
* // put your expectations here
|
||||
* expect<i32>(29 + 13).toBe(42);
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
declare function throws(description: string, callback: () => void, message?: string): void;
|
||||
|
||||
|
||||
/**
|
||||
* This function creates a test that is expected to fail. This is useful to verify if a given
|
||||
* behavior is expected to throw.
|
||||
*
|
||||
* @param {string} description - This is the name of the test, and should describe a behavior.
|
||||
* @param {() => void} callback - A function that contains a set of expectations for this test.
|
||||
* @param {string?} message - A message that describes why the test should fail.
|
||||
* @example
|
||||
* describe("the meaning of life", (): void => {
|
||||
* itThrows("when the value should be 42", (): void => {
|
||||
* // put your expectations here
|
||||
* expect<i32>(29 + 13).not.toBe(42);
|
||||
* }, "The value is actually 42.");
|
||||
* });
|
||||
*/
|
||||
declare function itThrows(description: string, callback: () => void, message?: string): void;
|
||||
|
||||
/**
|
||||
* This function creates a callback that is called before each individual test is run in this test
|
||||
* group.
|
||||
*
|
||||
* @param {function} callback - The function to be run before each test in the current test group.
|
||||
*
|
||||
* @example
|
||||
* // create a global
|
||||
* var cat: Cat = new Cat();
|
||||
*
|
||||
* describe("cats", (): void => {
|
||||
* beforeEach((): void => {
|
||||
* cat.meow(1); // meow once per test
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
declare function beforeEach(callback: () => void): void;
|
||||
|
||||
/**
|
||||
* This function creates a callback that is called before the whole test group is run, and only
|
||||
* once.
|
||||
*
|
||||
* @param {function} callback - The function to be run before each test in the current test group.
|
||||
*
|
||||
* @example
|
||||
* // create a global
|
||||
* var dog: Dog = null;
|
||||
* describe("dogs", (): void => {
|
||||
* beforeAll((): void => {
|
||||
* dog = new Dog(); // create a single dog once before the tests start
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
declare function beforeAll(callback: () => void): void;
|
||||
|
||||
/**
|
||||
* This function creates a callback that is called after each individual test is run in this test
|
||||
* group.
|
||||
*
|
||||
* @param {function} callback - The function to be run after each test in the current test group.
|
||||
*
|
||||
* @example
|
||||
* // create a global
|
||||
* var cat: Cat = new Cat();
|
||||
*
|
||||
* describe("cats", (): void => {
|
||||
* afterEach((): void => {
|
||||
* cat.sleep(12); // cats sleep a lot
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
declare function afterEach(callback: () => void): void;
|
||||
|
||||
/**
|
||||
* This function creates a callback that is called after the whole test group is run, and only
|
||||
* once.
|
||||
*
|
||||
* @param {function} callback - The function to be run after each test in the current test group.
|
||||
*
|
||||
* @example
|
||||
* // create a global
|
||||
* var dog: Dog = null;
|
||||
* describe("dogs", (): void => {
|
||||
* afterAll((): void => {
|
||||
* memory.free(changetype<usize>(dog)); // free some memory
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
declare function afterAll(callback: () => void): void;
|
||||
|
||||
/**
|
||||
* Describes a value and returns an expectation to test the value.
|
||||
*
|
||||
* @type {T} - The test's type
|
||||
* @param {T} actual - The value being tested.
|
||||
*
|
||||
* @example
|
||||
* expect<i32>(42).not.toBe(-1, "42 should not be -1");
|
||||
* expect<i32>(19 + 23).toBe(42, "19 + 23 should equal 42");
|
||||
*/
|
||||
declare function expect<T>(actual: T | null): Expectation<T>;
|
||||
|
||||
/**
|
||||
* Describes a function and returns an expectation to test the function.
|
||||
*
|
||||
* @param {() => void} callback - The callback being tested.
|
||||
*
|
||||
* @example
|
||||
* expectFn((): void => unreachable()).toThrow("unreachables do not throw");
|
||||
* expectFn((): void => {
|
||||
* cat.meow();
|
||||
* }).not.toThrow("Uhoh, cats can't meow!");;
|
||||
*/
|
||||
declare function expectFn(cb: () => void): Expectation<() => void>;
|
||||
|
||||
/**
|
||||
* Describes a test that needs to be written.
|
||||
*
|
||||
* @param {string} description - The description of the test that needs to be written.
|
||||
*/
|
||||
declare function todo(description: string): void;
|
||||
|
||||
/**
|
||||
* Logs a single value to the logger, and is stringified. It works for references, values, and
|
||||
* strings.
|
||||
*
|
||||
* @type {T} - The type to be logged.
|
||||
* @param {T | null} value - The value to be logged.
|
||||
* @example
|
||||
* log<string>("This is a logged value.");
|
||||
* log<i32>(42);
|
||||
* log<Vec3>(new Vec(1, 2, 3));
|
||||
* log<Vec3>(null);
|
||||
*/
|
||||
declare function log<T>(value: T | null): void;
|
||||
|
||||
/**
|
||||
* An expectation for a value.
|
||||
*/
|
||||
declare class Expectation<T> {
|
||||
|
||||
/**
|
||||
* Create a new expectation.
|
||||
*
|
||||
* @param {T | null} actual - The actual value of the expectation.
|
||||
*/
|
||||
constructor(actual: T | null);
|
||||
|
||||
/**
|
||||
* This expectation performs a strict equality on value types and reference types.
|
||||
*
|
||||
* @param {T | null} expected - The value to be compared.
|
||||
* @param {string} message - The optional message that describes the expectation.
|
||||
*
|
||||
* @example
|
||||
* expect<i32>(42).not.toBe(-1, "42 should not be -1");
|
||||
* expect<i32>(19 + 23).toBe(42, "19 + 23 should equal 42");
|
||||
*/
|
||||
toBe(expected: T | null, message?: string): void;
|
||||
|
||||
/**
|
||||
* This expectation performs a strict equality on value types and performs a memcompare on
|
||||
* reference types. If the reference type `T` has reference types as properties, the comparison does
|
||||
* not perform property traversal. It will only compare the pointer values in the memory block, and
|
||||
* only compare `offsetof<T>()` bytes, regardless of the allocated block size.
|
||||
*
|
||||
* @param {T | null} expected - The value to be compared.
|
||||
* @param {string} message - The optional message that describes the expectation.
|
||||
*
|
||||
* @example
|
||||
* expect<Vec3>(new Vec3(1, 2, 3)).toStrictEqual(new Vec(1, 2, 3), "Vectors of the same shape should be equal");
|
||||
*/
|
||||
toStrictEqual(expected: T | null, message?: string): void;
|
||||
|
||||
/**
|
||||
* This expectation performs a strict memory block equality based on the allocated block sizes.
|
||||
*
|
||||
* @param {T | null} expected - The value to be compared.
|
||||
* @param {string} message - The optional message that describes the expectation.
|
||||
*
|
||||
* @example
|
||||
* expect<Vec3>(new Vec3(1, 2, 3)).toBlockEqual(new Vec(1, 2, 3), "Vectors of the same shape should be equal");
|
||||
*/
|
||||
toBlockEqual(expected: T | null, message?: string): void;
|
||||
|
||||
/**
|
||||
* If the value is callable, it calls the function, and fails the expectation if it throws, or hits
|
||||
* an unreachable().
|
||||
*
|
||||
* @param {string} message - The optional message that describes the expectation.
|
||||
*
|
||||
* @example
|
||||
* expectFn((): void => unreachable()).toThrow("unreachable() should throw.");
|
||||
* expectFn((): void => {
|
||||
* cat.sleep(100); // cats can sleep quite a lot
|
||||
* }).not.toThrow("cats should sleep, not throw");
|
||||
*/
|
||||
toThrow(message?: string): void;
|
||||
|
||||
/**
|
||||
* This expecation asserts that the value is truthy, like in javascript. If the value is a string,
|
||||
* then strings of length 0 are not truthy.
|
||||
*
|
||||
* @param {string} message - The optional message that describes the expectation.
|
||||
*
|
||||
* @example
|
||||
* expect<bool>(true).toBeTruthy("true is truthy.");
|
||||
* expect<i32>(1).toBeTruthy("numeric values that are not 0 are truthy.");
|
||||
* expect<Vec3>(new Vec3(1, 2, 3)).toBeTruthy("reference types that aren't null are truthy.");
|
||||
* expect<bool>(false).not.toBeTruthy("false is not truthy.");
|
||||
* expect<i32>(0).not.toBeTruthy("0 is not truthy.");
|
||||
* expect<Vec3>(null).not.toBeTruthy("null is not truthy.");
|
||||
*/
|
||||
toBeTruthy(message?: string): void;
|
||||
|
||||
/**
|
||||
* This expectation tests the value to see if it is null. If the value is a value type, it is
|
||||
* never null. If the value is a reference type, it performs a strict null comparison.
|
||||
*
|
||||
* @param {string} message - The optional message that describes the expectation.
|
||||
*
|
||||
* @example
|
||||
* expect<i32>(0).not.toBeNull("numbers are never null");
|
||||
* expect<Vec3>(null).toBeNull("null reference types are null.");
|
||||
*/
|
||||
toBeNull(message?: string): void;
|
||||
|
||||
/**
|
||||
* This expecation assert that the value is falsy, like in javascript. If the value is a string,
|
||||
* then strings of length 0 are falsy.
|
||||
*
|
||||
* @param {string} message - The optional message that describes the expectation.
|
||||
*
|
||||
* @example
|
||||
* expect<bool>(false).toBeFalsy("false is falsy.");
|
||||
* expect<i32>(0).toBeFalsy("0 is falsy.");
|
||||
* expect<Vec3>(null).toBeFalsy("null is falsy.");
|
||||
* expect<bool>(true).not.toBeFalsy("true is not falsy.");
|
||||
* expect<i32>(1).not.toBeFalsy("numeric values that are not 0 are not falsy.");
|
||||
* expect<Vec3>(new Vec3(1, 2, 3)).not.toBeFalsy("reference types that aren't null are not falsy.");
|
||||
*/
|
||||
toBeFalsy(message?: string): void;
|
||||
|
||||
/**
|
||||
* This expectation asserts that the value is greater than the expected value. Since operators can
|
||||
* be overloaded in assemblyscript, it's possible for this to work on reference types.
|
||||
*
|
||||
* @param {T | null} expected - The expected value that the actual value should be greater than.
|
||||
* @param {string} message - The optional message that describes this expectation.
|
||||
*
|
||||
* @example
|
||||
* expect<i32>(10).toBeGreaterThan(4);
|
||||
* expect<i32>(12).not.toBeGreaterThan(42);
|
||||
*/
|
||||
toBeGreaterThan(expected: T | null, message?: string): void;
|
||||
|
||||
/**
|
||||
* This expectation asserts that the value is less than the expected value. Since operators can
|
||||
* be overloaded in assemblyscript, it's possible for this to work on reference types.
|
||||
*
|
||||
* @param {T | null} value - The expected value that the actual value should be less than.
|
||||
* @param {string} message - The optional message that describes this expectation.
|
||||
*
|
||||
* @example
|
||||
* expect<i32>(10).not.toBeLessThan(4);
|
||||
* expect<i32>(12).toBeLessThan(42);
|
||||
*/
|
||||
toBeLessThan(expected: T | null, message?: string): void;
|
||||
|
||||
/**
|
||||
* This expectation asserts that the value is greater than or equal to the expected value. Since
|
||||
* operators can be overloaded in assemblyscript, it's possible for this to work on reference
|
||||
* types.
|
||||
*
|
||||
* @param {T | null} value - The expected value that the actual value should be greater than or
|
||||
* equal to.
|
||||
* @param {string} message - The optional message that describes this expectation.
|
||||
*
|
||||
* @example
|
||||
* expect<i32>(42).toBeGreaterThanOrEqualTo(42);
|
||||
* expect<i32>(10).toBeGreaterThanOrEqualTo(4);
|
||||
* expect<i32>(12).not.toBeGreaterThanOrEqualTo(42);
|
||||
*/
|
||||
toBeGreaterThanOrEqualTo(expected: T | null, message?: string): void;
|
||||
|
||||
/**
|
||||
* This expectation asserts that the value is less than or equal to the expected value. Since
|
||||
* operators can be overloaded in assemblyscript, it's possible for this to work on reference
|
||||
* types.
|
||||
*
|
||||
* @param {T | null} value - The expected value that the actual value should be less than or equal
|
||||
* to.
|
||||
* @param {string} message - The optional message that describes this expectation.
|
||||
*
|
||||
* @example
|
||||
* expect<i32>(42).toBeLessThanOrEqualTo(42);
|
||||
* expect<i32>(10).not.toBeLessThanOrEqualTo(4);
|
||||
* expect<i32>(12).toBeLessThanOrEqualTo(42);
|
||||
*/
|
||||
toBeLessThanOrEqualTo(expected: T | null, message?: string): void;
|
||||
|
||||
/**
|
||||
* This expectation asserts that the value is close to another value. Both numbers must be finite,
|
||||
* and T must extend f64 or f32.
|
||||
*
|
||||
* @param {T extends f64 | f32} value - The expected value to be close to.
|
||||
* @param {i32} decimalPlaces - The number of decimal places used to calculate epsilon. Default is
|
||||
* 2.
|
||||
* @param {string} message - The optional message that describes this expectation.
|
||||
*/
|
||||
toBeCloseTo(expected: T, decimalPlaces?: number, message?: string): void;
|
||||
|
||||
/**
|
||||
* This function asserts the float type value is NaN.
|
||||
*
|
||||
* @param {string} message - The optional message the describes this expectation.
|
||||
* @example
|
||||
* expect<f64>(NaN).toBeNaN();
|
||||
* expect<f32>(42).not.toBeNaN();
|
||||
*/
|
||||
toBeNaN(message?: string): void;
|
||||
|
||||
/**
|
||||
* This function asserts a float is finite.
|
||||
*
|
||||
* @param {string} message - The optional message the describes this expectation.
|
||||
* @example
|
||||
* expect<f32>(42).toBeFinite();
|
||||
* expect<f64>(Infinity).not.toBeFinite();
|
||||
*/
|
||||
toBeFinite(message?: string): void;
|
||||
|
||||
/**
|
||||
* This method asserts the item has the expected length.
|
||||
*
|
||||
* @param {i32} expected - The expected length.
|
||||
* @param {string} message - The optional message the describes this expectation.
|
||||
*/
|
||||
toHaveLength(expected: i32, message?: string): void;
|
||||
|
||||
/**
|
||||
* This method asserts that a given T that extends Array<U> has a value/reference included.
|
||||
*
|
||||
* @param {i32} expected - The expected item to be included in the Array.
|
||||
* @param {string} message - The optional message the describes this expectation.
|
||||
*/
|
||||
toInclude<U>(expected: U, message?: string): void;
|
||||
|
||||
|
||||
/**
|
||||
* This method asserts that a given T that extends Array<U> has a value/reference included and
|
||||
* compared via memory.compare().
|
||||
*
|
||||
* @param {i32} expected - The expected item to be included in the Array.
|
||||
* @param {string} message - The optional message the describes this expectation.
|
||||
*/
|
||||
toIncludeEqual<U>(expected: U, message?: string): void;
|
||||
|
||||
/**
|
||||
* This computed property is chainable, and negates the existing expectation. It returns itself.
|
||||
*
|
||||
* @param {U} expected - The expected item.
|
||||
* @param {string} message - The optional message the describes this expectation.
|
||||
* @type {Expectation<T>}
|
||||
*/
|
||||
not: Expectation<T>;
|
||||
|
||||
/**
|
||||
* The actual value of the expectation.
|
||||
*/
|
||||
actual: T | null;
|
||||
private _not: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* This is called to stop the debugger. e.g. `node --inspect-brk asp`.
|
||||
*/
|
||||
declare function debug(): void;
|
||||
|
||||
/**
|
||||
* This function call enables performance statistics gathering for the following test.
|
||||
*
|
||||
* @param {bool} enabled - The bool to indicate if performance statistics should be gathered.
|
||||
*/
|
||||
declare function performanceEnabled(enabled: bool): void;
|
||||
|
||||
/**
|
||||
* This function call sets the maximum number of samples to complete the following test.
|
||||
*
|
||||
* @param {f64} count - The maximum number of samples required.
|
||||
*/
|
||||
declare function maxSamples(count: f64): void;
|
||||
|
||||
/**
|
||||
* This function call sets the number of decimal places to round to for the following test.
|
||||
*
|
||||
* @param {i32} deicmalPlaces - The number of decimal places to round to
|
||||
*/
|
||||
declare function roundDecimalPlaces(count: i32): void;
|
||||
|
||||
/**
|
||||
* This function call will set the maximum amount of time that should pass before it can stop
|
||||
* gathering samples for the following test.
|
||||
*
|
||||
* @param {f64} time - The ammount of time in milliseconds.
|
||||
*/
|
||||
declare function maxTestRunTime(time: f64): void;
|
||||
|
||||
/**
|
||||
* This function call enables gathering the average/mean run time of each sample for the following
|
||||
* test.
|
||||
*
|
||||
* @param {bool} enabled - The bool to indicate if the average/mean should be gathered.
|
||||
*/
|
||||
declare function reportAverage(enabled: bool): void;
|
||||
|
||||
/**
|
||||
* This function call enables gathering the median run time of each sample for the following test.
|
||||
*
|
||||
* @param {bool} enabled - The bool to indicate if the median should be gathered.
|
||||
*/
|
||||
declare function reportMedian(value: bool): void;
|
||||
|
||||
/**
|
||||
* This function call enables gathering the standard deviation of the run times of the samples
|
||||
* collected for the following test.
|
||||
*
|
||||
* @param {bool} enabled - The bool to indicate if the standard deviation should be gathered.
|
||||
*/
|
||||
declare function reportStdDev(value: bool): void;
|
||||
|
||||
/**
|
||||
* This function call enables gathering the largest run time of the samples collected for the
|
||||
* following test.
|
||||
*
|
||||
* @param {bool} enabled - The bool to indicate if the max should be gathered.
|
||||
*/
|
||||
declare function reportMax(value: bool): void;
|
||||
|
||||
/**
|
||||
* This function call enables gathering the smallest run time of the samples collected for the
|
||||
* following test.
|
||||
*
|
||||
* @param {bool} enabled - The bool to indicate if the min should be gathered.
|
||||
*/
|
||||
declare function reportMin(value: bool): void;
|
||||
|
||||
/**
|
||||
* This function call enables gathering the varaince of the samples collected for the following test.
|
||||
*
|
||||
* @param {bool} enabled - The bool to indicate if the variance should be calculated.
|
||||
*/
|
||||
declare function reportVariance(value: bool): void;
|
||||
|
||||
/**
|
||||
* This static class contains a few conveince methods for developers to test the current number of
|
||||
* blocks allocated on the heap.
|
||||
*/
|
||||
declare class RTrace {
|
||||
/**
|
||||
* This bool indicates if `RTrace` should call into JavaScript to obtain reference counts.
|
||||
*/
|
||||
public static enabled: bool;
|
||||
|
||||
/**
|
||||
* This method returns the current number of active references on the heap.
|
||||
*/
|
||||
public static count(): i32;
|
||||
|
||||
/**
|
||||
* This method starts a new refcounting group, and causes the next call to `RTrace.end(label)` to
|
||||
* return a delta in reference counts on the heap.
|
||||
*
|
||||
* @param {i32} label - The numeric label for this refcounting group.
|
||||
*/
|
||||
public static start(label: i32): void;
|
||||
|
||||
/**
|
||||
* This method returns a delta of how many new (positive) or collected (negative) are on the heap.
|
||||
*
|
||||
* @param {i32} label - The numeric label for this refcounting group.
|
||||
*/
|
||||
public static end(label: i32): i32;
|
||||
|
||||
/**
|
||||
* This method returns the number of increments that have occurred over the course of a test
|
||||
* file.
|
||||
*/
|
||||
public static increments(): i32;
|
||||
|
||||
/**
|
||||
* This method returns the number of decrements that have occurred over the course of a test
|
||||
* file.
|
||||
*/
|
||||
public static decrements(): i32;
|
||||
|
||||
/**
|
||||
* This method returns the number of increments that have occurred over the course of a test
|
||||
* group.
|
||||
*/
|
||||
public static groupIncrements(): i32;
|
||||
|
||||
/**
|
||||
* This method returns the number of decrements that have occurred over the course of a test
|
||||
* group.
|
||||
*/
|
||||
public static groupDecrements(): i32;
|
||||
|
||||
/**
|
||||
* This method returns the number of increments that have occurred over the course of a test
|
||||
* group.
|
||||
*/
|
||||
public static testIncrements(): i32;
|
||||
|
||||
/**
|
||||
* This method returns the number of decrements that have occurred over the course of a test
|
||||
* group.
|
||||
*/
|
||||
public static testDecrements(): i32;
|
||||
|
||||
/**
|
||||
* This method returns the number of allocations that have occurred over the course of a test
|
||||
* file.
|
||||
*/
|
||||
public static allocations(): i32;
|
||||
|
||||
/**
|
||||
* This method returns the number of frees that have occurred over the course of a test
|
||||
* file.
|
||||
*/
|
||||
public static frees(): i32;
|
||||
|
||||
/**
|
||||
* This method returns the number of allocations that have occurred over the course of a test
|
||||
* group.
|
||||
*/
|
||||
public static groupAllocations(): i32;
|
||||
|
||||
/**
|
||||
* This method returns the number of frees that have occurred over the course of a test
|
||||
* group.
|
||||
*/
|
||||
public static groupFrees(): i32;
|
||||
|
||||
/**
|
||||
* This method returns the number of allocations that have occurred over the course of a test
|
||||
* group.
|
||||
*/
|
||||
public static testAllocations(): i32;
|
||||
|
||||
/**
|
||||
* This method returns the number of frees that have occurred over the course of a test
|
||||
* group.
|
||||
*/
|
||||
public static testFrees(): i32;
|
||||
|
||||
/**
|
||||
* This method triggers a garbage collection.
|
||||
*/
|
||||
public static collect(): void;
|
||||
}
|
113
assembly/__tests__/roundtrip.spec.ts
Normal file
113
assembly/__tests__/roundtrip.spec.ts
Normal file
@ -0,0 +1,113 @@
|
||||
import { JSONDecoder } from "../decoder";
|
||||
import { JSONEncoder } from "../encoder";
|
||||
|
||||
let handler: JSONEncoder;
|
||||
let decoder: JSONDecoder<JSONEncoder>;
|
||||
|
||||
function roundripTest(jsonString: string, expectedString: string | null = null): bool {
|
||||
log<string>("--------" + jsonString + (expectedString ? " " + expectedString! : ""));
|
||||
expectedString = expectedString || jsonString;
|
||||
let buffer: Uint8Array = new Uint8Array(jsonString.lengthUTF8);
|
||||
let utf8ptr = jsonString.toUTF8();
|
||||
memory.copy(<usize>buffer.buffer, utf8ptr, buffer.byteLength);
|
||||
decoder.deserialize(buffer);
|
||||
let resultBuffer = handler.serialize();
|
||||
let resultString = String.fromUTF8(
|
||||
<usize>resultBuffer.buffer + resultBuffer.byteOffset,
|
||||
resultBuffer.length
|
||||
);
|
||||
assert(expectedString != null);
|
||||
if (expectedString) {
|
||||
expect<string>(resultString).toStrictEqual(expectedString);
|
||||
expect<string>(handler.toString()).toStrictEqual(expectedString);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
describe("Round trip", () => {
|
||||
|
||||
beforeEach(() => {
|
||||
handler = new JSONEncoder();
|
||||
decoder = new JSONDecoder<JSONEncoder>(handler);
|
||||
});
|
||||
|
||||
|
||||
it("create decoder", () => {
|
||||
expect<bool>(decoder != null).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle empty object", () => {
|
||||
expect<bool>(roundripTest("{}")).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle empty object with whitespace", () => {
|
||||
expect<bool>(roundripTest("{ }", "{}")).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle int32", () => {
|
||||
expect<bool>(roundripTest('{"int":4660}')).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle int32Sign", () => {
|
||||
expect<bool>(roundripTest('{"int":-4660}')).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle true", () => {
|
||||
expect<bool>(roundripTest('{"val":true}')).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle false", () => {
|
||||
expect<bool>(roundripTest('{"val":false}')).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle null", () => {
|
||||
expect<bool>(roundripTest('{"val":null}')).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle string", () => {
|
||||
expect<bool>(roundripTest('{"str":"foo"}')).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle string escaped", () => {
|
||||
expect<bool>(roundripTest('"\\"\\\\\\/\\n\\t\\b\\r\\t"', '"\\"\\\\/\\n\\t\\b\\r\\t"')).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle string unicode escaped simple", () => {
|
||||
expect<bool>(roundripTest('"\\u0022"', '"\\""')).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle string unicode escaped", () => {
|
||||
expect<bool>(roundripTest('"\\u041f\\u043e\\u043b\\u0442\\u043e\\u0440\\u0430 \\u0417\\u0435\\u043c\\u043b\\u0435\\u043a\\u043e\\u043f\\u0430"', '"Полтора Землекопа"')).toBe(true)
|
||||
})
|
||||
|
||||
it("should multiple keys", () => {
|
||||
expect<bool>(roundripTest('{"str":"foo","bar":"baz"}')).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle nested objects", () => {
|
||||
expect<bool>(roundripTest('{"str":"foo","obj":{"a":1,"b":-123456}}')).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle empty array", () => {
|
||||
expect<bool>(roundripTest('[]')).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle array", () => {
|
||||
expect<bool>(roundripTest('[1,2,3]')).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle nested arrays", () => {
|
||||
expect<bool>(roundripTest('[[1,2,3],[4,[5,6]]]')).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle nested objects and arrays", () => {
|
||||
expect<bool>(roundripTest('{"str":"foo","arr":[{"obj":{"a":1,"b":-123456}}]}')).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle whitespace", () => {
|
||||
expect<bool>(roundripTest(
|
||||
' { "str":"foo","obj": {"a":1, "b" :\n -123456} } ',
|
||||
'{"str":"foo","obj":{"a":1,"b":-123456}}')).toBe(true);
|
||||
});
|
||||
})
|
@ -100,6 +100,7 @@ export class JSONDecoder<JSONHandlerT extends JSONHandler> {
|
||||
}
|
||||
|
||||
assert(this.parseValue(), "Cannot parse JSON");
|
||||
|
||||
// TODO: Error if input left
|
||||
}
|
||||
|
||||
@ -201,7 +202,10 @@ export class JSONDecoder<JSONHandlerT extends JSONHandler> {
|
||||
let byte = this.readChar();
|
||||
assert(byte >= 0x20, "Unexpected control character");
|
||||
if (byte == '"'.charCodeAt(0)) {
|
||||
let s = String.fromUTF8(this.state.buffer.buffer.data + savedIndex, this.state.readIndex - savedIndex - 1);
|
||||
let s = String.fromUTF8(
|
||||
<usize>this.state.buffer.buffer + this.state.buffer.byteOffset + savedIndex,
|
||||
this.state.readIndex - savedIndex - 1
|
||||
);
|
||||
if (stringParts == null) {
|
||||
return s;
|
||||
}
|
||||
@ -213,7 +217,11 @@ export class JSONDecoder<JSONHandlerT extends JSONHandler> {
|
||||
}
|
||||
if (this.state.readIndex > savedIndex + 1) {
|
||||
stringParts.push(
|
||||
String.fromUTF8(this.state.buffer.buffer.data + savedIndex, this.state.readIndex - savedIndex - 1));
|
||||
String.fromUTF8(
|
||||
<usize>this.state.buffer.buffer + this.state.buffer.byteOffset + savedIndex,
|
||||
this.state.readIndex - savedIndex - 1
|
||||
)
|
||||
);
|
||||
}
|
||||
stringParts.push(this.readEscapedChar());
|
||||
savedIndex = this.state.readIndex;
|
||||
|
@ -14,7 +14,7 @@ export class JSONEncoder {
|
||||
let result = this.toString();
|
||||
let utf8ptr = result.toUTF8();
|
||||
let buffer = new Uint8Array(result.lengthUTF8 - 1);
|
||||
memory.copy(buffer.buffer.data, utf8ptr, buffer.byteLength);
|
||||
memory.copy(<usize>buffer.buffer, utf8ptr, buffer.byteLength);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
4815
package-lock.json
generated
4815
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
26
package.json
26
package.json
@ -6,30 +6,12 @@
|
||||
"asbuild:untouched": "asc assembly/index.ts -b build/untouched.wasm -t build/untouched.wat --sourceMap --validate --debug",
|
||||
"asbuild:optimized": "asc assembly/index.ts -b build/optimized.wasm -t build/optimized.wat --sourceMap --validate --optimize",
|
||||
"asbuild": "npm run asbuild:untouched && npm run asbuild:optimized",
|
||||
"asbuild:test": "npm run asbuild:test:roundtrip",
|
||||
"asbuild:test:roundtrip": "asc tests/assembly/roundtrip.spec.as.ts -b tests/build/roundtrip.wasm -t tests/build/roundtrip.wat --validate --sourceMap --importMemory --debug",
|
||||
"test": "npm run asbuild:test && ava -v --serial",
|
||||
"test:ci": "npm run asbuild:test && ava --fail-fast --serial"
|
||||
"test": "asp",
|
||||
"test:ci": "asp --reporter=SummaryTestReporter"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^10.12.3",
|
||||
"assemblyscript": "nearprotocol/assemblyscript",
|
||||
"ava": "1.0.0-rc.1",
|
||||
"ts-node": "^7.0.1",
|
||||
"typedoc": "^0.13.0",
|
||||
"typescript": "^3.1.6"
|
||||
},
|
||||
"ava": {
|
||||
"compileEnhancements": true,
|
||||
"extensions": [
|
||||
"ts"
|
||||
],
|
||||
"require": [
|
||||
"ts-node/register/transpile-only"
|
||||
],
|
||||
"files": [
|
||||
"tests/**/*.spec.ts"
|
||||
]
|
||||
"assemblyscript": "github:assemblyscript/assemblyscript",
|
||||
"as-pect": "github:jtenner/as-pect"
|
||||
},
|
||||
"dependencies": {}
|
||||
}
|
||||
|
@ -1,112 +0,0 @@
|
||||
import "allocator/arena";
|
||||
|
||||
import { JSONDecoder } from "../../assembly/decoder";
|
||||
import { JSONEncoder } from "../../assembly/encoder";
|
||||
|
||||
declare function logStr(str: string): void;
|
||||
declare function logF64(val: f64): void;
|
||||
|
||||
export class StringConversionTests {
|
||||
private static handler : JSONEncoder = null;
|
||||
|
||||
static setUp(): void {
|
||||
this.handler = new JSONEncoder();
|
||||
}
|
||||
|
||||
static createDecoder(): JSONDecoder<JSONEncoder> {
|
||||
return new JSONDecoder(this.handler);
|
||||
}
|
||||
|
||||
static shouldHandleEmptyObject(): bool {
|
||||
return this.roundripTest("{}");
|
||||
}
|
||||
|
||||
static shouldHandleEmptyObjectWithWhitespace(): bool {
|
||||
return this.roundripTest("{ }", "{}");
|
||||
}
|
||||
|
||||
static shouldHandleInt32(): bool {
|
||||
return this.roundripTest('{"int":4660}');
|
||||
}
|
||||
|
||||
static shouldHandleInt32Sign(): bool {
|
||||
return this.roundripTest('{"int":-4660}');
|
||||
}
|
||||
|
||||
static shouldHandleTrue(): bool {
|
||||
return this.roundripTest('{"val":true}');
|
||||
}
|
||||
|
||||
static shouldHandleFalse(): bool {
|
||||
return this.roundripTest('{"val":false}');
|
||||
}
|
||||
|
||||
static shouldHandleNull(): bool {
|
||||
return this.roundripTest('{"val":null}');
|
||||
}
|
||||
|
||||
static shouldHandleString(): bool {
|
||||
return this.roundripTest('{"str":"foo"}');
|
||||
}
|
||||
|
||||
static shouldHandleStringEscaped(): bool {
|
||||
return this.roundripTest('"\\"\\\\\\/\\n\\t\\b\\r\\t"', '"\\"\\\\/\\n\\t\\b\\r\\t"');
|
||||
}
|
||||
|
||||
static shouldHandleStringUnicodeEscaped1(): bool {
|
||||
return this.roundripTest('"\\u0022"', '"\\""');
|
||||
}
|
||||
|
||||
static shouldHandleStringUnicodeEscaped2(): bool {
|
||||
return this.roundripTest('"\\u041f\\u043e\\u043b\\u0442\\u043e\\u0440\\u0430 \\u0417\\u0435\\u043c\\u043b\\u0435\\u043a\\u043e\\u043f\\u0430"', '"Полтора Землекопа"');
|
||||
}
|
||||
|
||||
static shouldMultipleKeys(): bool {
|
||||
return this.roundripTest('{"str":"foo","bar":"baz"}');
|
||||
}
|
||||
|
||||
static shouldHandleNestedObjects(): bool {
|
||||
return this.roundripTest('{"str":"foo","obj":{"a":1,"b":-123456}}');
|
||||
}
|
||||
|
||||
static shouldHandleEmptyArray(): bool {
|
||||
return this.roundripTest('[]');
|
||||
}
|
||||
|
||||
static shouldHandleArray(): bool {
|
||||
return this.roundripTest('[1,2,3]');
|
||||
}
|
||||
|
||||
static shouldHandleNestedArrays(): bool {
|
||||
return this.roundripTest('[[1,2,3],[4,[5,6]]]');
|
||||
}
|
||||
|
||||
static shouldHandleNestedObjectsAndArrays(): bool {
|
||||
return this.roundripTest('{"str":"foo","arr":[{"obj":{"a":1,"b":-123456}}]}');
|
||||
}
|
||||
|
||||
static shouldHandleWhitespace(): bool {
|
||||
return this.roundripTest(
|
||||
' { "str":"foo","obj": {"a":1, "b" :\n -123456} } ',
|
||||
'{"str":"foo","obj":{"a":1,"b":-123456}}');
|
||||
}
|
||||
|
||||
private static roundripTest(jsonString: string, expectedString: string = null): bool {
|
||||
logStr("--------" + jsonString + (expectedString ? " " + expectedString : ""));
|
||||
expectedString = expectedString || jsonString;
|
||||
let buffer: Uint8Array = new Uint8Array(jsonString.lengthUTF8);
|
||||
let utf8ptr = jsonString.toUTF8();
|
||||
// TODO: std should expose memcpy?
|
||||
for (let i = 0; i < buffer.length; i++) {
|
||||
buffer[i] = load<u8>(utf8ptr + i);
|
||||
}
|
||||
this.createDecoder().deserialize(buffer);
|
||||
let resultBuffer = this.handler.serialize();
|
||||
let resultString = String.fromUTF8(resultBuffer.buffer.data, resultBuffer.length);
|
||||
assert(resultString == expectedString,
|
||||
"Expected:\n" + expectedString + "\n" + "Actual:\n" + resultString);
|
||||
assert(this.handler.toString() == expectedString,
|
||||
"Expected:\n" + expectedString + "\n" + "Actual:\n" + resultString);
|
||||
return true;
|
||||
}
|
||||
}
|
@ -1,63 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Basic Options */
|
||||
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
|
||||
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
|
||||
// "lib": [], /* Specify library files to be included in the compilation. */
|
||||
// "allowJs": true, /* Allow javascript files to be compiled. */
|
||||
// "checkJs": true, /* Report errors in .js files. */
|
||||
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
|
||||
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
||||
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
|
||||
// "sourceMap": true, /* Generates corresponding '.map' file. */
|
||||
// "outFile": "./", /* Concatenate and emit output to single file. */
|
||||
// "outDir": "./", /* Redirect output structure to the directory. */
|
||||
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
||||
// "composite": true, /* Enable project compilation */
|
||||
// "removeComments": true, /* Do not emit comments to output. */
|
||||
// "noEmit": true, /* Do not emit outputs. */
|
||||
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
|
||||
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
|
||||
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
|
||||
|
||||
/* Strict Type-Checking Options */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* Enable strict null checks. */
|
||||
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
|
||||
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
|
||||
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
|
||||
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
|
||||
|
||||
/* Additional Checks */
|
||||
// "noUnusedLocals": true, /* Report errors on unused locals. */
|
||||
// "noUnusedParameters": true, /* Report errors on unused parameters. */
|
||||
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
|
||||
|
||||
/* Module Resolution Options */
|
||||
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
|
||||
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
|
||||
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
|
||||
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
|
||||
// "typeRoots": [], /* List of folders to include type definitions from. */
|
||||
// "types": [], /* Type declaration files to be included in compilation. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
|
||||
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
|
||||
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
|
||||
|
||||
/* Source Map Options */
|
||||
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
|
||||
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
|
||||
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
|
||||
|
||||
/* Experimental Options */
|
||||
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
||||
},
|
||||
"extends": "../../node_modules/assemblyscript/std/assembly.json",
|
||||
"include": [
|
||||
"./**/*.ts","*.ts"
|
||||
]
|
||||
}
|
@ -1,3 +0,0 @@
|
||||
import { defineTestsFromModule } from './utils/spec';
|
||||
|
||||
defineTestsFromModule('roundtrip');
|
96
tests/types/webassembly/index.d.ts
vendored
96
tests/types/webassembly/index.d.ts
vendored
@ -1,96 +0,0 @@
|
||||
/**
|
||||
* WebAssembly v1 (MVP) declaration file for TypeScript
|
||||
* Definitions by: 01alchemist (https://twitter.com/01alchemist)
|
||||
*/
|
||||
declare namespace WebAssembly {
|
||||
/**
|
||||
* WebAssembly.Module
|
||||
**/
|
||||
class Module {
|
||||
constructor(bufferSource: ArrayBuffer | ArrayBufferView<number>);
|
||||
|
||||
static customSections(module: Module, sectionName: string): ArrayBuffer[];
|
||||
static exports(module: Module): { name: string, kind: string }[];
|
||||
static imports(module: Module): { module: string, name: string, kind: string }[];
|
||||
}
|
||||
|
||||
/**
|
||||
* WebAssembly.Instance
|
||||
**/
|
||||
class Instance {
|
||||
readonly exports: any;
|
||||
constructor(module: Module, importObject?: any);
|
||||
}
|
||||
|
||||
/**
|
||||
* WebAssembly.Memory
|
||||
* Note: A WebAssembly page has a constant size of 65,536 bytes, i.e., 64KiB.
|
||||
**/
|
||||
interface MemoryDescriptor {
|
||||
initial: number;
|
||||
maximum?: number;
|
||||
}
|
||||
|
||||
class Memory {
|
||||
readonly buffer: ArrayBuffer;
|
||||
constructor(memoryDescriptor: MemoryDescriptor);
|
||||
grow(numPages: number): number;
|
||||
}
|
||||
|
||||
/**
|
||||
* WebAssembly.Table
|
||||
**/
|
||||
interface TableDescriptor {
|
||||
element: "anyfunc",
|
||||
initial: number;
|
||||
maximum?: number;
|
||||
}
|
||||
|
||||
class Table {
|
||||
readonly length: number;
|
||||
constructor(tableDescriptor: TableDescriptor);
|
||||
get(index: number): Function;
|
||||
grow(numElements: number): number;
|
||||
set(index: number, value: Function): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Errors
|
||||
*/
|
||||
class CompileError extends Error {
|
||||
readonly fileName: string;
|
||||
readonly lineNumber: string;
|
||||
readonly columnNumber: string;
|
||||
constructor(message?: string, fileName?: string, lineNumber?: number);
|
||||
toString(): string;
|
||||
}
|
||||
|
||||
class LinkError extends Error {
|
||||
readonly fileName: string;
|
||||
readonly lineNumber: string;
|
||||
readonly columnNumber: string;
|
||||
constructor(message?: string, fileName?: string, lineNumber?: number);
|
||||
toString(): string;
|
||||
}
|
||||
|
||||
class RuntimeError extends Error {
|
||||
readonly fileName: string;
|
||||
readonly lineNumber: string;
|
||||
readonly columnNumber: string;
|
||||
constructor(message?: string, fileName?: string, lineNumber?: number);
|
||||
toString(): string;
|
||||
}
|
||||
|
||||
function compile(bufferSource: ArrayBuffer | ArrayBufferView<number>): Promise<Module>;
|
||||
|
||||
interface ResultObject {
|
||||
module: Module;
|
||||
instance: Instance;
|
||||
}
|
||||
|
||||
function instantiateStreaming(bufferSource: ArrayBuffer | ArrayBufferView<number>, importObject?: any): Promise<ResultObject>;
|
||||
function instantiate(bufferSource: ArrayBuffer | ArrayBufferView<number>, importObject?: any): Promise<ResultObject>;
|
||||
function instantiate(module: Module, importObject?: any): Promise<Instance>;
|
||||
|
||||
function validate(bufferSource: ArrayBuffer | ArrayBufferView<number>): boolean;
|
||||
}
|
@ -1,3 +0,0 @@
|
||||
{
|
||||
"types": "index.d.ts"
|
||||
}
|
@ -1,114 +0,0 @@
|
||||
/// <reference path="../types/webassembly/index.d.ts" />
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as util from 'util';
|
||||
|
||||
import { demangle } from 'assemblyscript/lib/loader';
|
||||
|
||||
const DIGITALS_REGEXP = /([0-9]{1,})/g;
|
||||
const UPPER_ALPHAS_REGEXP = /([A-Z]{1,})/g;
|
||||
|
||||
export type ImportEntries = { [key: string]: object };
|
||||
export type ExportedEntry = { [key: string]: Function };
|
||||
export type ExportedEntries = { [key: string]: ExportedEntry };
|
||||
|
||||
const readFile = util.promisify(fs.readFile);
|
||||
|
||||
const F64 = new Float64Array(1);
|
||||
const U64 = new Uint32Array(F64.buffer);
|
||||
|
||||
export function decamelize(str: string): string {
|
||||
const t = str
|
||||
.replace(DIGITALS_REGEXP, ' $1')
|
||||
.replace(UPPER_ALPHAS_REGEXP, m => ' ' + (m.length === 1 ? m.toLowerCase() : m));
|
||||
return t.charAt(0).toUpperCase() + t.slice(1);
|
||||
}
|
||||
|
||||
export async function setup(testFileName: string): Promise<ExportedEntries> {
|
||||
const pathName = path.resolve(__dirname, `../build/${ testFileName }.wasm`);
|
||||
const file = await readFile(pathName, null);
|
||||
if (!WebAssembly.validate(file)) {
|
||||
throw new Error(`WebAssembly binary "${ pathName }" file not valid!`);
|
||||
}
|
||||
const imports = buildImports(`${ testFileName }.spec.as`, new WebAssembly.Memory({ initial: 2 }));
|
||||
const result = await WebAssembly.instantiate(file, imports);
|
||||
return demangle<ExportedEntries>(result.instance.exports);
|
||||
}
|
||||
|
||||
function unpackToString64(value: number): string {
|
||||
F64[0] = value;
|
||||
return U64[1].toString(16) + U64[0].toString(16);
|
||||
}
|
||||
|
||||
function unpackToString128(lo: number, hi: number): string {
|
||||
return `0x${ (unpackToString64(hi) + unpackToString64(lo)).padStart(32, '0') }`;
|
||||
}
|
||||
|
||||
function getString(ptr: number, buffer: ArrayBuffer): string {
|
||||
var U16 = new Uint16Array(buffer);
|
||||
var U32 = new Uint32Array(buffer);
|
||||
var dataLength = U32[ptr >>> 2];
|
||||
var dataOffset = (ptr + 4) >>> 1;
|
||||
var dataRemain = dataLength;
|
||||
var parts = [];
|
||||
const chunkSize = 1024;
|
||||
while (dataRemain > chunkSize) {
|
||||
let last = U16[dataOffset + chunkSize - 1];
|
||||
let size = last >= 0xD800 && last < 0xDC00 ? chunkSize - 1 : chunkSize;
|
||||
let part = U16.subarray(dataOffset, dataOffset += size);
|
||||
parts.push(String.fromCharCode.apply(String, part));
|
||||
dataRemain -= size;
|
||||
}
|
||||
return parts.join('') + String.fromCharCode.apply(String, U16.subarray(dataOffset, dataOffset + dataRemain));
|
||||
}
|
||||
|
||||
function buildImports(name: string, memory: WebAssembly.Memory): ImportEntries {
|
||||
const buffer = memory.buffer;
|
||||
return {
|
||||
env: {
|
||||
memory,
|
||||
abort(msgPtr: number, filePtr: number, line: number, column: number) {
|
||||
if (msgPtr) {
|
||||
throw new Error(
|
||||
`Abort called by reason "${ getString(msgPtr, buffer) }" at ${ getString(filePtr, buffer) } [${ line }:${ column }]`
|
||||
);
|
||||
} else {
|
||||
throw new Error(`Abort called at ${ getString(filePtr, buffer) } [${ line }:${ column }]`);
|
||||
}
|
||||
},
|
||||
},
|
||||
// TODO: Don't hardcode support for encoder/decoder
|
||||
decoder: {
|
||||
logStr(msgPtr: number) {
|
||||
if (msgPtr) console.log(`[str]: ${ getString(msgPtr, buffer) }`);
|
||||
},
|
||||
logF64(value: number) {
|
||||
console.log(`[f64]: ${ value }`);
|
||||
},
|
||||
},
|
||||
encoder: {
|
||||
logStr(msgPtr: number) {
|
||||
if (msgPtr) console.log(`[str]: ${ getString(msgPtr, buffer) }`);
|
||||
},
|
||||
logF64(value: number) {
|
||||
console.log(`[f64]: ${ value }`);
|
||||
},
|
||||
},
|
||||
[name]: {
|
||||
logF64(value: number) {
|
||||
console.log(`[f64]: ${ value }`);
|
||||
},
|
||||
logStr(msgPtr: number) {
|
||||
if (msgPtr) console.log(`[str]: ${ getString(msgPtr, buffer) }`);
|
||||
},
|
||||
logU128Packed(msgPtr: number, lo: number, hi: number) {
|
||||
if (msgPtr) {
|
||||
console.log(`[u128] ${ getString(msgPtr, buffer) }: ${ unpackToString128(lo, hi) }`);
|
||||
} else {
|
||||
console.log(`[u128]: ${ unpackToString128(lo, hi) }`);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
@ -1,34 +0,0 @@
|
||||
import test from 'ava';
|
||||
import { setup, decamelize } from './helpers';
|
||||
|
||||
export async function defineTestsFromModule(moduleName: string) {
|
||||
try {
|
||||
const instance = await setup(moduleName);
|
||||
|
||||
// TODO: Refactor into proper testing framework for AssemblyScript
|
||||
for (const tests in instance) {
|
||||
const testsInstance = instance[tests];
|
||||
|
||||
if (testsInstance.setUp) {
|
||||
test.beforeEach(() => {
|
||||
testsInstance.setUp();
|
||||
});
|
||||
}
|
||||
if (testsInstance.tearDown) {
|
||||
test.afterEach(() => {
|
||||
testsInstance.tearDown();
|
||||
});
|
||||
}
|
||||
for (const testName of Object.keys(testsInstance).filter(it => !(["setUp", "tearDown"].indexOf(it) != -1))) {
|
||||
if (testName.startsWith("shouldAbort")) {
|
||||
test(decamelize(testName), t => { t.throws(() => testsInstance[testName]()) });
|
||||
} else {
|
||||
test(decamelize(testName), t => t.truthy(testsInstance[testName]()));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("Error loading WebAssembly module:", e);
|
||||
throw e;
|
||||
}
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user