Skip to content

Commit bd54909

Browse files
authored
Misc refactorings (#974)
1 parent b1478ee commit bd54909

File tree

284 files changed

+1738
-1796
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

284 files changed

+1738
-1796
lines changed

cli/asc.js

Lines changed: 87 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ exports.main = function main(argv, options, callback) {
181181
stdout.write("Version " + exports.version + (isDev ? "-dev" : "") + EOL);
182182
return callback(null);
183183
}
184+
184185
// Print the help message if requested or no source files are provided
185186
if (args.help || !argv.length) {
186187
var out = args.help ? stdout : stderr;
@@ -211,6 +212,77 @@ exports.main = function main(argv, options, callback) {
211212
// Set up base directory
212213
const baseDir = args.baseDir ? path.resolve(args.baseDir) : ".";
213214

215+
// Set up options
216+
const compilerOptions = assemblyscript.newOptions();
217+
assemblyscript.setTarget(compilerOptions, 0);
218+
assemblyscript.setNoAssert(compilerOptions, args.noAssert);
219+
assemblyscript.setImportMemory(compilerOptions, args.importMemory);
220+
assemblyscript.setSharedMemory(compilerOptions, args.sharedMemory);
221+
assemblyscript.setImportTable(compilerOptions, args.importTable);
222+
assemblyscript.setExplicitStart(compilerOptions, args.explicitStart);
223+
assemblyscript.setMemoryBase(compilerOptions, args.memoryBase >>> 0);
224+
assemblyscript.setSourceMap(compilerOptions, args.sourceMap != null);
225+
assemblyscript.setNoUnsafe(compilerOptions, args.noUnsafe);
226+
227+
// Initialize default aliases
228+
assemblyscript.setGlobalAlias(compilerOptions, "Math", "NativeMath");
229+
assemblyscript.setGlobalAlias(compilerOptions, "Mathf", "NativeMathf");
230+
assemblyscript.setGlobalAlias(compilerOptions, "abort", "~lib/builtins/abort");
231+
assemblyscript.setGlobalAlias(compilerOptions, "trace", "~lib/builtins/trace");
232+
233+
// Add or override aliases if specified
234+
if (args.use) {
235+
let aliases = args.use;
236+
for (let i = 0, k = aliases.length; i < k; ++i) {
237+
let part = aliases[i];
238+
let p = part.indexOf("=");
239+
if (p < 0) return callback(Error("Global alias '" + part + "' is invalid."));
240+
let alias = part.substring(0, p).trim();
241+
let name = part.substring(p + 1).trim();
242+
if (!alias.length) return callback(Error("Global alias '" + part + "' is invalid."));
243+
assemblyscript.setGlobalAlias(compilerOptions, alias, name);
244+
}
245+
}
246+
247+
// Disable default features if specified
248+
var features;
249+
if ((features = args.disable) != null) {
250+
if (typeof features === "string") features = features.split(",");
251+
for (let i = 0, k = features.length; i < k; ++i) {
252+
let name = features[i].trim();
253+
let flag = assemblyscript["FEATURE_" + name.replace(/\-/g, "_").toUpperCase()];
254+
if (!flag) return callback(Error("Feature '" + name + "' is unknown."));
255+
assemblyscript.disableFeature(compilerOptions, flag);
256+
}
257+
}
258+
259+
// Enable experimental features if specified
260+
if ((features = args.enable) != null) {
261+
if (typeof features === "string") features = features.split(",");
262+
for (let i = 0, k = features.length; i < k; ++i) {
263+
let name = features[i].trim();
264+
let flag = assemblyscript["FEATURE_" + name.replace(/\-/g, "_").toUpperCase()];
265+
if (!flag) return callback(Error("Feature '" + name + "' is unknown."));
266+
assemblyscript.enableFeature(compilerOptions, flag);
267+
}
268+
}
269+
270+
// Set up optimization levels
271+
var optimizeLevel = 0;
272+
var shrinkLevel = 0;
273+
if (args.optimize) {
274+
optimizeLevel = exports.defaultOptimizeLevel;
275+
shrinkLevel = exports.defaultShrinkLevel;
276+
}
277+
if (typeof args.optimizeLevel === "number") optimizeLevel = args.optimizeLevel;
278+
if (typeof args.shrinkLevel === "number") shrinkLevel = args.shrinkLevel;
279+
optimizeLevel = Math.min(Math.max(optimizeLevel, 0), 3);
280+
shrinkLevel = Math.min(Math.max(shrinkLevel, 0), 2);
281+
assemblyscript.setOptimizeLevelHints(compilerOptions, optimizeLevel, shrinkLevel);
282+
283+
// Initialize the program
284+
const program = assemblyscript.newProgram(compilerOptions);
285+
214286
// Set up transforms
215287
const transforms = [];
216288
if (args.transform) {
@@ -222,6 +294,7 @@ exports.main = function main(argv, options, callback) {
222294
const classOrModule = require(require.resolve(filename, { paths: [baseDir, process.cwd()] }));
223295
if (typeof classOrModule === "function") {
224296
Object.assign(classOrModule.prototype, {
297+
program,
225298
baseDir,
226299
stdout,
227300
stderr,
@@ -252,15 +325,12 @@ exports.main = function main(argv, options, callback) {
252325
}
253326
}
254327

255-
// Begin parsing
256-
var parser = null;
257-
258-
// Include library files
328+
// Parse library files
259329
Object.keys(exports.libraryFiles).forEach(libPath => {
260330
if (libPath.indexOf("/") >= 0) return; // in sub-directory: imported on demand
261331
stats.parseCount++;
262332
stats.parseTime += measure(() => {
263-
parser = assemblyscript.parseFile(exports.libraryFiles[libPath], exports.libraryPrefix + libPath + ".ts", false, parser);
333+
assemblyscript.parse(program, exports.libraryFiles[libPath], exports.libraryPrefix + libPath + ".ts", false);
264334
});
265335
});
266336
const customLibDirs = [];
@@ -284,7 +354,7 @@ exports.main = function main(argv, options, callback) {
284354
stats.parseCount++;
285355
exports.libraryFiles[libPath.replace(/\.ts$/, "")] = libText;
286356
stats.parseTime += measure(() => {
287-
parser = assemblyscript.parseFile(libText, exports.libraryPrefix + libPath, false, parser);
357+
assemblyscript.parse(program, libText, exports.libraryPrefix + libPath, false);
288358
});
289359
}
290360
}
@@ -393,15 +463,15 @@ exports.main = function main(argv, options, callback) {
393463
// Parses the backlog of imported files after including entry files
394464
function parseBacklog() {
395465
var internalPath;
396-
while ((internalPath = parser.nextFile()) != null) {
397-
let file = getFile(internalPath, assemblyscript.getDependee(parser, internalPath));
466+
while ((internalPath = assemblyscript.nextFile(program)) != null) {
467+
let file = getFile(internalPath, assemblyscript.getDependee(program, internalPath));
398468
if (!file) return callback(Error("Import file '" + internalPath + ".ts' not found."))
399469
stats.parseCount++;
400470
stats.parseTime += measure(() => {
401-
assemblyscript.parseFile(file.sourceText, file.sourcePath, false, parser);
471+
assemblyscript.parse(program, file.sourceText, file.sourcePath, false);
402472
});
403473
}
404-
if (checkDiagnostics(parser, stderr)) return callback(Error("Parse error"));
474+
if (checkDiagnostics(program, stderr)) return callback(Error("Parse error"));
405475
}
406476

407477
// Include runtime template before entry files so its setup runs first
@@ -418,7 +488,7 @@ exports.main = function main(argv, options, callback) {
418488
}
419489
stats.parseCount++;
420490
stats.parseTime += measure(() => {
421-
parser = assemblyscript.parseFile(runtimeText, runtimePath, true, parser);
491+
assemblyscript.parse(program, runtimeText, runtimePath, true);
422492
});
423493
}
424494

@@ -442,7 +512,7 @@ exports.main = function main(argv, options, callback) {
442512

443513
stats.parseCount++;
444514
stats.parseTime += measure(() => {
445-
parser = assemblyscript.parseFile(sourceText, sourcePath, true, parser);
515+
assemblyscript.parse(program, sourceText, sourcePath, true);
446516
});
447517
}
448518

@@ -454,7 +524,7 @@ exports.main = function main(argv, options, callback) {
454524

455525
// Call afterParse transform hook
456526
{
457-
let error = applyTransform("afterParse", parser);
527+
let error = applyTransform("afterParse", program.parser);
458528
if (error) return callback(error);
459529
}
460530

@@ -464,9 +534,6 @@ exports.main = function main(argv, options, callback) {
464534
if (code) return code;
465535
}
466536

467-
// Finish parsing
468-
const program = assemblyscript.finishParsing(parser);
469-
470537
// Print files and exit if listFiles
471538
if (args.listFiles) {
472539
// FIXME: not a proper C-like API
@@ -490,72 +557,16 @@ exports.main = function main(argv, options, callback) {
490557
optimizeLevel = Math.min(Math.max(optimizeLevel, 0), 3);
491558
shrinkLevel = Math.min(Math.max(shrinkLevel, 0), 2);
492559

493-
// Begin compilation
494-
const compilerOptions = assemblyscript.createOptions();
495-
assemblyscript.setTarget(compilerOptions, 0);
496-
assemblyscript.setNoAssert(compilerOptions, args.noAssert);
497-
assemblyscript.setImportMemory(compilerOptions, args.importMemory);
498-
assemblyscript.setSharedMemory(compilerOptions, args.sharedMemory);
499-
assemblyscript.setImportTable(compilerOptions, args.importTable);
500-
assemblyscript.setExplicitStart(compilerOptions, args.explicitStart);
501-
assemblyscript.setMemoryBase(compilerOptions, args.memoryBase >>> 0);
502-
assemblyscript.setSourceMap(compilerOptions, args.sourceMap != null);
503-
assemblyscript.setOptimizeLevelHints(compilerOptions, optimizeLevel, shrinkLevel);
504-
assemblyscript.setNoUnsafe(compilerOptions, args.noUnsafe);
505-
506-
// Initialize default aliases
507-
assemblyscript.setGlobalAlias(compilerOptions, "Math", "NativeMath");
508-
assemblyscript.setGlobalAlias(compilerOptions, "Mathf", "NativeMathf");
509-
assemblyscript.setGlobalAlias(compilerOptions, "abort", "~lib/builtins/abort");
510-
assemblyscript.setGlobalAlias(compilerOptions, "trace", "~lib/builtins/trace");
511-
512-
// Add or override aliases if specified
513-
if (args.use) {
514-
let aliases = args.use;
515-
for (let i = 0, k = aliases.length; i < k; ++i) {
516-
let part = aliases[i];
517-
let p = part.indexOf("=");
518-
if (p < 0) return callback(Error("Global alias '" + part + "' is invalid."));
519-
let alias = part.substring(0, p).trim();
520-
let name = part.substring(p + 1).trim();
521-
if (!alias.length) return callback(Error("Global alias '" + part + "' is invalid."));
522-
assemblyscript.setGlobalAlias(compilerOptions, alias, name);
523-
}
524-
}
525-
526-
// Disable default features if specified
527-
var features;
528-
if ((features = args.disable) != null) {
529-
if (typeof features === "string") features = features.split(",");
530-
for (let i = 0, k = features.length; i < k; ++i) {
531-
let name = features[i].trim();
532-
let flag = assemblyscript["FEATURE_" + name.replace(/\-/g, "_").toUpperCase()];
533-
if (!flag) return callback(Error("Feature '" + name + "' is unknown."));
534-
assemblyscript.disableFeature(compilerOptions, flag);
535-
}
536-
}
537-
538-
// Enable experimental features if specified
539-
if ((features = args.enable) != null) {
540-
if (typeof features === "string") features = features.split(",");
541-
for (let i = 0, k = features.length; i < k; ++i) {
542-
let name = features[i].trim();
543-
let flag = assemblyscript["FEATURE_" + name.replace(/\-/g, "_").toUpperCase()];
544-
if (!flag) return callback(Error("Feature '" + name + "' is unknown."));
545-
assemblyscript.enableFeature(compilerOptions, flag);
546-
}
547-
}
548-
549560
var module;
550561
stats.compileCount++;
551562
try {
552563
stats.compileTime += measure(() => {
553-
module = assemblyscript.compileProgram(program, compilerOptions);
564+
module = assemblyscript.compile(program);
554565
});
555566
} catch (e) {
556567
return callback(e);
557568
}
558-
if (checkDiagnostics(parser, stderr)) {
569+
if (checkDiagnostics(program, stderr)) {
559570
if (module) module.dispose();
560571
return callback(Error("Compile error"));
561572
}
@@ -944,10 +955,10 @@ exports.main = function main(argv, options, callback) {
944955
}
945956

946957
/** Checks diagnostics emitted so far for errors. */
947-
function checkDiagnostics(emitter, stderr) {
958+
function checkDiagnostics(program, stderr) {
948959
var diagnostic;
949960
var hasErrors = false;
950-
while ((diagnostic = assemblyscript.nextDiagnostic(emitter)) != null) {
961+
while ((diagnostic = assemblyscript.nextDiagnostic(program)) != null) {
951962
if (stderr) {
952963
stderr.write(
953964
assemblyscript.formatDiagnostic(diagnostic, stderr.isTTY, true) +

cli/transform.d.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,14 @@
33
* @module cli/transform
44
*//***/
55

6-
import { Parser, Module } from "..";
6+
import { Program, Parser, Module } from "..";
77
import { OutputStream } from "./asc";
88

99
export abstract class Transform {
1010

11+
/** Program reference. */
12+
readonly program: Program;
13+
1114
/** Base directory. */
1215
readonly baseDir: string;
1316

src/builtins.ts

Lines changed: 0 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -150,8 +150,6 @@ export namespace BuiltinSymbols {
150150
export const changetype = "~lib/builtins/changetype";
151151
export const assert = "~lib/builtins/assert";
152152
export const unchecked = "~lib/builtins/unchecked";
153-
export const call_direct = "~lib/builtins/call_direct";
154-
export const call_indirect = "~lib/builtins/call_indirect";
155153
export const instantiate = "~lib/builtins/instantiate";
156154
export const idof = "~lib/builtins/idof";
157155

@@ -2309,60 +2307,6 @@ export function compileCall(
23092307
if (!alreadyUnchecked) flow.unset(FlowFlags.UNCHECKED_CONTEXT);
23102308
return expr;
23112309
}
2312-
case BuiltinSymbols.call_direct:
2313-
case BuiltinSymbols.call_indirect: { // call_indirect<T?>(target: Function | u32, ...args: *[]) -> T
2314-
if (
2315-
checkTypeOptional(typeArguments, reportNode, compiler, true) |
2316-
checkArgsOptional(operands, 1, i32.MAX_VALUE, reportNode, compiler)
2317-
) return module.unreachable();
2318-
let returnType = typeArguments ? typeArguments[0] : contextualType;
2319-
let arg0 = compiler.compileExpression(operands[0], Type.u32);
2320-
let arg0Type = compiler.currentType;
2321-
if (!(
2322-
arg0Type == Type.u32 || // either plain index
2323-
arg0Type.kind == TypeKind.U32 && arg0Type.signatureReference // or function reference
2324-
)) {
2325-
compiler.error(
2326-
DiagnosticCode.Type_0_is_not_a_function_index_or_function_reference,
2327-
operands[0].range, arg0Type.toString()
2328-
);
2329-
return module.unreachable();
2330-
}
2331-
let numOperands = operands.length - 1;
2332-
let operandExprs = new Array<ExpressionRef>(numOperands);
2333-
let nativeReturnType = returnType.toNativeType();
2334-
let parameterTypes = new Array<Type>(numOperands);
2335-
let nativeParamTypes = new Array<NativeType>(numOperands);
2336-
for (let i = 0; i < numOperands; ++i) {
2337-
operandExprs[i] = compiler.compileExpression(operands[1 + i], Type.i32);
2338-
let operandType = compiler.currentType;
2339-
parameterTypes[i] = operandType;
2340-
nativeParamTypes[i] = operandType.toNativeType();
2341-
}
2342-
let typeName = Signature.makeSignatureString(parameterTypes, returnType);
2343-
let typeRef = module.getFunctionTypeBySignature(nativeReturnType, nativeParamTypes);
2344-
if (!typeRef) typeRef = module.addFunctionType(typeName, nativeReturnType, nativeParamTypes);
2345-
compiler.currentType = returnType;
2346-
if (prototype.internalName == BuiltinSymbols.call_direct) {
2347-
// if the index expression is precomputable to a constant value, emit a direct call
2348-
if (getExpressionId(arg0 = module.precomputeExpression(arg0)) == ExpressionId.Const) {
2349-
assert(getExpressionType(arg0) == NativeType.I32);
2350-
let index = getConstValueI32(arg0);
2351-
let functionTable = compiler.functionTable;
2352-
if (index >= 0 && index < functionTable.length) {
2353-
return module.call(functionTable[index], operandExprs, nativeReturnType);
2354-
}
2355-
}
2356-
compiler.error(
2357-
DiagnosticCode.Expression_must_be_a_compile_time_constant,
2358-
operands[0].range
2359-
);
2360-
return module.unreachable();
2361-
}
2362-
// of course this can easily result in a 'RuntimeError: function signature mismatch' trap and
2363-
// thus must be used with care. it exists because it *might* be useful in specific scenarios.
2364-
return module.call_indirect(arg0, operandExprs, typeName);
2365-
}
23662310
case BuiltinSymbols.instantiate: { // instantiate<T!>(...args: *[]) -> T
23672311
if (
23682312
checkTypeRequired(typeArguments, reportNode, compiler, true)

src/common.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,8 @@ export enum CommonFlags {
7070
TRAMPOLINE = 1 << 25,
7171
/** Is a virtual method. */
7272
VIRTUAL = 1 << 26,
73-
/** Is the main function. */
74-
MAIN = 1 << 27,
73+
/** Is (part of) a closure. */
74+
CLOSURE = 1 << 27,
7575

7676
// Other
7777

0 commit comments

Comments
 (0)