Skip to content

Commit

Permalink
Support relative import.
Browse files Browse the repository at this point in the history
  • Loading branch information
ry committed May 14, 2018
1 parent 50105d7 commit 362aa67
Show file tree
Hide file tree
Showing 15 changed files with 108 additions and 37 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ msg.pb.js: msg.proto node_modules
msg.pb.d.ts: msg.pb.js node_modules
./node_modules/.bin/pbts -o msg.pb.d.ts msg.pb.js

dist/main.js: main.ts compiler.ts fs.ts util.ts msg.pb.js msg.pb.d.ts node_modules
dist/main.js: main.ts compiler.ts os.ts util.ts msg.pb.js msg.pb.d.ts node_modules
./node_modules/.bin/tsc --noEmit # Only for type checking.
./node_modules/.bin/parcel build --out-dir=dist/ --no-minify main.ts

Expand Down
40 changes: 32 additions & 8 deletions compiler.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,32 @@
import * as ts from "typescript";
import { assert, globalEval } from "./util";
import { readFileSync } from "./fs";
import { exit, readFileSync } from "./os";
import * as path from "path";

export function compile(cwd: string, inputFn: string): void {
const options: ts.CompilerOptions = {
"allowJs": true,
"outFile": "out.js",
allowJs: true,
outFile: "out.js"
};
const host = new CompilerHost(cwd);

let program = ts.createProgram([inputFn], options, host);
const inputExt = path.extname(inputFn);
if (!EXTENSIONS.includes(inputExt)) {
console.error(`Bad file name extension for input "${inputFn}"`);
exit(1);
}

const program = ts.createProgram([inputFn], options, host);
//let sourceFiles = program.getSourceFiles();
//console.log("rootFileNames", program.getRootFileNames());

let emitResult = program.emit();
const emitResult = program.emit();
assert(!emitResult.emitSkipped);
//console.log("emitResult", emitResult);
}

const EXTENSIONS = [".ts", ".js"];

export class CompilerHost {
constructor(public cwd: string) {}

Expand Down Expand Up @@ -101,9 +110,24 @@ export class CompilerHost {
moduleNames: string[],
containingFile: string,
reusedNames?: string[]
): (ts.ResolvedModule | undefined)[] {
console.log("resolveModuleNames", moduleNames);
return [];
): Array<ts.ResolvedModule | undefined> {
console.log("resolveModuleNames", { moduleNames, reusedNames });
return moduleNames.map((name: string) => {
if (
name.startsWith("/") ||
name.startsWith("http:https://") ||
name.startsWith("https://")
) {
throw Error("Non-relative imports not yet supported.");
} else {
// Relative import.
console.log("relative import", { containingFile, name });
const containingDir = path.dirname(containingFile);
const resolvedFileName = path.join(containingDir, name);
const isExternalLibraryImport = false;
return { resolvedFileName, isExternalLibraryImport };
}
});
}

fileExists(fileName: string): boolean {
Expand Down
18 changes: 0 additions & 18 deletions fs.ts

This file was deleted.

4 changes: 4 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,13 @@ func recv(buf []byte) []byte {
switch msg.Kind {
case Msg_READ_FILE_SYNC:
return ReadFileSync(msg.Path)
case Msg_EXIT:
os.Exit(int(msg.Code))
default:
panic("Unexpected message")
}

return nil
}

func loadAsset(w *v8worker2.Worker, path string) {
Expand Down
1 change: 0 additions & 1 deletion main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { main as pb } from "./msg.pb";
import "./util";
import { compile } from "./compiler";


function start(cwd: string, argv: string[]): void {
// TODO parse arguments.
const inputFn = argv[1];
Expand Down
4 changes: 4 additions & 0 deletions msg.proto
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ message Msg {
START = 0;
READ_FILE_SYNC = 1;
DATA_RESPONSE = 2;
EXIT = 3;
}
MsgKind kind = 10;

Expand All @@ -20,4 +21,7 @@ message Msg {
// DATA_RESPONSE
bytes data = 30;
string error = 31;

// EXIT
int32 code = 40;
}
41 changes: 41 additions & 0 deletions os.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { main as pb } from "./msg.pb";
import { TextDecoder } from "text-encoding";

// TODO move this to types.ts
type TypedArray = Uint8Array | Float32Array | Int32Array;

export function exit(code = 0): void {
sendMsgFromObject({
kind: pb.Msg.MsgKind.EXIT,
code
});
}

export function readFileSync(filename: string): string {
const res = sendMsgFromObject({
kind: pb.Msg.MsgKind.READ_FILE_SYNC,
path: filename
});
if (res.error != null && res.error.length > 0) {
throw Error(res.error);
}
const decoder = new TextDecoder("utf8");
return decoder.decode(res.data);
}

function typedArrayToArrayBuffer(ta: TypedArray): ArrayBuffer {
const ab = ta.buffer.slice(ta.byteOffset, ta.byteOffset + ta.byteLength);
return ab as ArrayBuffer;
}

function sendMsgFromObject(obj: pb.IMsg): null | pb.Msg {
const msg = pb.Msg.fromObject(obj);
const ui8 = pb.Msg.encode(msg).finish();
const ab = typedArrayToArrayBuffer(ui8);
const resBuf = V8Worker2.send(ab);
if (resBuf != null && resBuf.byteLength > 0) {
return pb.Msg.decode(new Uint8Array(resBuf));
} else {
return null;
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
3 changes: 3 additions & 0 deletions testdata/003_relative_import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { printHello } from "./subdir/print_hello.ts";

printHello();
1 change: 1 addition & 0 deletions testdata/003_relative_import.ts.out
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello
3 changes: 3 additions & 0 deletions testdata/subdir/print_hello.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function printHello(): void {
console.log("Hello");
}
28 changes: 19 additions & 9 deletions util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,28 @@ const print = V8Worker2.print;
_global["console"] = {
// tslint:disable-next-line:no-any
log(...args: any[]): void {
const out: string[] = [];
for (const a of args) {
if (typeof a === "string") {
out.push(a);
} else {
out.push(JSON.stringify(a));
}
}
print(out.join(" "));
print(stringifyArgs(args));
},

// tslint:disable-next-line:no-any
error(...args: any[]): void {
print("ERROR: " + stringifyArgs(args));
}
};

// tslint:disable-next-line:no-any
function stringifyArgs(args: any[]): string {
const out: string[] = [];
for (const a of args) {
if (typeof a === "string") {
out.push(a);
} else {
out.push(JSON.stringify(a));
}
}
return out.join(" ");
}

export function assert(cond: boolean, msg = "") {
if (!cond) {
throw Error("Assertion failed. " + msg);
Expand Down

0 comments on commit 362aa67

Please sign in to comment.