2021-01-11 12:13:41 -05:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
2020-09-14 08:27:44 -04:00
|
|
|
|
2021-05-10 12:16:39 -04:00
|
|
|
use crate::config_file;
|
2020-09-15 10:33:14 -04:00
|
|
|
use crate::media_type::MediaType;
|
2021-08-16 03:28:29 -04:00
|
|
|
use crate::text_encoding::strip_bom;
|
2020-09-24 18:31:17 -04:00
|
|
|
|
2020-09-14 12:48:57 -04:00
|
|
|
use deno_core::error::AnyError;
|
2021-02-17 13:47:18 -05:00
|
|
|
use deno_core::resolve_url_or_path;
|
2020-10-19 23:10:42 -04:00
|
|
|
use deno_core::serde_json;
|
2020-09-14 08:27:44 -04:00
|
|
|
use deno_core::ModuleSpecifier;
|
|
|
|
use std::error::Error;
|
|
|
|
use std::fmt;
|
2020-11-27 14:14:54 -05:00
|
|
|
use std::ops::Range;
|
2020-09-14 08:27:44 -04:00
|
|
|
use std::rc::Rc;
|
2021-08-06 10:36:16 -04:00
|
|
|
use std::sync::Arc;
|
2020-09-14 08:27:44 -04:00
|
|
|
use swc_common::chain;
|
|
|
|
use swc_common::comments::Comment;
|
2020-11-27 14:14:54 -05:00
|
|
|
use swc_common::comments::CommentKind;
|
2021-08-06 10:36:16 -04:00
|
|
|
use swc_common::comments::Comments;
|
2020-09-14 08:27:44 -04:00
|
|
|
use swc_common::comments::SingleThreadedComments;
|
2021-08-06 10:36:16 -04:00
|
|
|
use swc_common::BytePos;
|
2020-09-14 08:27:44 -04:00
|
|
|
use swc_common::FileName;
|
|
|
|
use swc_common::Globals;
|
2020-10-19 23:10:42 -04:00
|
|
|
use swc_common::SourceFile;
|
2020-09-14 08:27:44 -04:00
|
|
|
use swc_common::SourceMap;
|
|
|
|
use swc_common::Span;
|
2021-06-11 09:03:42 -04:00
|
|
|
use swc_common::Spanned;
|
2020-09-14 08:27:44 -04:00
|
|
|
use swc_ecmascript::ast::Module;
|
|
|
|
use swc_ecmascript::ast::Program;
|
|
|
|
use swc_ecmascript::codegen::text_writer::JsWriter;
|
|
|
|
use swc_ecmascript::codegen::Node;
|
|
|
|
use swc_ecmascript::dep_graph::analyze_dependencies;
|
|
|
|
use swc_ecmascript::dep_graph::DependencyDescriptor;
|
|
|
|
use swc_ecmascript::parser::lexer::Lexer;
|
2020-11-27 14:14:54 -05:00
|
|
|
use swc_ecmascript::parser::token::Token;
|
2020-09-14 08:27:44 -04:00
|
|
|
use swc_ecmascript::parser::EsConfig;
|
|
|
|
use swc_ecmascript::parser::JscTarget;
|
|
|
|
use swc_ecmascript::parser::StringInput;
|
|
|
|
use swc_ecmascript::parser::Syntax;
|
|
|
|
use swc_ecmascript::parser::TsConfig;
|
|
|
|
use swc_ecmascript::transforms::fixer;
|
|
|
|
use swc_ecmascript::transforms::helpers;
|
2020-12-02 14:26:04 -05:00
|
|
|
use swc_ecmascript::transforms::hygiene;
|
2020-09-14 08:27:44 -04:00
|
|
|
use swc_ecmascript::transforms::pass::Optional;
|
2020-10-19 23:10:42 -04:00
|
|
|
use swc_ecmascript::transforms::proposals;
|
2020-09-14 08:27:44 -04:00
|
|
|
use swc_ecmascript::transforms::react;
|
|
|
|
use swc_ecmascript::transforms::typescript;
|
|
|
|
use swc_ecmascript::visit::FoldWith;
|
|
|
|
|
2021-08-06 10:36:16 -04:00
|
|
|
mod bundle_hook;
|
|
|
|
mod comments;
|
|
|
|
mod source_file_info;
|
2021-06-24 09:00:46 -04:00
|
|
|
mod transforms;
|
|
|
|
|
2021-08-06 10:36:16 -04:00
|
|
|
pub use bundle_hook::BundleHook;
|
|
|
|
use comments::MultiThreadedComments;
|
|
|
|
use source_file_info::SourceFileInfo;
|
|
|
|
|
2020-09-14 08:27:44 -04:00
|
|
|
static TARGET: JscTarget = JscTarget::Es2020;
|
|
|
|
|
2020-09-14 17:59:49 -04:00
|
|
|
#[derive(Debug, Clone, Eq, PartialEq)]
|
2020-09-14 08:27:44 -04:00
|
|
|
pub struct Location {
|
2021-08-06 10:36:16 -04:00
|
|
|
pub specifier: String,
|
2020-09-14 08:27:44 -04:00
|
|
|
pub line: usize,
|
|
|
|
pub col: usize,
|
|
|
|
}
|
|
|
|
|
2021-03-25 14:17:37 -04:00
|
|
|
impl From<swc_common::Loc> for Location {
|
|
|
|
fn from(swc_loc: swc_common::Loc) -> Self {
|
2020-09-14 08:27:44 -04:00
|
|
|
use swc_common::FileName::*;
|
|
|
|
|
2021-03-25 14:17:37 -04:00
|
|
|
let filename = match &swc_loc.file.name {
|
2020-09-14 08:27:44 -04:00
|
|
|
Real(path_buf) => path_buf.to_string_lossy().to_string(),
|
|
|
|
Custom(str_) => str_.to_string(),
|
|
|
|
_ => panic!("invalid filename"),
|
|
|
|
};
|
|
|
|
|
|
|
|
Location {
|
2021-08-06 10:36:16 -04:00
|
|
|
specifier: filename,
|
2021-03-25 14:17:37 -04:00
|
|
|
line: swc_loc.line,
|
|
|
|
col: swc_loc.col_display,
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-25 14:17:37 -04:00
|
|
|
impl From<Location> for ModuleSpecifier {
|
|
|
|
fn from(loc: Location) -> Self {
|
2021-08-06 10:36:16 -04:00
|
|
|
resolve_url_or_path(&loc.specifier).unwrap()
|
2020-10-22 20:50:15 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::fmt::Display for Location {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
2021-08-06 10:36:16 -04:00
|
|
|
write!(f, "{}:{}:{}", self.specifier, self.line, self.col)
|
2020-10-22 20:50:15 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-11 09:03:42 -04:00
|
|
|
/// A diagnostic from the AST parser.
|
|
|
|
#[derive(Debug, Clone, Eq, PartialEq)]
|
|
|
|
pub struct Diagnostic {
|
|
|
|
pub location: Location,
|
|
|
|
pub message: String,
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
|
2021-06-11 09:03:42 -04:00
|
|
|
impl Error for Diagnostic {}
|
2020-09-14 08:27:44 -04:00
|
|
|
|
2021-06-11 09:03:42 -04:00
|
|
|
impl fmt::Display for Diagnostic {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
write!(f, "{} at {}", self.message, self.location)
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_es_config(jsx: bool) -> EsConfig {
|
|
|
|
EsConfig {
|
|
|
|
class_private_methods: true,
|
|
|
|
class_private_props: true,
|
|
|
|
class_props: true,
|
|
|
|
dynamic_import: true,
|
|
|
|
export_default_from: true,
|
|
|
|
export_namespace_from: true,
|
|
|
|
import_meta: true,
|
|
|
|
jsx,
|
|
|
|
nullish_coalescing: true,
|
|
|
|
num_sep: true,
|
|
|
|
optional_chaining: true,
|
|
|
|
top_level_await: true,
|
|
|
|
..EsConfig::default()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_ts_config(tsx: bool, dts: bool) -> TsConfig {
|
|
|
|
TsConfig {
|
|
|
|
decorators: true,
|
|
|
|
dts,
|
|
|
|
dynamic_import: true,
|
|
|
|
tsx,
|
|
|
|
..TsConfig::default()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get_syntax(media_type: &MediaType) -> Syntax {
|
|
|
|
match media_type {
|
|
|
|
MediaType::JavaScript => Syntax::Es(get_es_config(false)),
|
2021-03-25 14:17:37 -04:00
|
|
|
MediaType::Jsx => Syntax::Es(get_es_config(true)),
|
2020-09-14 08:27:44 -04:00
|
|
|
MediaType::TypeScript => Syntax::Typescript(get_ts_config(false, false)),
|
|
|
|
MediaType::Dts => Syntax::Typescript(get_ts_config(false, true)),
|
2021-03-25 14:17:37 -04:00
|
|
|
MediaType::Tsx => Syntax::Typescript(get_ts_config(true, false)),
|
2020-09-14 08:27:44 -04:00
|
|
|
_ => Syntax::Es(get_es_config(false)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-07 15:40:11 -05:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
pub enum ImportsNotUsedAsValues {
|
|
|
|
Remove,
|
|
|
|
Preserve,
|
|
|
|
Error,
|
|
|
|
}
|
|
|
|
|
2020-09-14 08:27:44 -04:00
|
|
|
/// Options which can be adjusted when transpiling a module.
|
|
|
|
#[derive(Debug, Clone)]
|
2020-10-19 23:10:42 -04:00
|
|
|
pub struct EmitOptions {
|
2020-09-14 08:27:44 -04:00
|
|
|
/// When emitting a legacy decorator, also emit experimental decorator meta
|
|
|
|
/// data. Defaults to `false`.
|
|
|
|
pub emit_metadata: bool,
|
2021-03-07 15:40:11 -05:00
|
|
|
/// What to do with import statements that only import types i.e. whether to
|
|
|
|
/// remove them (`Remove`), keep them as side-effect imports (`Preserve`)
|
|
|
|
/// or error (`Error`). Defaults to `Remove`.
|
|
|
|
pub imports_not_used_as_values: ImportsNotUsedAsValues,
|
2020-09-14 08:27:44 -04:00
|
|
|
/// Should the source map be inlined in the emitted code file, or provided
|
|
|
|
/// as a separate file. Defaults to `true`.
|
|
|
|
pub inline_source_map: bool,
|
2021-05-19 00:18:01 -04:00
|
|
|
// Should a corresponding .map file be created for the output. This should be
|
|
|
|
// false if inline_source_map is true. Defaults to `false`.
|
|
|
|
pub source_map: bool,
|
2020-09-14 08:27:44 -04:00
|
|
|
/// When transforming JSX, what value should be used for the JSX factory.
|
|
|
|
/// Defaults to `React.createElement`.
|
|
|
|
pub jsx_factory: String,
|
|
|
|
/// When transforming JSX, what value should be used for the JSX fragment
|
|
|
|
/// factory. Defaults to `React.Fragment`.
|
|
|
|
pub jsx_fragment_factory: String,
|
|
|
|
/// Should JSX be transformed or preserved. Defaults to `true`.
|
|
|
|
pub transform_jsx: bool,
|
2021-06-24 09:00:46 -04:00
|
|
|
/// Should import declarations be transformed to variable declarations.
|
|
|
|
/// This should only be set to true for the REPL. Defaults to `false`.
|
|
|
|
pub repl_imports: bool,
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
|
2020-10-19 23:10:42 -04:00
|
|
|
impl Default for EmitOptions {
|
2020-09-14 08:27:44 -04:00
|
|
|
fn default() -> Self {
|
2020-10-19 23:10:42 -04:00
|
|
|
EmitOptions {
|
2020-09-14 08:27:44 -04:00
|
|
|
emit_metadata: false,
|
2021-03-07 15:40:11 -05:00
|
|
|
imports_not_used_as_values: ImportsNotUsedAsValues::Remove,
|
2020-09-14 08:27:44 -04:00
|
|
|
inline_source_map: true,
|
2021-05-19 00:18:01 -04:00
|
|
|
source_map: false,
|
2020-09-14 08:27:44 -04:00
|
|
|
jsx_factory: "React.createElement".into(),
|
|
|
|
jsx_fragment_factory: "React.Fragment".into(),
|
|
|
|
transform_jsx: true,
|
2021-06-24 09:00:46 -04:00
|
|
|
repl_imports: false,
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-10 12:16:39 -04:00
|
|
|
impl From<config_file::TsConfig> for EmitOptions {
|
|
|
|
fn from(config: config_file::TsConfig) -> Self {
|
|
|
|
let options: config_file::EmitConfigOptions =
|
2020-10-19 23:10:42 -04:00
|
|
|
serde_json::from_value(config.0).unwrap();
|
2021-03-07 15:40:11 -05:00
|
|
|
let imports_not_used_as_values =
|
|
|
|
match options.imports_not_used_as_values.as_str() {
|
|
|
|
"preserve" => ImportsNotUsedAsValues::Preserve,
|
|
|
|
"error" => ImportsNotUsedAsValues::Error,
|
|
|
|
_ => ImportsNotUsedAsValues::Remove,
|
|
|
|
};
|
2020-10-19 23:10:42 -04:00
|
|
|
EmitOptions {
|
|
|
|
emit_metadata: options.emit_decorator_metadata,
|
2021-03-07 15:40:11 -05:00
|
|
|
imports_not_used_as_values,
|
2020-10-26 09:03:03 -04:00
|
|
|
inline_source_map: options.inline_source_map,
|
2021-05-19 00:18:01 -04:00
|
|
|
source_map: options.source_map,
|
2020-10-19 23:10:42 -04:00
|
|
|
jsx_factory: options.jsx_factory,
|
|
|
|
jsx_fragment_factory: options.jsx_fragment_factory,
|
|
|
|
transform_jsx: options.jsx == "react",
|
2021-06-24 09:00:46 -04:00
|
|
|
repl_imports: false,
|
2020-10-19 23:10:42 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-07 15:40:11 -05:00
|
|
|
fn strip_config_from_emit_options(
|
|
|
|
options: &EmitOptions,
|
|
|
|
) -> typescript::strip::Config {
|
2021-04-09 17:35:29 -04:00
|
|
|
typescript::strip::Config {
|
|
|
|
import_not_used_as_values: match options.imports_not_used_as_values {
|
|
|
|
ImportsNotUsedAsValues::Remove => {
|
|
|
|
typescript::strip::ImportsNotUsedAsValues::Remove
|
|
|
|
}
|
|
|
|
ImportsNotUsedAsValues::Preserve => {
|
|
|
|
typescript::strip::ImportsNotUsedAsValues::Preserve
|
|
|
|
}
|
|
|
|
// `Error` only affects the type-checking stage. Fall back to `Remove` here.
|
|
|
|
ImportsNotUsedAsValues::Error => {
|
|
|
|
typescript::strip::ImportsNotUsedAsValues::Remove
|
|
|
|
}
|
|
|
|
},
|
2021-04-10 17:56:40 -04:00
|
|
|
use_define_for_class_fields: true,
|
2021-06-06 12:42:12 -04:00
|
|
|
// TODO(bartlomieju): this could be changed to `false` to provide `export {}`
|
|
|
|
// in Typescript files without manual changes
|
|
|
|
no_empty_export: true,
|
2021-04-09 17:35:29 -04:00
|
|
|
}
|
2021-03-07 15:40:11 -05:00
|
|
|
}
|
|
|
|
|
2020-09-14 08:27:44 -04:00
|
|
|
/// A logical structure to hold the value of a parsed module for further
|
|
|
|
/// processing.
|
2020-09-14 17:59:49 -04:00
|
|
|
#[derive(Clone)]
|
2020-09-14 08:27:44 -04:00
|
|
|
pub struct ParsedModule {
|
2021-08-06 10:36:16 -04:00
|
|
|
info: Arc<SourceFileInfo>,
|
|
|
|
comments: MultiThreadedComments,
|
2021-03-24 20:13:37 -04:00
|
|
|
pub module: Module,
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
|
2020-09-14 17:59:49 -04:00
|
|
|
impl fmt::Debug for ParsedModule {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
f.debug_struct("ParsedModule")
|
|
|
|
.field("comments", &self.comments)
|
|
|
|
.field("module", &self.module)
|
|
|
|
.finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-14 08:27:44 -04:00
|
|
|
impl ParsedModule {
|
|
|
|
/// Return a vector of dependencies for the module.
|
|
|
|
pub fn analyze_dependencies(&self) -> Vec<DependencyDescriptor> {
|
2021-07-14 21:28:01 -04:00
|
|
|
analyze_dependencies(&self.module, &self.comments)
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Get the module's leading comments, where triple slash directives might
|
|
|
|
/// be located.
|
|
|
|
pub fn get_leading_comments(&self) -> Vec<Comment> {
|
2021-08-06 10:36:16 -04:00
|
|
|
self
|
|
|
|
.comments
|
|
|
|
.get_leading(self.module.span.lo)
|
|
|
|
.unwrap_or_else(Vec::new)
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
|
2021-08-06 10:36:16 -04:00
|
|
|
/// Get the module's comments sorted by position.
|
2021-05-10 19:54:39 -04:00
|
|
|
pub fn get_comments(&self) -> Vec<Comment> {
|
2021-08-06 10:36:16 -04:00
|
|
|
self.comments.get_vec()
|
2021-05-10 19:54:39 -04:00
|
|
|
}
|
|
|
|
|
2021-08-06 10:36:16 -04:00
|
|
|
/// Get a location for a given position within the module.
|
|
|
|
pub fn get_location(&self, pos: BytePos) -> Location {
|
|
|
|
self.info.get_location(pos)
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Transform a TypeScript file into a JavaScript file, based on the supplied
|
|
|
|
/// options.
|
|
|
|
///
|
|
|
|
/// The result is a tuple of the code and optional source map as strings.
|
|
|
|
pub fn transpile(
|
|
|
|
self,
|
2020-10-19 23:10:42 -04:00
|
|
|
options: &EmitOptions,
|
|
|
|
) -> Result<(String, Option<String>), AnyError> {
|
2020-09-14 08:27:44 -04:00
|
|
|
let program = Program::Module(self.module);
|
2021-08-06 10:36:16 -04:00
|
|
|
let source_map = Rc::new(SourceMap::default());
|
|
|
|
let file_name = FileName::Custom(self.info.specifier.clone());
|
|
|
|
source_map.new_source_file(file_name, self.info.text.clone());
|
|
|
|
let comments = self.comments.as_single_threaded(); // needs to be mutable
|
2020-09-14 08:27:44 -04:00
|
|
|
|
|
|
|
let jsx_pass = react::react(
|
2021-08-06 10:36:16 -04:00
|
|
|
source_map.clone(),
|
|
|
|
Some(&comments),
|
2020-09-14 08:27:44 -04:00
|
|
|
react::Options {
|
|
|
|
pragma: options.jsx_factory.clone(),
|
|
|
|
pragma_frag: options.jsx_fragment_factory.clone(),
|
|
|
|
// this will use `Object.assign()` instead of the `_extends` helper
|
|
|
|
// when spreading props.
|
|
|
|
use_builtins: true,
|
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
);
|
|
|
|
let mut passes = chain!(
|
|
|
|
Optional::new(jsx_pass, options.transform_jsx),
|
2021-06-24 09:00:46 -04:00
|
|
|
Optional::new(transforms::DownlevelImportsFolder, options.repl_imports),
|
2021-08-06 09:37:24 -04:00
|
|
|
Optional::new(transforms::StripExportsFolder, options.repl_imports),
|
2020-10-19 23:10:42 -04:00
|
|
|
proposals::decorators::decorators(proposals::decorators::Config {
|
2020-09-14 08:27:44 -04:00
|
|
|
legacy: true,
|
|
|
|
emit_metadata: options.emit_metadata
|
|
|
|
}),
|
2021-06-24 09:00:46 -04:00
|
|
|
// DownlevelImportsFolder::new(), // todo: make this conditional
|
2020-11-02 06:33:43 -05:00
|
|
|
helpers::inject_helpers(),
|
2021-03-07 15:40:11 -05:00
|
|
|
typescript::strip::strip_with_config(strip_config_from_emit_options(
|
|
|
|
options
|
|
|
|
)),
|
2021-08-06 10:36:16 -04:00
|
|
|
fixer(Some(&comments)),
|
2020-12-02 14:26:04 -05:00
|
|
|
hygiene(),
|
2020-09-14 08:27:44 -04:00
|
|
|
);
|
|
|
|
|
|
|
|
let program = swc_common::GLOBALS.set(&Globals::new(), || {
|
|
|
|
helpers::HELPERS.set(&helpers::Helpers::new(false), || {
|
|
|
|
program.fold_with(&mut passes)
|
|
|
|
})
|
|
|
|
});
|
|
|
|
|
|
|
|
let mut src_map_buf = vec![];
|
|
|
|
let mut buf = vec![];
|
|
|
|
{
|
|
|
|
let writer = Box::new(JsWriter::new(
|
2021-08-06 10:36:16 -04:00
|
|
|
source_map.clone(),
|
2020-09-14 08:27:44 -04:00
|
|
|
"\n",
|
|
|
|
&mut buf,
|
|
|
|
Some(&mut src_map_buf),
|
|
|
|
));
|
|
|
|
let config = swc_ecmascript::codegen::Config { minify: false };
|
|
|
|
let mut emitter = swc_ecmascript::codegen::Emitter {
|
|
|
|
cfg: config,
|
2021-08-06 10:36:16 -04:00
|
|
|
comments: Some(&comments),
|
|
|
|
cm: source_map.clone(),
|
2020-09-14 08:27:44 -04:00
|
|
|
wr: writer,
|
|
|
|
};
|
|
|
|
program.emit_with(&mut emitter)?;
|
|
|
|
}
|
|
|
|
let mut src = String::from_utf8(buf)?;
|
2020-10-07 07:43:44 -04:00
|
|
|
let mut map: Option<String> = None;
|
2020-09-14 08:27:44 -04:00
|
|
|
{
|
|
|
|
let mut buf = Vec::new();
|
2021-08-06 10:36:16 -04:00
|
|
|
source_map
|
2020-09-14 08:27:44 -04:00
|
|
|
.build_source_map_from(&mut src_map_buf, None)
|
|
|
|
.to_writer(&mut buf)?;
|
|
|
|
|
|
|
|
if options.inline_source_map {
|
|
|
|
src.push_str("//# sourceMappingURL=data:application/json;base64,");
|
|
|
|
let encoded_map = base64::encode(buf);
|
|
|
|
src.push_str(&encoded_map);
|
|
|
|
} else {
|
2020-10-07 07:43:44 -04:00
|
|
|
map = Some(String::from_utf8(buf)?);
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
}
|
2020-10-07 07:43:44 -04:00
|
|
|
Ok((src, map))
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-06 10:36:16 -04:00
|
|
|
/// For a given specifier, source, and media type, parse the text of the
|
2020-12-01 15:20:18 -05:00
|
|
|
/// module and return a representation which can be further processed.
|
|
|
|
///
|
|
|
|
/// # Arguments
|
|
|
|
///
|
|
|
|
/// - `specifier` - The module specifier for the module.
|
|
|
|
/// - `source` - The source code for the module.
|
|
|
|
/// - `media_type` - The media type for the module.
|
|
|
|
///
|
|
|
|
// NOTE(bartlomieju): `specifier` has `&str` type instead of
|
|
|
|
// `&ModuleSpecifier` because runtime compiler APIs don't
|
|
|
|
// require valid module specifiers
|
|
|
|
pub fn parse(
|
|
|
|
specifier: &str,
|
|
|
|
source: &str,
|
|
|
|
media_type: &MediaType,
|
|
|
|
) -> Result<ParsedModule, AnyError> {
|
2021-08-16 03:28:29 -04:00
|
|
|
let source = strip_bom(source);
|
2021-08-06 10:36:16 -04:00
|
|
|
let info = SourceFileInfo::new(specifier, source);
|
|
|
|
let input =
|
|
|
|
StringInput::new(source, BytePos(0), BytePos(source.len() as u32));
|
2021-08-16 03:28:29 -04:00
|
|
|
let (comments, module) =
|
|
|
|
parse_string_input(input, media_type).map_err(|err| Diagnostic {
|
|
|
|
location: info.get_location(err.span().lo),
|
|
|
|
message: err.into_kind().msg().to_string(),
|
|
|
|
})?;
|
2021-08-06 10:36:16 -04:00
|
|
|
|
|
|
|
Ok(ParsedModule {
|
|
|
|
info: Arc::new(info),
|
|
|
|
comments: MultiThreadedComments::from_single_threaded(comments),
|
|
|
|
module,
|
|
|
|
})
|
2020-12-01 15:20:18 -05:00
|
|
|
}
|
|
|
|
|
2020-11-27 14:14:54 -05:00
|
|
|
pub enum TokenOrComment {
|
|
|
|
Token(Token),
|
|
|
|
Comment { kind: CommentKind, text: String },
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct LexedItem {
|
|
|
|
pub span: Span,
|
|
|
|
pub inner: TokenOrComment,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl LexedItem {
|
|
|
|
pub fn span_as_range(&self) -> Range<usize> {
|
|
|
|
self.span.lo.0 as usize..self.span.hi.0 as usize
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn flatten_comments(
|
|
|
|
comments: SingleThreadedComments,
|
|
|
|
) -> impl Iterator<Item = Comment> {
|
|
|
|
let (leading, trailing) = comments.take_all();
|
|
|
|
let mut comments = (*leading).clone().into_inner();
|
|
|
|
comments.extend((*trailing).clone().into_inner());
|
|
|
|
comments.into_iter().flat_map(|el| el.1)
|
|
|
|
}
|
|
|
|
|
2021-08-06 10:36:16 -04:00
|
|
|
pub fn lex(source: &str, media_type: &MediaType) -> Vec<LexedItem> {
|
2020-11-27 14:14:54 -05:00
|
|
|
let comments = SingleThreadedComments::default();
|
|
|
|
let lexer = Lexer::new(
|
|
|
|
get_syntax(media_type),
|
|
|
|
TARGET,
|
2021-08-06 10:36:16 -04:00
|
|
|
StringInput::new(source, BytePos(0), BytePos(source.len() as u32)),
|
2020-11-27 14:14:54 -05:00
|
|
|
Some(&comments),
|
|
|
|
);
|
|
|
|
|
|
|
|
let mut tokens: Vec<LexedItem> = lexer
|
|
|
|
.map(|token| LexedItem {
|
|
|
|
span: token.span,
|
|
|
|
inner: TokenOrComment::Token(token.token),
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
tokens.extend(flatten_comments(comments).map(|comment| LexedItem {
|
|
|
|
span: comment.span,
|
|
|
|
inner: TokenOrComment::Comment {
|
|
|
|
kind: comment.kind,
|
|
|
|
text: comment.text,
|
|
|
|
},
|
|
|
|
}));
|
|
|
|
|
|
|
|
tokens.sort_by_key(|item| item.span.lo.0);
|
|
|
|
|
|
|
|
tokens
|
|
|
|
}
|
|
|
|
|
2020-10-19 23:10:42 -04:00
|
|
|
/// A low level function which transpiles a source module into an swc
|
|
|
|
/// SourceFile.
|
|
|
|
pub fn transpile_module(
|
2021-08-06 10:36:16 -04:00
|
|
|
specifier: &str,
|
|
|
|
source: &str,
|
2020-10-19 23:10:42 -04:00
|
|
|
media_type: &MediaType,
|
|
|
|
emit_options: &EmitOptions,
|
2020-11-02 06:33:43 -05:00
|
|
|
globals: &Globals,
|
2020-10-19 23:10:42 -04:00
|
|
|
cm: Rc<SourceMap>,
|
|
|
|
) -> Result<(Rc<SourceFile>, Module), AnyError> {
|
2021-08-16 03:28:29 -04:00
|
|
|
let source = strip_bom(source);
|
2021-08-06 10:36:16 -04:00
|
|
|
let source_file = cm.new_source_file(
|
|
|
|
FileName::Custom(specifier.to_string()),
|
|
|
|
source.to_string(),
|
|
|
|
);
|
|
|
|
let input = StringInput::from(&*source_file);
|
2021-08-16 03:28:29 -04:00
|
|
|
let (comments, module) =
|
|
|
|
parse_string_input(input, media_type).map_err(|err| Diagnostic {
|
|
|
|
location: cm.lookup_char_pos(err.span().lo).into(),
|
|
|
|
message: err.into_kind().msg().to_string(),
|
|
|
|
})?;
|
2020-10-19 23:10:42 -04:00
|
|
|
|
|
|
|
let jsx_pass = react::react(
|
|
|
|
cm,
|
2021-08-06 10:36:16 -04:00
|
|
|
Some(&comments),
|
2020-10-19 23:10:42 -04:00
|
|
|
react::Options {
|
|
|
|
pragma: emit_options.jsx_factory.clone(),
|
|
|
|
pragma_frag: emit_options.jsx_fragment_factory.clone(),
|
|
|
|
// this will use `Object.assign()` instead of the `_extends` helper
|
|
|
|
// when spreading props.
|
|
|
|
use_builtins: true,
|
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
);
|
|
|
|
let mut passes = chain!(
|
|
|
|
Optional::new(jsx_pass, emit_options.transform_jsx),
|
|
|
|
proposals::decorators::decorators(proposals::decorators::Config {
|
|
|
|
legacy: true,
|
|
|
|
emit_metadata: emit_options.emit_metadata
|
|
|
|
}),
|
2020-11-02 06:33:43 -05:00
|
|
|
helpers::inject_helpers(),
|
2021-03-07 15:40:11 -05:00
|
|
|
typescript::strip::strip_with_config(strip_config_from_emit_options(
|
|
|
|
emit_options
|
|
|
|
)),
|
2021-08-06 10:36:16 -04:00
|
|
|
fixer(Some(&comments)),
|
2020-10-19 23:10:42 -04:00
|
|
|
);
|
2020-12-01 15:20:18 -05:00
|
|
|
|
2020-11-02 06:33:43 -05:00
|
|
|
let module = swc_common::GLOBALS.set(globals, || {
|
2020-10-30 07:19:49 -04:00
|
|
|
helpers::HELPERS.set(&helpers::Helpers::new(false), || {
|
|
|
|
module.fold_with(&mut passes)
|
|
|
|
})
|
|
|
|
});
|
2020-10-19 23:10:42 -04:00
|
|
|
|
|
|
|
Ok((source_file, module))
|
|
|
|
}
|
|
|
|
|
2021-08-06 10:36:16 -04:00
|
|
|
fn parse_string_input(
|
|
|
|
input: StringInput,
|
|
|
|
media_type: &MediaType,
|
2021-08-16 03:28:29 -04:00
|
|
|
) -> Result<
|
|
|
|
(SingleThreadedComments, Module),
|
|
|
|
swc_ecmascript::parser::error::Error,
|
|
|
|
> {
|
2021-08-06 10:36:16 -04:00
|
|
|
let syntax = get_syntax(media_type);
|
|
|
|
let comments = SingleThreadedComments::default();
|
|
|
|
let lexer = Lexer::new(syntax, TARGET, input, Some(&comments));
|
|
|
|
let mut parser = swc_ecmascript::parser::Parser::new_from(lexer);
|
2021-08-16 03:28:29 -04:00
|
|
|
let module = parser.parse_module()?;
|
2021-08-06 10:36:16 -04:00
|
|
|
|
|
|
|
Ok((comments, module))
|
2020-10-19 23:10:42 -04:00
|
|
|
}
|
|
|
|
|
2020-09-14 08:27:44 -04:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2021-02-11 11:05:42 -05:00
|
|
|
use std::collections::HashMap;
|
2021-07-14 21:28:01 -04:00
|
|
|
use swc_common::BytePos;
|
2020-09-14 08:27:44 -04:00
|
|
|
use swc_ecmascript::dep_graph::DependencyKind;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_parsed_module_analyze_dependencies() {
|
2021-02-17 13:47:18 -05:00
|
|
|
let specifier = resolve_url_or_path("https://deno.land/x/mod.js").unwrap();
|
2021-07-14 21:28:01 -04:00
|
|
|
let source = "import * as bar from './test.ts';\nconst foo = await import('./foo.ts');";
|
2020-10-26 09:03:03 -04:00
|
|
|
let parsed_module =
|
|
|
|
parse(specifier.as_str(), source, &MediaType::JavaScript)
|
|
|
|
.expect("could not parse module");
|
2020-09-14 08:27:44 -04:00
|
|
|
let actual = parsed_module.analyze_dependencies();
|
|
|
|
assert_eq!(
|
|
|
|
actual,
|
|
|
|
vec![
|
|
|
|
DependencyDescriptor {
|
|
|
|
kind: DependencyKind::Import,
|
|
|
|
is_dynamic: false,
|
|
|
|
leading_comments: Vec::new(),
|
2021-07-14 21:28:01 -04:00
|
|
|
span: Span::new(BytePos(0), BytePos(33), Default::default()),
|
2020-12-09 17:09:10 -05:00
|
|
|
specifier: "./test.ts".into(),
|
2021-07-14 21:28:01 -04:00
|
|
|
specifier_span: Span::new(
|
|
|
|
BytePos(21),
|
|
|
|
BytePos(32),
|
|
|
|
Default::default()
|
|
|
|
),
|
2021-02-11 11:05:42 -05:00
|
|
|
import_assertions: HashMap::default(),
|
2020-09-14 08:27:44 -04:00
|
|
|
},
|
|
|
|
DependencyDescriptor {
|
|
|
|
kind: DependencyKind::Import,
|
|
|
|
is_dynamic: true,
|
|
|
|
leading_comments: Vec::new(),
|
2021-07-14 21:28:01 -04:00
|
|
|
span: Span::new(BytePos(52), BytePos(70), Default::default()),
|
2020-12-09 17:09:10 -05:00
|
|
|
specifier: "./foo.ts".into(),
|
2021-07-14 21:28:01 -04:00
|
|
|
specifier_span: Span::new(
|
|
|
|
BytePos(59),
|
|
|
|
BytePos(69),
|
|
|
|
Default::default()
|
|
|
|
),
|
2021-02-11 11:05:42 -05:00
|
|
|
import_assertions: HashMap::default(),
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
]
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_transpile() {
|
2021-02-17 13:47:18 -05:00
|
|
|
let specifier = resolve_url_or_path("https://deno.land/x/mod.ts")
|
|
|
|
.expect("could not resolve specifier");
|
2020-09-14 08:27:44 -04:00
|
|
|
let source = r#"
|
|
|
|
enum D {
|
|
|
|
A,
|
|
|
|
B,
|
|
|
|
C,
|
|
|
|
}
|
|
|
|
|
|
|
|
export class A {
|
|
|
|
private b: string;
|
|
|
|
protected c: number = 1;
|
|
|
|
e: "foo";
|
|
|
|
constructor (public d = D.A) {
|
|
|
|
const e = "foo" as const;
|
|
|
|
this.e = e;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"#;
|
2020-10-26 09:03:03 -04:00
|
|
|
let module = parse(specifier.as_str(), source, &MediaType::TypeScript)
|
2020-09-14 08:27:44 -04:00
|
|
|
.expect("could not parse module");
|
|
|
|
let (code, maybe_map) = module
|
2020-10-19 23:10:42 -04:00
|
|
|
.transpile(&EmitOptions::default())
|
2020-09-14 08:27:44 -04:00
|
|
|
.expect("could not strip types");
|
2020-10-07 07:43:44 -04:00
|
|
|
assert!(code.starts_with("var D;\n(function(D) {\n"));
|
|
|
|
assert!(
|
|
|
|
code.contains("\n//# sourceMappingURL=data:application/json;base64,")
|
|
|
|
);
|
2020-09-14 08:27:44 -04:00
|
|
|
assert!(maybe_map.is_none());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_transpile_tsx() {
|
2021-02-17 13:47:18 -05:00
|
|
|
let specifier = resolve_url_or_path("https://deno.land/x/mod.ts")
|
|
|
|
.expect("could not resolve specifier");
|
2020-09-14 08:27:44 -04:00
|
|
|
let source = r#"
|
|
|
|
export class A {
|
|
|
|
render() {
|
|
|
|
return <div><span></span></div>
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"#;
|
2021-03-25 14:17:37 -04:00
|
|
|
let module = parse(specifier.as_str(), source, &MediaType::Tsx)
|
2020-09-14 08:27:44 -04:00
|
|
|
.expect("could not parse module");
|
|
|
|
let (code, _) = module
|
2020-10-19 23:10:42 -04:00
|
|
|
.transpile(&EmitOptions::default())
|
2020-09-14 08:27:44 -04:00
|
|
|
.expect("could not strip types");
|
2020-10-07 07:43:44 -04:00
|
|
|
assert!(code.contains("React.createElement(\"div\", null"));
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_transpile_decorators() {
|
2021-02-17 13:47:18 -05:00
|
|
|
let specifier = resolve_url_or_path("https://deno.land/x/mod.ts")
|
|
|
|
.expect("could not resolve specifier");
|
2020-09-14 08:27:44 -04:00
|
|
|
let source = r#"
|
|
|
|
function enumerable(value: boolean) {
|
|
|
|
return function (
|
|
|
|
_target: any,
|
|
|
|
_propertyKey: string,
|
|
|
|
descriptor: PropertyDescriptor,
|
|
|
|
) {
|
|
|
|
descriptor.enumerable = value;
|
|
|
|
};
|
|
|
|
}
|
2021-02-17 13:47:18 -05:00
|
|
|
|
2020-09-14 08:27:44 -04:00
|
|
|
export class A {
|
|
|
|
@enumerable(false)
|
|
|
|
a() {
|
|
|
|
Test.value;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"#;
|
2020-10-26 09:03:03 -04:00
|
|
|
let module = parse(specifier.as_str(), source, &MediaType::TypeScript)
|
2020-09-14 08:27:44 -04:00
|
|
|
.expect("could not parse module");
|
|
|
|
let (code, _) = module
|
2020-10-19 23:10:42 -04:00
|
|
|
.transpile(&EmitOptions::default())
|
2020-09-14 08:27:44 -04:00
|
|
|
.expect("could not strip types");
|
2020-10-07 07:43:44 -04:00
|
|
|
assert!(code.contains("_applyDecoratedDescriptor("));
|
2020-09-14 08:27:44 -04:00
|
|
|
}
|
|
|
|
}
|