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

refactor: reorganize TS compiler #5603

Merged
merged 5 commits into from
May 20, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion cli/file_fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,7 @@ impl SourceFileFetcher {
}
}

fn map_file_extension(path: &Path) -> msg::MediaType {
pub fn map_file_extension(path: &Path) -> msg::MediaType {
match path.extension() {
None => msg::MediaType::Unknown,
Some(os_str) => match os_str.to_str() {
Expand Down
81 changes: 20 additions & 61 deletions cli/js/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,15 @@ import { Diagnostic, DiagnosticItem } from "./diagnostics.ts";
import { fromTypeScriptDiagnostic } from "./diagnostics_util.ts";
import { TranspileOnlyResult } from "./ops/runtime_compiler.ts";
import { bootstrapWorkerRuntime } from "./runtime_worker.ts";
import { assert } from "./util.ts";
import * as util from "./util.ts";
import { TextDecoder, TextEncoder } from "./web/text_encoding.ts";
import { assert, log, notImplemented } from "./util.ts";
import { core } from "./core.ts";

const encoder = new TextEncoder();
const decoder = new TextDecoder();

// We really don't want to depend on JSON dispatch during snapshotting, so
// this op exchanges strings with Rust as raw byte arrays.
function getAsset(name: string): string {
const opId = core.ops()["op_fetch_asset"];
// We really don't want to depend on JSON dispatch during snapshotting, so
// this op exchanges strings with Rust as raw byte arrays.
const sourceCodeBytes = core.dispatch(opId, encoder.encode(name));
return decoder.decode(sourceCodeBytes!);
const sourceCodeBytes = core.dispatch(opId, core.encode(name));
return core.decode(sourceCodeBytes!);
}

// Constants used by `normalizeString` and `resolvePath`
Expand Down Expand Up @@ -194,18 +189,6 @@ function getExtension(fileName: string, mediaType: MediaType): ts.Extension {
}
}

/** Because we support providing types for JS files as well as X-TypeScript-Types
* header we might be feeding TS compiler with different files than import specifiers
* suggest. To accomplish that we keep track of two different specifiers:
* - original - the one in import statement (import "./foo.js")
* - mapped - if there's no type directive it's the same as original, otherwise
* it's unresolved specifier for type directive (/// @deno-types="./foo.d.ts")
*/
interface SourceFileSpecifierMap {
original: string;
mapped: string;
}

/** A global cache of module source files that have been loaded.
* This cache will be rewritten to be populated on compiler startup
* with files provided from Rust in request message.
Expand Down Expand Up @@ -329,7 +312,7 @@ class Host implements ts.CompilerHost {
path: string,
configurationText: string
): ConfigureResponse {
util.log("compiler::host.configure", path);
log("compiler::host.configure", path);
assert(configurationText);
const { config, error } = ts.parseConfigFileTextToJson(
path,
Expand Down Expand Up @@ -367,15 +350,15 @@ class Host implements ts.CompilerHost {
/* TypeScript CompilerHost APIs */

fileExists(_fileName: string): boolean {
return util.notImplemented();
return notImplemented();
}

getCanonicalFileName(fileName: string): string {
return fileName;
}

getCompilationSettings(): ts.CompilerOptions {
util.log("compiler::host.getCompilationSettings()");
log("compiler::host.getCompilationSettings()");
return this.#options;
}

Expand All @@ -384,7 +367,7 @@ class Host implements ts.CompilerHost {
}

getDefaultLibFileName(_options: ts.CompilerOptions): string {
util.log("compiler::host.getDefaultLibFileName()");
log("compiler::host.getDefaultLibFileName()");
switch (this.#target) {
case CompilerHostTarget.Main:
case CompilerHostTarget.Runtime:
Expand All @@ -404,7 +387,7 @@ class Host implements ts.CompilerHost {
onError?: (message: string) => void,
shouldCreateNewSourceFile?: boolean
): ts.SourceFile | undefined {
util.log("compiler::host.getSourceFile", fileName);
log("compiler::host.getSourceFile", fileName);
try {
assert(!shouldCreateNewSourceFile);
const sourceFile = fileName.startsWith(ASSETS)
Expand Down Expand Up @@ -436,21 +419,21 @@ class Host implements ts.CompilerHost {
}

readFile(_fileName: string): string | undefined {
return util.notImplemented();
return notImplemented();
}

resolveModuleNames(
moduleNames: string[],
containingFile: string
): Array<ts.ResolvedModuleFull | undefined> {
util.log("compiler::host.resolveModuleNames", {
log("compiler::host.resolveModuleNames", {
moduleNames,
containingFile,
});
return moduleNames.map((specifier) => {
const maybeUrl = SourceFile.getResolvedUrl(specifier, containingFile);

util.log("compiler::host.resolveModuleNames maybeUrl", {
log("compiler::host.resolveModuleNames maybeUrl", {
specifier,
containingFile,
maybeUrl,
Expand Down Expand Up @@ -488,7 +471,7 @@ class Host implements ts.CompilerHost {
_onError?: (message: string) => void,
sourceFiles?: readonly ts.SourceFile[]
): void {
util.log("compiler::host.writeFile", fileName);
log("compiler::host.writeFile", fileName);
this.#writeFile(fileName, data, sourceFiles);
}
}
Expand Down Expand Up @@ -546,30 +529,6 @@ const _TS_SNAPSHOT_PROGRAM = ts.createProgram({
// This function is called only during snapshotting process
const SYSTEM_LOADER = getAsset("system_loader.js");

function getMediaType(filename: string): MediaType {
const maybeExtension = /\.([a-zA-Z]+)$/.exec(filename);
if (!maybeExtension) {
util.log(`!!! Could not identify valid extension: "${filename}"`);
return MediaType.Unknown;
}
const [, extension] = maybeExtension;
switch (extension.toLowerCase()) {
case "js":
return MediaType.JavaScript;
case "jsx":
return MediaType.JSX;
case "ts":
return MediaType.TypeScript;
case "tsx":
return MediaType.TSX;
case "wasm":
return MediaType.Wasm;
default:
util.log(`!!! Unknown extension: "${extension}"`);
return MediaType.Unknown;
}
}

function buildLocalSourceFileCache(
sourceFileMap: Record<string, SourceFileMapEntry>
): void {
Expand All @@ -578,7 +537,7 @@ function buildLocalSourceFileCache(
SourceFile.addToCache({
url: entry.url,
filename: entry.url,
mediaType: getMediaType(entry.url),
mediaType: entry.mediaType,
sourceCode: entry.sourceCode,
});

Expand Down Expand Up @@ -1141,7 +1100,7 @@ function compile(request: CompilerRequestCompile): CompileResult {
cwd,
sourceFileMap,
} = request;
util.log(">>> compile start", {
log(">>> compile start", {
rootNames,
type: CompilerRequestType[request.type],
});
Expand Down Expand Up @@ -1221,7 +1180,7 @@ function compile(request: CompilerRequestCompile): CompileResult {
diagnostics: fromTypeScriptDiagnostic(diagnostics),
};

util.log("<<< compile end", {
log("<<< compile end", {
rootNames,
type: CompilerRequestType[request.type],
});
Expand All @@ -1241,7 +1200,7 @@ function runtimeCompile(
sourceFileMap,
} = request;

util.log(">>> runtime compile start", {
log(">>> runtime compile start", {
rootNames,
bundle,
});
Expand Down Expand Up @@ -1312,7 +1271,7 @@ function runtimeCompile(
assert(emitResult.emitSkipped === false, "Unexpected skip of the emit.");

assert(state.emitMap);
util.log("<<< runtime compile finish", {
log("<<< runtime compile finish", {
rootNames,
bundle,
emitMap: Object.keys(state.emitMap),
Expand Down Expand Up @@ -1385,7 +1344,7 @@ async function tsCompilerOnMessage({
break;
}
default:
util.log(
log(
`!!! unhandled CompilerRequestType: ${
(request as CompilerRequest).type
} (${CompilerRequestType[(request as CompilerRequest).type]})`
Expand Down
6 changes: 4 additions & 2 deletions cli/module_graph.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

use crate::file_fetcher::map_file_extension;
use crate::file_fetcher::SourceFile;
use crate::file_fetcher::SourceFileFetcher;
use crate::import_map::ImportMap;
Expand All @@ -19,6 +20,7 @@ use serde::Serialize;
use serde::Serializer;
use std::collections::HashMap;
use std::hash::BuildHasher;
use std::path::PathBuf;
use std::pin::Pin;

fn serialize_module_specifier<S>(
Expand Down Expand Up @@ -258,9 +260,9 @@ impl ModuleGraphLoader {
ModuleGraphFile {
specifier: specifier.to_string(),
url: specifier.to_string(),
media_type: map_file_extension(&PathBuf::from(specifier.clone()))
as i32,
filename: specifier,
// ignored, it's set in TS worker
media_type: MediaType::JavaScript as i32,
source_code,
imports,
referenced_files,
Expand Down
6 changes: 4 additions & 2 deletions cli/tsc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ struct EmittedSource {
#[serde(rename_all = "camelCase")]
struct BundleResponse {
diagnostics: Diagnostic,
bundle_output: String,
bundle_output: Option<String>,
}

#[derive(Deserialize)]
Expand Down Expand Up @@ -458,7 +458,9 @@ impl TsCompiler {
return Err(ErrBox::from(bundle_response.diagnostics));
}

let output_string = fmt::format_text(&bundle_response.bundle_output)?;
assert!(bundle_response.bundle_output.is_some());
let output = bundle_response.bundle_output.unwrap();
let output_string = fmt::format_text(&output)?;

if let Some(out_file_) = out_file.as_ref() {
eprintln!("Emitting bundle to {:?}", out_file_);
Expand Down