Skip to content

Commit

Permalink
Create an old program to be used in snapshot. (denoland#3644)
Browse files Browse the repository at this point in the history
  • Loading branch information
kitsonk authored and bartlomieju committed Jan 12, 2020
1 parent 8fac8ab commit 737ab94
Show file tree
Hide file tree
Showing 14 changed files with 85 additions and 60 deletions.
10 changes: 0 additions & 10 deletions cli/js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,6 @@ pub static COMPILER_SNAPSHOT_MAP: &[u8] =
pub static COMPILER_SNAPSHOT_DTS: &[u8] =
include_bytes!(concat!(env!("OUT_DIR"), "/COMPILER_SNAPSHOT.d.ts"));

static DENO_RUNTIME: &str = include_str!("js/lib.deno_runtime.d.ts");

/// Same as deno_typescript::get_asset but also has lib.deno_runtime.d.ts
pub fn get_asset(name: &str) -> Option<&'static str> {
match name {
"lib.deno_runtime.d.ts" => Some(DENO_RUNTIME),
_ => deno_typescript::get_asset(name),
}
}

#[test]
fn cli_snapshot() {
let mut isolate = deno_core::Isolate::new(
Expand Down
19 changes: 13 additions & 6 deletions cli/js/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import "./globals.ts";
import "./ts_global.d.ts";

import { TranspileOnlyResult } from "./compiler_api.ts";
import { oldProgram } from "./compiler_bootstrap.ts";
import { setRootExports } from "./compiler_bundler.ts";
import {
defaultBundlerOptions,
Expand Down Expand Up @@ -73,7 +74,7 @@ interface CompileResult {

// bootstrap the runtime environment, this gets called as the isolate is setup
self.denoMain = function denoMain(compilerType?: string): void {
os.start(true, compilerType || "TS");
os.start(true, compilerType ?? "TS");
};

// bootstrap the worker environment, this gets called as the isolate is setup
Expand Down Expand Up @@ -135,7 +136,12 @@ self.compilerMain = function compilerMain(): void {
// to generate the program and possibly emit it.
if (!diagnostics || (diagnostics && diagnostics.length === 0)) {
const options = host.getCompilationSettings();
const program = ts.createProgram(rootNames, options, host);
const program = ts.createProgram({
rootNames,
options,
host,
oldProgram
});

diagnostics = ts
.getPreEmitDiagnostics(program)
Expand Down Expand Up @@ -213,11 +219,12 @@ self.compilerMain = function compilerMain(): void {
}
host.mergeOptions(...compilerOptions);

const program = ts.createProgram(
const program = ts.createProgram({
rootNames,
host.getCompilationSettings(),
host
);
options: host.getCompilationSettings(),
host,
oldProgram
});

if (bundle) {
setRootExports(program, rootNames[0]);
Expand Down
34 changes: 34 additions & 0 deletions cli/js/compiler_bootstrap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

import { ASSETS, Host } from "./compiler_host.ts";
import { core } from "./core.ts";
import * as dispatch from "./dispatch.ts";
import { sendSync } from "./dispatch_json.ts";

// This registers ops that are available during the snapshotting process.
const ops = core.ops();
for (const [name, opId] of Object.entries(ops)) {
const opName = `OP_${name.toUpperCase()}`;
// TODO This type casting is dangerous, and should be improved when the same
// code in `os.ts` is done.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(dispatch as any)[opName] = opId;
}

const host = new Host({ writeFile(): void {} });
const options = host.getCompilationSettings();

/** Used to generate the foundational AST for all other compilations, so it can
* be cached as part of the snapshot and available to speed up startup */
export const oldProgram = ts.createProgram({
rootNames: [`${ASSETS}/bootstrap.ts`],
options,
host
});

/** A module loader which is concatenated into bundle files. We read all static
* assets during the snapshotting process, which is why this is located in
* compiler_bootstrap. */
export const bundleLoader = sendSync(dispatch.OP_FETCH_ASSET, {
name: "bundle_loader.js"
});
14 changes: 1 addition & 13 deletions cli/js/compiler_bundler.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

import * as dispatch from "./dispatch.ts";
import { sendSync } from "./dispatch_json.ts";
import { bundleLoader } from "./compiler_bootstrap.ts";
import {
assert,
commonPath,
normalizeString,
CHAR_FORWARD_SLASH
} from "./util.ts";

const BUNDLE_LOADER = "bundle_loader.js";

/** A loader of bundled modules that we will inline into any bundle outputs. */
let bundleLoader: string;

/** Local state of what the root exports are of a root module. */
let rootExports: string[] | undefined;

Expand All @@ -40,12 +34,6 @@ export function buildBundle(
data: string,
sourceFiles: readonly ts.SourceFile[]
): string {
// we can only do this once we are bootstrapped and easiest way to do it is
// inline here
if (!bundleLoader) {
bundleLoader = sendSync(dispatch.OP_FETCH_ASSET, { name: BUNDLE_LOADER });
}

// when outputting to AMD and a single outfile, TypeScript makes up the module
// specifiers which are used to define the modules, and doesn't expose them
// publicly, so we have to try to replicate
Expand Down
10 changes: 6 additions & 4 deletions cli/js/compiler_host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export interface ConfigureResponse {
diagnostics?: ts.Diagnostic[];
}

const ASSETS = "$asset$";
export const ASSETS = "$asset$";

/** Options that need to be used when generating a bundle (either trusted or
* runtime). */
Expand Down Expand Up @@ -129,11 +129,11 @@ export class Host implements ts.CompilerHost {
private _writeFile: WriteFileCallback;

private _getAsset(filename: string): SourceFile {
const sourceFile = SourceFile.get(filename);
const url = filename.split("/").pop()!;
const sourceFile = SourceFile.get(url);
if (sourceFile) {
return sourceFile;
}
const url = filename.split("/").pop()!;
const name = url.includes(".") ? url : `${url}.d.ts`;
const sourceCode = sendSync(dispatch.OP_FETCH_ASSET, { name });
return new SourceFile({
Expand Down Expand Up @@ -238,13 +238,15 @@ export class Host implements ts.CompilerHost {
: SourceFile.get(fileName);
assert(sourceFile != null);
if (!sourceFile.tsSourceFile) {
assert(sourceFile.sourceCode != null);
sourceFile.tsSourceFile = ts.createSourceFile(
fileName,
sourceFile.sourceCode,
languageVersion
);
delete sourceFile.sourceCode;
}
return sourceFile!.tsSourceFile;
return sourceFile.tsSourceFile;
} catch (e) {
if (onError) {
onError(String(e));
Expand Down
2 changes: 1 addition & 1 deletion cli/js/compiler_sourcefile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export class SourceFile {

mediaType!: MediaType;
processed = false;
sourceCode!: string;
sourceCode?: string;
tsSourceFile?: ts.SourceFile;
url!: string;

Expand Down
5 changes: 4 additions & 1 deletion cli/js/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,16 @@ export let OP_READ_LINK: number;
export let OP_TRUNCATE: number;
export let OP_MAKE_TEMP_DIR: number;
export let OP_CWD: number;
export let OP_FETCH_ASSET: number;
export let OP_DIAL_TLS: number;
export let OP_HOSTNAME: number;
export let OP_OPEN_PLUGIN: number;
export let OP_COMPILE: number;
export let OP_TRANSPILE: number;

/** **WARNING:** This is only available during the snapshotting process and is
* unavailable at runtime. */
export let OP_FETCH_ASSET: number;

const PLUGIN_ASYNC_HANDLER_MAP: Map<number, AsyncHandler> = new Map();

export function setPluginAsyncHandler(
Expand Down
2 changes: 1 addition & 1 deletion cli/js/dispatch_json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export function sendSync(
const resUi8 = core.dispatch(opId, argsUi8, zeroCopy);
util.assert(resUi8 != null);

const res = decode(resUi8!);
const res = decode(resUi8);
util.assert(res.promiseId == null);
return unwrapResponse(res);
}
Expand Down
2 changes: 1 addition & 1 deletion cli/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ fn create_worker_and_state(
}

fn types_command() {
let content = crate::js::get_asset("lib.deno_runtime.d.ts").unwrap();
let content = deno_typescript::get_asset("lib.deno_runtime.d.ts").unwrap();
println!("{}", content);
}

Expand Down
22 changes: 0 additions & 22 deletions cli/ops/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,6 @@ pub fn init(i: &mut Isolate, s: &ThreadSafeState) {
"fetch_source_files",
s.core_op(json_op(s.stateful_op(op_fetch_source_files))),
);
i.register_op(
"fetch_asset",
s.core_op(json_op(s.stateful_op(op_fetch_asset))),
);
i.register_op("compile", s.core_op(json_op(s.stateful_op(op_compile))));
i.register_op("transpile", s.core_op(json_op(s.stateful_op(op_transpile))));
}
Expand Down Expand Up @@ -155,24 +151,6 @@ fn op_fetch_source_files(
Ok(JsonOp::Async(future))
}

#[derive(Deserialize)]
struct FetchAssetArgs {
name: String,
}

fn op_fetch_asset(
_state: &ThreadSafeState,
args: Value,
_zero_copy: Option<PinnedBuf>,
) -> Result<JsonOp, ErrBox> {
let args: FetchAssetArgs = serde_json::from_value(args)?;
if let Some(source_code) = crate::js::get_asset(&args.name) {
Ok(JsonOp::Sync(json!(source_code)))
} else {
panic!("op_fetch_asset bad asset {}", args.name)
}
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct CompileArgs {
Expand Down
1 change: 1 addition & 0 deletions core/isolate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,7 @@ impl Isolate {
let mut hs = v8::HandleScope::new(&mut locker);
let scope = hs.enter();
self.global_context.reset(scope);
self.shared_response_buf.reset(scope);

let snapshot_creator = self.snapshot_creator.as_mut().unwrap();
let snapshot = snapshot_creator
Expand Down
1 change: 0 additions & 1 deletion core/shared_queue.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,6 @@ SharedQueue Binary Layout
}

function dispatch(opId, control, zeroCopy = null) {
maybeInit();
return Deno.core.send(opId, control, zeroCopy);
}

Expand Down
8 changes: 8 additions & 0 deletions deno_typescript/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,10 @@ pub fn mksnapshot_bundle_ts(
state: Arc<Mutex<TSState>>,
) -> Result<(), ErrBox> {
let runtime_isolate = &mut Isolate::new(StartupData::None, true);
runtime_isolate.register_op(
"fetch_asset",
compiler_op(state.clone(), ops::json_op(ops::fetch_asset)),
);
let source_code_vec = std::fs::read(bundle)?;
let source_code = std::str::from_utf8(&source_code_vec)?;

Expand Down Expand Up @@ -257,6 +261,10 @@ pub fn get_asset(name: &str) -> Option<&'static str> {
match name {
"bundle_loader.js" => Some(include_str!("bundle_loader.js")),
"lib.deno_core.d.ts" => Some(include_str!("lib.deno_core.d.ts")),
"lib.deno_runtime.d.ts" => {
Some(include_str!("../cli/js/lib.deno_runtime.d.ts"))
}
"bootstrap.ts" => Some("console.log(\"hello deno\");"),
"typescript.d.ts" => inc!("typescript.d.ts"),
"lib.esnext.d.ts" => inc!("lib.esnext.d.ts"),
"lib.es2020.d.ts" => inc!("lib.es2020.d.ts"),
Expand Down
15 changes: 15 additions & 0 deletions deno_typescript/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,21 @@ pub fn resolve_module_names(
Ok(json!(resolved))
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct FetchAssetArgs {
name: String,
}

pub fn fetch_asset(_s: &mut TSState, v: Value) -> Result<Value, ErrBox> {
let args: FetchAssetArgs = serde_json::from_value(v)?;
if let Some(source_code) = crate::get_asset(&args.name) {
Ok(json!(source_code))
} else {
panic!("op_fetch_asset bad asset {}", args.name)
}
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Exit {
Expand Down

0 comments on commit 737ab94

Please sign in to comment.