Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AssemblyScript transformer #5598

Draft
wants to merge 3 commits into
base: v2
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
284 changes: 284 additions & 0 deletions flow-libs/assemblyscript.js.flow
Original file line number Diff line number Diff line change
@@ -0,0 +1,284 @@
// @flow strict-local

declare module 'assemblyscript/cli/asc' {
/** Ready promise resolved once/if the compiler is ready. */
declare export var ready: Promise<void>;

/** Whether this is a webpack bundle or not. */
declare export var isBundle: boolean;

/** Whether asc runs the sources directly or not. */
declare export var isDev: boolean;

/** AssemblyScript version. */
declare export var version: string;

/** Command line option description. */
declare export interface OptionDescription {
/** Textual description. */
description?: string | string[];
/** Data type. One of (b)oolean [default], (i)nteger, (f)loat or (s)tring. Uppercase means multiple values. */
type?: 'b' | 'i' | 'f' | 's' | 'I' | 'F' | 'S';
/** Substituted options, if any. */
value?: any; // TODO
/** Short alias, if any. */
alias?: string;
/** The default value, if any. */
default?: string | number | boolean | string[] | number[];
/** The category this option belongs in. */
category?: string;
}

/** Available CLI options. */
declare export var options: {[key: string]: OptionDescription};

/** Common root used in source maps. */
declare export var sourceMapRoot: string;

/** Prefix used for library files. */
declare export var libraryPrefix: string;

/** Default Binaryen optimization level. */
declare export var defaultOptimizeLevel: number;

/** Default Binaryen shrink level. */
declare export var defaultShrinkLevel: number;

/** Bundled library files. */
declare export var libraryFiles: {[key: string]: string};

/** Bundled definition files. */
declare export var definitionFiles: {|assembly: string, portable: string|};

/** A compatible output stream. */
declare export interface OutputStream {
/** Writes another chunk of data to the stream. */
write(chunk: Uint8Array | string): void;
}

/** An in-memory output stream. */
declare export interface MemoryStream extends OutputStream {
/** Resets the stream to offset zero. */
reset(): void;
/** Converts the output to a buffer. */
toBuffer(): Uint8Array;
/** Converts the output to a string. */
toString(): string;
}

/** Relevant subset of the Source class for diagnostic reporting. */
declare export interface Source {
/** Normalized path with file extension. */
normalizedPath: string;
}

/** Relevant subset of the Range class for diagnostic reporting. */
declare export interface Range {
/** Start offset within the source file. */
start: number;
/** End offset within the source file. */
end: number;
/** Respective source file. */
source: Source;
}

/** Relevant subset of the DiagnosticMessage class for diagnostic reporting. */
declare export interface DiagnosticMessage {
/** Message code. */
code: number;
/** Message category. */
category: number;
/** Message text. */
message: string;
/** Respective source range, if any. */
range: Range | null;
/** Related range, if any. */
relatedRange: Range | null;
}

/** A function handling diagnostic messages. */
declare type DiagnosticReporter = (diagnostic: DiagnosticMessage) => void;

/** Compiler options. */
declare export interface CompilerOptions {
/** Prints just the compiler's version and exits. */
version?: boolean;
/** Prints the help message and exits. */
help?: boolean;
/** Optimizes the module. */
optimize?: boolean;
/** How much to focus on optimizing code. */
optimizeLevel?: number;
/** How much to focus on shrinking code size. */
shrinkLevel?: number;
/** Re-optimizes until no further improvements can be made. */
converge?: boolean;
/** Specifies the base directory of input and output files. */
baseDir?: string;
/** Specifies the output file. File extension indicates format. */
outFile?: string;
/** Specifies the binary output file (.wasm). */
binaryFile?: string;
/** Specifies the text output file (.wat). */
textFile?: string;
/** Specifies the JavaScript (via wasm2js) output file (.js). */
jsFile?: string;
/** Specifies the WebIDL output file (.webidl). */
idlFile?: string;
/** Specifies the TypeScript definition output file (.d.ts). */
tsdFile?: string;
/** Enables source map generation. Optionally takes the URL. */
sourceMap?: boolean | string;
/** Specifies the runtime variant to include in the program. */
runtime?: string;
/** Disallows the use of unsafe features in user code. */
noUnsafe?: boolean;
/** Enables debug information in emitted binaries. */
debug?: boolean;
/** Replaces assertions with just their value without trapping. */
noAssert?: boolean;
/** Performs compilation as usual but does not emit code. */
noEmit?: boolean;
/** Imports the memory provided as 'env.memory'. */
importMemory?: boolean;
/** Does not declare export the memory as 'memory'. */
noExportMemory?: boolean;
/** Sets the initial memory size in pages. */
initialMemory?: number;
/** Sets the maximum memory size in pages. */
maximumMemory?: number;
/** Declare memory as shared. Requires maximumMemory. */
sharedMemory?: boolean;
/** Sets the start offset of compiler-generated static memory. */
memoryBase?: number;
/** Imports the function table provided as 'env.table'. */
importTable?: boolean;
/** Exports the function table as 'table'. */
exportTable?: boolean;
/** Exports an explicit start function to be called manually. */
explicitStart?: boolean;
/** "Adds one or multiple paths to custom library components. */
lib?: string | string[];
/** Adds one or multiple paths to package resolution. */
path?: string | string[];
/** Aliases a global object under another name. */
use?: string | string[];
/** Sets the trap mode to use. */
trapMode?: 'allow' | 'clamp' | 'js';
/** Specifies additional Binaryen passes to run. */
runPasses?: string | string[];
/** Skips validating the module using Binaryen. */
noValidate?: boolean;
/** Enables WebAssembly features that are disabled by default. */
enable?: string | string[];
/** Disables WebAssembly features that are enabled by default. */
disable?: string | string[];
/** Specifies the path to a custom transform to 'require'. */
transform?: string | string[];
/** Make yourself sad for no good reason. */
pedantic?: boolean;
/** Enables tracing of package resolution. */
traceResolution?: boolean;
/** Lists files to be compiled and exits. */
listFiles?: boolean;
/** Prints measuring information on I/O and compile times. */
measure?: boolean;
/** Disables terminal colors. */
noColors?: boolean;
/** Specifies an alternative file extension. */
extension?: string;
}

/** Compiler API options. */
declare export interface APIOptions {
/** Standard output stream to use. */
stdout?: OutputStream;
/** Standard error stream to use. */
stderr?: OutputStream;
/** Reads a file from disk (or memory). */
readFile?: (filename: string, baseDir: string) => string | null;
/** Writes a file to disk (or memory). */
writeFile?: (
filename: string,
contents: Uint8Array,
baseDir: string,
) => void;
/** Lists all files within a directory. */
listFiles?: (dirname: string, baseDir: string) => string[] | null;
/** Handler for diagnostic messages. */
reportDiagnostic?: DiagnosticReporter;
/** Additional transforms to apply. */
transforms?: any[]; // TODO
}

/** Convenience function that parses and compiles source strings directly. */
declare export function compileString(
sources: {[key: string]: string} | string,
options?: CompilerOptions,
): {|
/** Standard output. */
stdout: OutputStream,
/** Standard error. */
stderr: OutputStream,
/** Emitted binary. */
binary: Uint8Array | null,
/** Emitted text format. */
text: string | null,
|};

/** Runs the command line utility using the specified arguments array. */
declare export function main(
argv: string[],
options: APIOptions,
callback?: (err: Error | null) => number,
): number;
declare export function main(
argv: string[],
callback?: (err: Error | null) => number,
): number;

/** Checks diagnostics emitted so far for errors. */
declare export function checkDiagnostics(
emitter: {|[string]: mixed|},
stderr?: OutputStream,
reportDiagnostic?: DiagnosticReporter,
): boolean;

/** An object of stats for the current task. */
declare export interface Stats {
readTime: number;
readCount: number;
writeTime: number;
writeCount: number;
parseTime: number;
parseCount: number;
compileTime: number;
compileCount: number;
emitTime: number;
emitCount: number;
validateTime: number;
validateCount: number;
optimizeTime: number;
optimizeCount: number;
}

/** Creates an empty set of stats. */
declare export function createStats(): Stats;

/** Measures the execution time of the specified function. */
declare export function measure(fn: () => void): number;

/** Formats a high resolution time to a human readable string. */
declare export function formatTime(time: number): string;

/** Formats and prints out the contents of a set of stats. */
declare export function printStats(stats: Stats, output: OutputStream): void;

/** Creates a memory stream that can be used in place of stdout/stderr. */
declare export function createMemoryStream(
fn?: (chunk: Uint8Array | string) => void,
): MemoryStream;

/** Compatible TypeScript compiler options for syntax highlighting etc. */
declare export var tscOptions: {|[string]: any|};
}
2 changes: 2 additions & 0 deletions packages/configs/default/index.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
"*.elm": ["@parcel/transformer-elm"],
"*.mdx": ["@parcel/transformer-mdx"],
"*.vue": ["@parcel/transformer-vue"],
"*.as": ["@parcel/transformer-assemblyscript"],
"*.wasm": ["@parcel/transformer-raw"],
"template:*.vue": ["@parcel/transformer-vue"],
"script:*.vue": ["@parcel/transformer-vue"],
"style:*.vue": ["@parcel/transformer-vue"],
Expand Down
17 changes: 17 additions & 0 deletions packages/examples/assemblyscript/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "@parcel/assemblyscript-example",
"version": "2.0.0-beta.2",
"license": "MIT",
"private": true,
"scripts": {
"demo": "parcel build src/index.html"
},
"browserslist": [
"last 1 Chrome versions"
],
"devDependencies": {
"@parcel/babel-register": "2.0.0-beta.2",
"parcel": "2.0.0-beta.2",
"assemblyscript": "^0.18.24"
}
}
3 changes: 3 additions & 0 deletions packages/examples/assemblyscript/src/addition.as
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function add(a: i32, b: i32): i32 {
return a + b;
}
2 changes: 2 additions & 0 deletions packages/examples/assemblyscript/src/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<!DOCTYPE html>
<script src="./index.js"></script>
5 changes: 5 additions & 0 deletions packages/examples/assemblyscript/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import wasmUrl from './addition.as';

WebAssembly.instantiateStreaming(fetch(wasmUrl)).then(({instance}) =>
console.log(instance.exports.add(40, 2)),
);
32 changes: 32 additions & 0 deletions packages/transformers/assemblyscript/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "@parcel/transformer-assemblyscript",
"version": "2.0.0-beta.1",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/parcel"
},
"repository": {
"type": "git",
"url": "https://github.com/parcel-bundler/parcel.git"
},
"main": "lib/ASTransformer.js",
"source": "src/ASTransformer.js",
"engines": {
"node": ">= 12.0.0",
"parcel": "^2.0.0-alpha.1.1"
},
"peerDependencies": {
"assemblyscript": "^0.18.0"
},
"dependencies": {
"@parcel/plugin": "2.0.0-beta.2"
},
"devDependencies": {
"@parcel/types": "2.0.0-beta.2",
"assemblyscript": "^0.18.24"
}
}
28 changes: 28 additions & 0 deletions packages/transformers/assemblyscript/src/ASTransformer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// @flow strict-local

import {Transformer} from '@parcel/plugin';
import invariant from 'assert';

import * as asc from 'assemblyscript/cli/asc';

export default (new Transformer({
async transform({asset}) {
await asc.ready;

let code = await asset.getCode();
const {binary} = asc.compileString(code, {
// optimize: true,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user should be able to modify the options here

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that's what I meant with

We probably also need a config file for the assemblyscript compiler options

});

invariant(binary);
return [
{
content: Buffer.from(binary),
type: 'wasm',
},
];

// let uniqueKey = "";
// return [asset, ]
},
}): Transformer);
Loading