refactor(common): Cleanup & rustfmt (#3495)

swc_common:
 - Merge identical source codes.

swc_css_parser:
 - Deny `clippy::all`.
 - Fix lints.
This commit is contained in:
Donny/강동윤 2022-02-09 15:33:32 +09:00 committed by GitHub
parent 5e82640b42
commit 9b76783281
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
471 changed files with 2570 additions and 1268 deletions

View File

@ -8,6 +8,7 @@ do_not_merge = true
[update]
autoupdate_label = "S-approved"
require_automerge_label = false
# I want to use auto-merge feature of github
[approve]

View File

@ -1,4 +1,7 @@
format_strings = true
group_imports = "StdExternalCrate"
hex_literal_case = "Lower"
imports_granularity = "Crate"
reorder_impl_items = true
use_field_init_shorthand = true
wrap_comments = true

View File

@ -1,8 +1,9 @@
use crate::{input::*, util::is_bool};
use pmutil::{smart_quote, Quote, SpanExt};
use swc_macros_common::prelude::*;
use syn::*;
use crate::{input::*, util::is_bool};
pub fn expand(
Input {
attrs,

View File

@ -1,11 +1,13 @@
use crate::{input::*, util::is_bool};
use std::{fmt::Display, ops::AddAssign, result::Result as StdResult};
use swc_macros_common::prelude::*;
use syn::{
parse::{Parse, ParseStream},
*,
};
use crate::{input::*, util::is_bool};
impl From<DeriveInput> for Input {
fn from(
DeriveInput {

View File

@ -1,11 +1,13 @@
use crate::ast::Text;
use nom::{Compare, CompareResult, InputIter, InputLength, InputTake, Slice, UnspecializedInput};
use std::{
ops::{Deref, Range, RangeFrom, RangeTo},
str::{CharIndices, Chars},
};
use nom::{Compare, CompareResult, InputIter, InputLength, InputTake, Slice, UnspecializedInput};
use swc_common::{comments::Comment, BytePos, Span};
use crate::ast::Text;
#[derive(Debug, Clone, Copy)]
pub struct Input<'i> {
start: BytePos,

View File

@ -1,5 +1,3 @@
pub use self::input::Input;
use crate::ast::*;
use nom::{
bytes::complete::{tag, take_while},
error::ErrorKind,
@ -7,6 +5,9 @@ use nom::{
};
use swc_common::{Span, Spanned, SyntaxContext};
pub use self::input::Input;
use crate::ast::*;
pub mod ast;
mod input;
@ -662,9 +663,10 @@ fn skip(i: Input) -> Input {
#[cfg(test)]
mod tests {
use super::*;
use swc_common::BytePos;
use super::*;
fn input(s: &str) -> Input {
Input::new(BytePos(0), BytePos(s.as_bytes().len() as _), s)
}

View File

@ -1,7 +1,8 @@
#![feature(bench_black_box)]
use dashmap::DashMap;
use std::path::PathBuf;
use dashmap::DashMap;
use swc_common::{
comments::{Comment, CommentKind, Comments},
BytePos, DUMMY_SP,

View File

@ -1,17 +1,14 @@
use crate::{
get_compiler,
util::{get_deserialized, MapErr},
use std::{
panic::{catch_unwind, AssertUnwindSafe},
sync::Arc,
};
use anyhow::{bail, Error};
use napi::{
bindgen_prelude::{AbortSignal, AsyncTask, Buffer},
Env, Status, Task,
};
use serde::Deserialize;
use std::{
panic::{catch_unwind, AssertUnwindSafe},
sync::Arc,
};
use swc::{
config::SourceMapsConfig,
resolver::{environment_resolver, paths_resolver},
@ -26,6 +23,11 @@ use swc_ecma_ast::{
};
use swc_ecma_loader::{TargetEnv, NODE_BUILTINS};
use crate::{
get_compiler,
util::{get_deserialized, MapErr},
};
struct ConfigItem {
loader: Box<dyn Load>,
resolver: Box<dyn Resolve>,
@ -48,8 +50,8 @@ pub(crate) struct BundleTask {
#[cfg(feature = "swc_v1")]
#[napi]
impl Task for BundleTask {
type Output = AHashMap<String, TransformOutput>;
type JsValue = AHashMap<String, TransformOutput>;
type Output = AHashMap<String, TransformOutput>;
fn compute(&mut self) -> napi::Result<Self::Output> {
let builtins = if let TargetEnv::Node = self.config.static_items.config.target {
@ -166,8 +168,8 @@ impl Task for BundleTask {
#[cfg(feature = "swc_v2")]
impl Task for BundleTask {
type Output = AHashMap<String, TransformOutput>;
type JsValue = AHashMap<String, TransformOutput>;
type Output = AHashMap<String, TransformOutput>;
fn compute(&mut self) -> napi::Result<Self::Output> {
todo!()

View File

@ -6,8 +6,9 @@ extern crate napi_derive;
/// Explicit extern crate to use allocator.
extern crate swc_node_base;
use backtrace::Backtrace;
use std::{env, panic::set_hook, sync::Arc};
use backtrace::Backtrace;
use swc::Compiler;
use swc_common::{self, sync::Lazy, FilePathMapping, SourceMap};
use tracing_subscriber::EnvFilter;

View File

@ -1,16 +1,18 @@
use crate::{
get_compiler,
util::{deserialize_json, get_deserialized, try_with, MapErr},
};
use std::sync::Arc;
use napi::{
bindgen_prelude::{AbortSignal, AsyncTask, Buffer},
Task,
};
use serde::Deserialize;
use std::sync::Arc;
use swc::{config::JsMinifyOptions, TransformOutput};
use swc_common::{collections::AHashMap, sync::Lrc, FileName, SourceFile, SourceMap};
use crate::{
get_compiler,
util::{deserialize_json, get_deserialized, try_with, MapErr},
};
struct MinifyTask {
c: Arc<swc::Compiler>,
code: String,
@ -47,9 +49,8 @@ impl MinifyTarget {
#[napi]
impl Task for MinifyTask {
type Output = TransformOutput;
type JsValue = TransformOutput;
type Output = TransformOutput;
fn compute(&mut self) -> napi::Result<Self::Output> {
let input: MinifyTarget = deserialize_json(&self.code)?;

View File

@ -1,19 +1,21 @@
use crate::{
get_compiler,
util::{deserialize_json, get_deserialized, try_with, MapErr},
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use anyhow::Context as _;
use napi::{
bindgen_prelude::{AbortSignal, AsyncTask, Buffer},
Env, Task,
};
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use swc::{config::ParseOptions, Compiler};
use swc_common::FileName;
use crate::{
get_compiler,
util::{deserialize_json, get_deserialized, try_with, MapErr},
};
// ----- Parsing -----
pub struct ParseTask {
@ -31,8 +33,8 @@ pub struct ParseFileTask {
#[napi]
impl Task for ParseTask {
type Output = String;
type JsValue = String;
type Output = String;
fn compute(&mut self) -> napi::Result<Self::Output> {
let options: ParseOptions = deserialize_json(&self.options)?;
@ -65,8 +67,8 @@ impl Task for ParseTask {
#[napi]
impl Task for ParseFileTask {
type Output = String;
type JsValue = String;
type Output = String;
fn compute(&mut self) -> napi::Result<Self::Output> {
let program = try_with(self.c.cm.clone(), false, |handler| {

View File

@ -1,18 +1,20 @@
use crate::{
get_compiler,
util::{deserialize_json, get_deserialized, MapErr},
};
use std::sync::Arc;
use napi::{
bindgen_prelude::{AbortSignal, AsyncTask, Buffer},
Env, Task,
};
use std::sync::Arc;
use swc::{
config::{Options, SourceMapsConfig},
Compiler, TransformOutput,
};
use swc_ecma_ast::{EsVersion, Program};
use crate::{
get_compiler,
util::{deserialize_json, get_deserialized, MapErr},
};
// ----- Printing -----
pub struct PrintTask {
@ -23,8 +25,8 @@ pub struct PrintTask {
#[napi]
impl Task for PrintTask {
type Output = TransformOutput;
type JsValue = TransformOutput;
type Output = TransformOutput;
fn compute(&mut self) -> napi::Result<Self::Output> {
let program: Program = deserialize_json(&self.program_json)?;

View File

@ -1,21 +1,23 @@
use crate::{
get_compiler,
util::{deserialize_json, get_deserialized, try_with, MapErr},
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use anyhow::Context as _;
use napi::{
bindgen_prelude::{AbortSignal, AsyncTask, Buffer},
Env, JsBuffer, JsBufferValue, Ref, Task,
};
use path_clean::clean;
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use swc::{config::Options, Compiler, TransformOutput};
use swc_common::FileName;
use swc_ecma_ast::Program;
use crate::{
get_compiler,
util::{deserialize_json, get_deserialized, try_with, MapErr},
};
/// Input to transform
#[derive(Debug)]
pub enum Input {
@ -35,8 +37,8 @@ pub struct TransformTask {
#[napi]
impl Task for TransformTask {
type Output = TransformOutput;
type JsValue = TransformOutput;
type Output = TransformOutput;
fn compute(&mut self) -> napi::Result<Self::Output> {
let mut options: Options = serde_json::from_slice(self.options.as_ref())?;

View File

@ -1,10 +1,11 @@
use anyhow::{anyhow, Context, Error};
use napi::Status;
use serde::de::DeserializeOwned;
use std::{
any::type_name,
panic::{catch_unwind, AssertUnwindSafe},
};
use anyhow::{anyhow, Context, Error};
use napi::Status;
use serde::de::DeserializeOwned;
use swc::try_with_handler;
use swc_common::{errors::Handler, sync::Lrc, SourceMap};

View File

@ -185,6 +185,7 @@ fn make_from_str(i: &DeriveInput) -> ItemImpl {
{
impl ::std::str::FromStr for Type {
type Err = ();
fn from_str(s: &str) -> Result<Self, ()> {
body
}

View File

@ -1,4 +1,5 @@
use std::fmt::{Debug, Display};
use string_enum::*;
pub trait Assert: Debug + Display {}

View File

@ -5,6 +5,7 @@ extern crate swc_node_base;
extern crate test;
use std::{fs::read_to_string, io::stderr, path::Path};
use swc::config::{IsModule, Options};
use swc_common::{errors::Handler, sync::Lrc, FilePathMapping, SourceMap};
use test::Bencher;

View File

@ -9,6 +9,7 @@ use std::{
io::{self, stderr},
sync::Arc,
};
use swc::config::{Config, IsModule, JscConfig, Options, SourceMapsConfig};
use swc_common::{errors::Handler, FileName, FilePathMapping, Mark, SourceFile, SourceMap};
use swc_ecma_ast::{EsVersion, Program};

View File

@ -1,4 +1,5 @@
use std::{path::Path, sync::Arc};
use swc::{self, config::Options};
use swc_common::{
errors::{ColorConfig, Handler},

View File

@ -1,10 +1,7 @@
use crate::{
config::{util::BoolOrObject, CompiledPaths, GlobalPassOption, JsMinifyOptions, ModuleConfig},
SwcComments,
};
use std::{cell::RefCell, collections::HashMap, path::PathBuf, rc::Rc, sync::Arc};
use compat::{es2015::regenerator, es2020::export_namespace_from};
use either::Either;
use std::{cell::RefCell, collections::HashMap, path::PathBuf, rc::Rc, sync::Arc};
use swc_atoms::JsWord;
use swc_common::{
chain, comments::Comments, errors::Handler, sync::Lrc, util::take::Take, FileName, Mark,
@ -20,6 +17,11 @@ use swc_ecma_transforms::{
};
use swc_ecma_visit::{as_folder, noop_visit_mut_type, VisitMut};
use crate::{
config::{util::BoolOrObject, CompiledPaths, GlobalPassOption, JsMinifyOptions, ModuleConfig},
SwcComments,
};
/// Builder is used to create a high performance `Compiler`.
pub struct PassBuilder<'a, 'b, P: swc_ecma_visit::Fold> {
cm: &'a Arc<SourceMap>,

View File

@ -1,15 +1,3 @@
use self::util::BoolOrObject;
use crate::{builder::PassBuilder, plugin::PluginConfig, SwcComments, SwcImportResolver};
use anyhow::{bail, Context, Error};
use dashmap::DashMap;
use either::Either;
use indexmap::IndexMap;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{
de::{Unexpected, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};
use std::{
cell::RefCell,
collections::{HashMap, HashSet},
@ -20,6 +8,17 @@ use std::{
sync::Arc,
usize,
};
use anyhow::{bail, Context, Error};
use dashmap::DashMap;
use either::Either;
use indexmap::IndexMap;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{
de::{Unexpected, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};
use swc_atoms::JsWord;
pub use swc_common::chain;
use swc_common::{
@ -59,6 +58,9 @@ use swc_ecma_transforms_compat::es2015::regenerator;
use swc_ecma_transforms_optimization::{inline_globals2, GlobalExprMap};
use swc_ecma_visit::{Fold, VisitMutWith};
use self::util::BoolOrObject;
use crate::{builder::PassBuilder, plugin::PluginConfig, SwcComments, SwcImportResolver};
#[cfg(test)]
mod tests;
pub mod util;

View File

@ -1,6 +1,7 @@
use serde_json;
use super::Rc;
use crate::Options;
use serde_json;
#[test]
fn object() {

View File

@ -1,6 +1,7 @@
use super::Merge;
use serde::{Deserialize, Serialize};
use super::Merge;
/// Note: `{}` (empty object) is treated as `true`.
#[derive(Clone, Serialize, Debug)]
#[serde(untagged)]

View File

@ -111,10 +111,14 @@ pub extern crate swc_atoms as atoms;
pub extern crate swc_common as common;
pub extern crate swc_ecmascript as ecmascript;
pub use crate::builder::PassBuilder;
use crate::config::{
BuiltInput, Config, ConfigFile, InputSourceMap, Merge, Options, Rc, RootMode, SourceMapsConfig,
use std::{
fs::{read_to_string, File},
io::Write,
mem::take,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
use anyhow::{bail, Context, Error};
use atoms::JsWord;
use common::{
@ -126,13 +130,6 @@ use once_cell::sync::Lazy;
use serde::Serialize;
use serde_json::error::Category;
pub use sourcemap;
use std::{
fs::{read_to_string, File},
io::Write,
mem::take,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
use swc_common::{
chain,
comments::{Comment, Comments},
@ -160,18 +157,25 @@ use swc_ecma_transforms::{
use swc_ecma_visit::{noop_visit_type, FoldWith, Visit, VisitMutWith, VisitWith};
pub use swc_node_comments::SwcComments;
pub use crate::builder::PassBuilder;
use crate::config::{
BuiltInput, Config, ConfigFile, InputSourceMap, Merge, Options, Rc, RootMode, SourceMapsConfig,
};
mod builder;
pub mod config;
mod plugin;
pub mod resolver {
use crate::config::CompiledPaths;
use std::path::PathBuf;
use swc_common::collections::AHashMap;
use swc_ecma_loader::{
resolvers::{lru::CachingResolver, node::NodeModulesResolver, tsc::TsConfigResolver},
TargetEnv,
};
use crate::config::CompiledPaths;
pub type NodeResolver = CachingResolver<NodeModulesResolver>;
pub fn paths_resolver(

View File

@ -1,4 +1,5 @@
use std::path::{Path, PathBuf};
use swc::{
config::{IsModule, Options},
try_with_handler, Compiler,

View File

@ -1,8 +1,9 @@
use rayon::prelude::*;
use std::{
fs::create_dir_all,
path::{Path, PathBuf},
};
use rayon::prelude::*;
use swc::{
config::{
BuiltInput, Config, IsModule, JscConfig, ModuleConfig, Options, SourceMapsConfig,

View File

@ -1,4 +1,5 @@
use std::path::Path;
use swc_common::input::StringInput;
use swc_ecma_ast::Module;
use swc_ecma_parser::{lexer::Lexer, PResult, Parser, Syntax};

View File

@ -1,6 +1,5 @@
#![allow(unused)]
use anyhow::{Context, Error};
use std::{
env::temp_dir,
fs,
@ -9,6 +8,8 @@ use std::{
process::{Command, Output},
sync::Arc,
};
use anyhow::{Context, Error};
use swc::{
config::{Config, IsModule, Options, SourceMapsConfig},
Compiler,

View File

@ -1,8 +1,9 @@
use serde::de::DeserializeOwned;
use std::{
fs::create_dir_all,
path::{Path, PathBuf},
};
use serde::de::DeserializeOwned;
use swc::{
config::{Config, IsModule, JscConfig, Options},
Compiler,

View File

@ -3,14 +3,15 @@
/// Use memory allocator
extern crate swc_node_base;
use anyhow::{bail, Error};
use path_clean::PathClean;
use std::{
collections::HashMap,
env, fs,
path::{Path, PathBuf},
time::{Duration, Instant},
};
use anyhow::{bail, Error};
use path_clean::PathClean;
use swc_atoms::js_word;
use swc_bundler::{Bundle, Bundler, Load, ModuleData, ModuleRecord, Resolve};
use swc_common::{

View File

@ -1,5 +1,6 @@
use anyhow::Error;
use std::{collections::HashMap, io::stdout};
use anyhow::Error;
use swc_bundler::{BundleKind, Bundler, Config, Hook, Load, ModuleData, ModuleRecord, Resolve};
use swc_common::{sync::Lrc, FileName, FilePathMapping, Globals, SourceMap, Span};
use swc_ecma_ast::KeyValueProp;

View File

@ -1,16 +1,18 @@
use crate::{
bundler::{chunk::merge::Ctx, load::TransformedModule},
modules::Modules,
Bundler, Load, Resolve,
};
use anyhow::Error;
use std::sync::atomic::Ordering;
use anyhow::Error;
use swc_atoms::js_word;
use swc_common::{Span, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::{ModuleItem, *};
use swc_ecma_utils::{quote_ident, undefined, ExprFactory};
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use crate::{
bundler::{chunk::merge::Ctx, load::TransformedModule},
modules::Modules,
Bundler, Load, Resolve,
};
impl<L, R> Bundler<'_, L, R>
where
L: Load,

View File

@ -1,12 +1,14 @@
use crate::{bundler::chunk::merge::Ctx, modules::Modules, Bundler, Load, ModuleId, Resolve};
use anyhow::{bail, Error};
use std::mem::take;
use anyhow::{bail, Error};
use swc_atoms::js_word;
use swc_common::{SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::{find_ids, private_ident, ExprFactory};
use swc_ecma_visit::{noop_fold_type, noop_visit_type, Fold, Visit};
use crate::{bundler::chunk::merge::Ctx, modules::Modules, Bundler, Load, ModuleId, Resolve};
impl<L, R> Bundler<'_, L, R>
where
L: Load,
@ -188,7 +190,9 @@ impl Visit for TopLevelAwaitFinder {
noop_visit_type!();
fn visit_function(&mut self, _: &Function) {}
fn visit_arrow_expr(&mut self, _: &ArrowExpr) {}
fn visit_class_member(&mut self, _: &ClassMember) {}
fn visit_await_expr(&mut self, _: &AwaitExpr) {

View File

@ -1,3 +1,19 @@
use std::sync::atomic::Ordering;
use anyhow::Error;
use indexmap::IndexSet;
use petgraph::EdgeDirection;
use swc_atoms::js_word;
use swc_common::{
collections::{AHashMap, AHashSet},
sync::Lock,
FileName, SyntaxContext, DUMMY_SP,
};
use swc_ecma_ast::*;
use swc_ecma_utils::{find_ids, prepend, private_ident, quote_ident, ExprFactory};
use swc_ecma_visit::{noop_fold_type, noop_visit_mut_type, Fold, VisitMut, VisitMutWith};
use EdgeDirection::Outgoing;
use crate::{
bundler::{
keywords::KeywordRenamer,
@ -12,20 +28,6 @@ use crate::{
util::{CloneMap, ExprExt, VarDeclaratorExt},
Bundler, Hook, ModuleRecord,
};
use anyhow::Error;
use indexmap::IndexSet;
use petgraph::EdgeDirection;
use std::sync::atomic::Ordering;
use swc_atoms::js_word;
use swc_common::{
collections::{AHashMap, AHashSet},
sync::Lock,
FileName, SyntaxContext, DUMMY_SP,
};
use swc_ecma_ast::*;
use swc_ecma_utils::{find_ids, prepend, private_ident, quote_ident, ExprFactory};
use swc_ecma_visit::{noop_fold_type, noop_visit_mut_type, Fold, VisitMut, VisitMutWith};
use EdgeDirection::Outgoing;
pub(super) struct Ctx {
/// Full dependency graph.

View File

@ -1,12 +1,14 @@
use std::time::Instant;
use anyhow::{Context, Error};
#[cfg(feature = "rayon")]
use rayon::iter::ParallelIterator;
use swc_common::collections::AHashMap;
use super::{load::TransformedModule, Bundler};
use crate::{
bundler::chunk::merge::Ctx, load::Load, resolve::Resolve, util::IntoParallelIterator, Bundle,
};
use anyhow::{Context, Error};
#[cfg(feature = "rayon")]
use rayon::iter::ParallelIterator;
use std::time::Instant;
use swc_common::collections::AHashMap;
mod cjs;
mod computed_key;
@ -153,9 +155,10 @@ where
#[cfg(test)]
mod tests {
use swc_common::FileName;
use super::*;
use crate::bundler::tests::suite;
use swc_common::FileName;
#[test]
fn cjs_chunk() {

View File

@ -1,11 +1,12 @@
use anyhow::{bail, Error};
use swc_common::collections::AHashMap;
use swc_graph_analyzer::{DepGraph, GraphAnalyzer};
use crate::{
bundler::{load::TransformedModule, scope::Scope},
dep_graph::ModuleGraph,
BundleKind, Bundler, Load, ModuleId, Resolve,
};
use anyhow::{bail, Error};
use swc_common::collections::AHashMap;
use swc_graph_analyzer::{DepGraph, GraphAnalyzer};
#[cfg(test)]
mod tests;

View File

@ -1,7 +1,9 @@
use crate::bundler::tests::suite;
use std::collections::HashMap;
use swc_common::collections::{AHashMap, AHashSet};
use crate::bundler::tests::suite;
fn assert_cycles(map: AHashMap<String, String>, cycle_entries: Vec<&str>) {
let mut tester = suite();

View File

@ -1,8 +1,3 @@
use super::{
load::{Source, Specifier},
Bundler,
};
use crate::{id::Id, load::Load, resolve::Resolve};
use indexmap::IndexMap;
use swc_atoms::{js_word, JsWord};
use swc_common::{FileName, SyntaxContext};
@ -10,6 +5,12 @@ use swc_ecma_ast::*;
use swc_ecma_utils::find_ids;
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use super::{
load::{Source, Specifier},
Bundler,
};
use crate::{id::Id, load::Load, resolve::Resolve};
impl<L, R> Bundler<'_, L, R>
where
L: Load,

View File

@ -1,8 +1,8 @@
use crate::{hash::calc_hash, Bundle, BundleKind, Bundler, Load, ModuleType, Resolve};
use std::path::{Path, PathBuf};
use ahash::AHashMap;
use anyhow::Error;
use relative_path::RelativePath;
use std::path::{Path, PathBuf};
use swc_atoms::js_word;
use swc_common::{util::move_map::MoveMap, FileName, DUMMY_SP};
use swc_ecma_ast::*;
@ -14,6 +14,8 @@ use swc_ecma_transforms_base::{
use swc_ecma_utils::{find_ids, private_ident, ExprFactory};
use swc_ecma_visit::{noop_fold_type, noop_visit_type, Fold, FoldWith, Visit, VisitWith};
use crate::{hash::calc_hash, Bundle, BundleKind, Bundler, Load, ModuleType, Resolve};
impl<L, R> Bundler<'_, L, R>
where
L: Load,

View File

@ -1,5 +1,6 @@
use once_cell::sync::Lazy;
use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
use once_cell::sync::Lazy;
use swc_common::{FileName, FilePathMapping, SourceMap};
use swc_ecma_ast::*;
use swc_ecma_parser::{lexer::Lexer, Parser, StringInput};

View File

@ -1,5 +1,3 @@
use super::Bundler;
use crate::{load::Load, resolve::Resolve};
use anyhow::{Context, Error};
use retain_mut::RetainMut;
use swc_atoms::{js_word, JsWord};
@ -12,6 +10,9 @@ use swc_ecma_ast::*;
use swc_ecma_utils::{find_ids, ident::IdentLike, Id};
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use super::Bundler;
use crate::{load::Load, resolve::Resolve};
#[cfg(test)]
mod tests;

View File

@ -1,10 +1,11 @@
use crate::id::Id;
use swc_atoms::js_word;
use swc_common::{collections::AHashMap, util::take::Take};
use swc_ecma_ast::*;
use swc_ecma_utils::private_ident;
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use crate::id::Id;
#[derive(Default)]
pub struct KeywordRenamer {
renamed: AHashMap<Id, Ident>,

View File

@ -1,14 +1,5 @@
#![allow(dead_code)]
use super::{export::Exports, helpers::Helpers, Bundler};
use crate::{
bundler::{export::RawExports, import::RawImports},
id::{Id, ModuleId},
load::ModuleData,
util,
util::IntoParallelIterator,
Load, Resolve,
};
use anyhow::{Context, Error};
use is_macro::Is;
#[cfg(feature = "rayon")]
@ -23,6 +14,16 @@ use swc_ecma_transforms_base::resolver::resolver_with_mark;
use swc_ecma_visit::{
noop_visit_mut_type, noop_visit_type, FoldWith, Visit, VisitMut, VisitMutWith, VisitWith,
};
use super::{export::Exports, helpers::Helpers, Bundler};
use crate::{
bundler::{export::RawExports, import::RawImports},
id::{Id, ModuleId},
load::ModuleData,
util,
util::IntoParallelIterator,
Load, Resolve,
};
/// Module after applying transformations.
#[derive(Debug, Clone)]
pub(crate) struct TransformedModule {

View File

@ -1,13 +1,15 @@
use self::scope::Scope;
use crate::{Hook, Load, ModuleId, Resolve};
use anyhow::{Context, Error};
use std::collections::HashMap;
use anyhow::{Context, Error};
use swc_atoms::JsWord;
use swc_common::{
collections::AHashMap, sync::Lrc, FileName, Globals, Mark, SourceMap, SyntaxContext, GLOBALS,
};
use swc_ecma_ast::Module;
use self::scope::Scope;
use crate::{Hook, Load, ModuleId, Resolve};
mod chunk;
mod export;
mod finalize;
@ -139,9 +141,11 @@ where
}
})
}
pub(crate) fn is_external(&self, src: &JsWord) -> bool {
return self.config.external_modules.iter().any(|v| v == src);
}
///
///
///

View File

@ -1,9 +1,10 @@
use crate::{Bundler, Load, Resolve};
use swc_common::pass::Repeat;
use swc_ecma_ast::*;
use swc_ecma_transforms_optimization::simplify::{const_propgation::constant_propagation, dce};
use swc_ecma_visit::FoldWith;
use crate::{Bundler, Load, Resolve};
impl<L, R> Bundler<'_, L, R>
where
L: Load,

View File

@ -1,10 +1,12 @@
use std::sync::atomic::{AtomicBool, Ordering};
use swc_common::{sync::Lrc, FileName};
use super::load::TransformedModule;
use crate::{
id::{Id, ModuleId, ModuleIdGenerator},
util::CloneMap,
};
use std::sync::atomic::{AtomicBool, Ordering};
use swc_common::{sync::Lrc, FileName};
#[derive(Debug, Default)]
pub(super) struct Scope {

View File

@ -1,15 +1,17 @@
//! Utilities for testing.
use super::{load::TransformedModule, Bundler, Config};
use crate::{load::ModuleData, util::HygieneRemover, Load, ModuleRecord, Resolve};
use std::path::PathBuf;
use anyhow::Error;
use indexmap::IndexMap;
use std::path::PathBuf;
use swc_common::{sync::Lrc, FileName, SourceMap, Span, GLOBALS};
use swc_ecma_ast::*;
use swc_ecma_parser::{lexer::Lexer, Parser, StringInput};
use swc_ecma_utils::drop_span;
use swc_ecma_visit::VisitMutWith;
use super::{load::TransformedModule, Bundler, Config};
use crate::{load::ModuleData, util::HygieneRemover, Load, ModuleRecord, Resolve};
pub(crate) struct Tester<'a> {
pub cm: Lrc<SourceMap>,
pub bundler: Bundler<'a, Loader, Resolver>,

View File

@ -1,6 +1,7 @@
#![allow(dead_code)]
use std::io::{stderr, Write};
use swc_common::{sync::Lrc, SourceMap, SyntaxContext};
use swc_ecma_ast::{Ident, Module};
use swc_ecma_codegen::{text_writer::JsWriter, Emitter};

View File

@ -1,4 +1,5 @@
use crate::ModuleId;
use swc_fast_graph::digraph::FastDiGraphMap;
use crate::ModuleId;
pub(crate) type ModuleGraph = FastDiGraphMap<ModuleId, ()>;

View File

@ -1,6 +1,7 @@
use std::io;
use anyhow::{Context, Error};
use crc::{crc64, crc64::Digest, Hasher64};
use std::io;
use swc_common::{sync::Lrc, SourceMap, Span};
use swc_ecma_ast::{EsVersion, Module};
use swc_ecma_codegen::{text_writer::WriteJs, Emitter};

View File

@ -2,6 +2,7 @@ use std::{
fmt,
sync::atomic::{AtomicU32, Ordering::SeqCst},
};
use swc_atoms::JsWord;
use swc_common::{collections::AHashMap, sync::Lock, FileName, Mark, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::{Expr, Ident};

View File

@ -1,4 +1,3 @@
use crate::{id::Id, modules::Modules, util::Readonly};
use swc_common::{collections::AHashMap, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_visit::{
@ -6,6 +5,8 @@ use swc_ecma_visit::{
VisitMutWith, VisitWith,
};
use crate::{id::Id, modules::Modules, util::Readonly};
#[derive(Debug, Default)]
pub(crate) struct InlineData {
ids: AHashMap<Id, Id>,
@ -85,6 +86,8 @@ impl Visit for Analyzer<'_> {
impl VisitMut for Inliner {
noop_visit_mut_type!();
visit_mut_obj_and_computed!();
/// Don't modify exported ident.
fn visit_mut_export_named_specifier(&mut self, n: &mut ExportNamedSpecifier) {
if n.exported.is_none() {
@ -101,8 +104,6 @@ impl VisitMut for Inliner {
}
}
visit_mut_obj_and_computed!();
fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) {
n.visit_mut_children_with(self);

View File

@ -1,10 +1,12 @@
use crate::ModuleId;
use retain_mut::RetainMut;
use std::mem::take;
use retain_mut::RetainMut;
use swc_common::{collections::AHashMap, SourceMap, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_visit::{Fold, FoldWith, Visit, VisitMut, VisitMutWith, VisitWith};
use crate::ModuleId;
mod sort;
#[derive(Debug, Clone)]

View File

@ -1,12 +1,14 @@
use super::stmt::sort_stmts;
use crate::{dep_graph::ModuleGraph, modules::Modules, ModuleId};
use std::{collections::VecDeque, iter::from_fn, mem::take, time::Instant};
use indexmap::IndexSet;
use petgraph::EdgeDirection::Outgoing;
use std::{collections::VecDeque, iter::from_fn, mem::take, time::Instant};
use swc_common::{collections::AHashSet, sync::Lrc, SourceMap, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_utils::prepend_stmts;
use super::stmt::sort_stmts;
use crate::{dep_graph::ModuleGraph, modules::Modules, ModuleId};
/// The unit of sorting.
#[derive(Debug)]
pub(super) struct Chunk {

View File

@ -1,8 +1,9 @@
use std::{collections::VecDeque, iter::repeat};
use petgraph::{
EdgeDirection,
EdgeDirection::{Incoming, Outgoing},
};
use std::{collections::VecDeque, iter::repeat};
use swc_common::collections::AHashSet;
use swc_fast_graph::digraph::FastDiGraphMap;

View File

@ -1,9 +1,11 @@
use super::Modules;
use crate::{dep_graph::ModuleGraph, ModuleId};
use std::time::Instant;
use swc_common::{sync::Lrc, SourceMap, DUMMY_SP};
use swc_ecma_ast::*;
use super::Modules;
use crate::{dep_graph::ModuleGraph, ModuleId};
mod chunk;
mod graph;
mod stmt;

View File

@ -1,8 +1,7 @@
use super::graph::Required;
use crate::{id::Id, modules::sort::graph::StmtDepGraph};
use std::{collections::VecDeque, iter::from_fn, ops::Range};
use indexmap::IndexSet;
use petgraph::EdgeDirection::{Incoming as Dependants, Outgoing as Dependencies};
use std::{collections::VecDeque, iter::from_fn, ops::Range};
use swc_atoms::js_word;
use swc_common::{
collections::{AHashMap, AHashSet},
@ -14,6 +13,9 @@ use swc_ecma_ast::*;
use swc_ecma_utils::find_ids;
use swc_ecma_visit::{noop_visit_type, Visit, VisitWith};
use super::graph::Required;
use crate::{id::Id, modules::sort::graph::StmtDepGraph};
pub(super) fn sort_stmts(
injected_ctxt: SyntaxContext,
modules: Vec<Vec<ModuleItem>>,
@ -348,6 +350,7 @@ impl FieldInitFinder {
}
}
}
fn check_lhs_expr_of_assign(&mut self, lhs: &Expr) {
if let Expr::Member(m) = lhs {
match &*m.obj {
@ -539,9 +542,13 @@ impl Visit for RequirementCalculator {
noop_visit_type!();
weak!(visit_arrow_expr, ArrowExpr);
weak!(visit_function, Function);
weak!(visit_class_method, ClassMethod);
weak!(visit_private_method, PrivateMethod);
weak!(visit_method_prop, MethodProp);
fn visit_export_named_specifier(&mut self, n: &ExportNamedSpecifier) {
@ -787,11 +794,12 @@ fn calc_deps(new: &[ModuleItem]) -> StmtDepGraph {
#[cfg(test)]
mod tests {
use super::{calc_deps, Dependencies};
use crate::{bundler::tests::suite, debug::print_hygiene};
use swc_common::DUMMY_SP;
use swc_ecma_ast::*;
use super::{calc_deps, Dependencies};
use crate::{bundler::tests::suite, debug::print_hygiene};
fn assert_no_cycle(s: &str) {
suite().file("main.js", s).run(|t| {
let info = t.module("main.js");

View File

@ -1,10 +1,11 @@
use super::stmt::sort_stmts;
use crate::{bundler::tests::suite, debug::print_hygiene};
use swc_common::{SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::drop_span;
use testing::assert_eq;
use super::stmt::sort_stmts;
use crate::{bundler::tests::suite, debug::print_hygiene};
fn assert_sorted(src: &[&str], res: &str) {
assert_sorted_with_free(src, "", res)
}

View File

@ -1,6 +1,7 @@
#![allow(dead_code)]
use std::{clone::Clone, cmp::Eq, hash::Hash};
use swc_common::{Span, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::ident::IdentLike;

View File

@ -1,13 +1,14 @@
use anyhow::{bail, Context, Error};
use path_clean::PathClean;
use reqwest::Url;
use sha1::{Digest, Sha1};
use std::{
env::current_dir,
fs::{create_dir_all, read_to_string, write},
io::Write,
path::{Path, PathBuf},
};
use anyhow::{bail, Context, Error};
use path_clean::PathClean;
use reqwest::Url;
use sha1::{Digest, Sha1};
use swc_bundler::{Load, ModuleData, Resolve};
use swc_common::{
comments::SingleThreadedComments,

View File

@ -3,10 +3,10 @@
//! This module exists because this is way easier than using copying requires
//! files.
use self::common::*;
use std::{collections::HashMap, fs::write, path::PathBuf, process::Command};
use anyhow::Error;
use ntest::timeout;
use std::{collections::HashMap, fs::write, path::PathBuf, process::Command};
use swc_atoms::js_word;
use swc_bundler::{Bundler, Load, ModuleRecord};
use swc_common::{collections::AHashSet, FileName, Mark, Span, GLOBALS};
@ -21,6 +21,8 @@ use swc_ecma_utils::{find_ids, Id};
use swc_ecma_visit::{Visit, VisitMutWith, VisitWith};
use testing::assert_eq;
use self::common::*;
#[path = "common/mod.rs"]
mod common;

View File

@ -1,5 +1,3 @@
use self::common::*;
use anyhow::Error;
use std::{
self,
collections::HashMap,
@ -7,6 +5,8 @@ use std::{
io,
path::{Path, PathBuf},
};
use anyhow::Error;
use swc_atoms::js_word;
use swc_bundler::{BundleKind, Bundler, Config, ModuleRecord};
use swc_common::{FileName, Globals, Span};
@ -20,6 +20,8 @@ use swc_ecma_transforms_base::fixer::fixer;
use swc_ecma_visit::FoldWith;
use testing::NormalizedOutput;
use self::common::*;
#[path = "common/mod.rs"]
mod common;

View File

@ -1,4 +1,5 @@
use std::path::PathBuf;
use structopt::StructOpt;
/// Transform, compile files.

View File

@ -3,9 +3,10 @@
extern crate test;
use std::hint::black_box;
use ast_node::ast_node;
use serde::{Deserialize, Serialize};
use std::hint::black_box;
use swc_common::{Span, DUMMY_SP};
use test::Bencher;

View File

@ -1,14 +1,16 @@
use crate::{
pos::Spanned,
syntax_pos::{BytePos, Span, DUMMY_SP},
};
use rustc_hash::FxHashMap;
use std::{
cell::{Ref, RefCell},
rc::Rc,
sync::Arc,
};
use rustc_hash::FxHashMap;
use crate::{
pos::Spanned,
syntax_pos::{BytePos, Span, DUMMY_SP},
};
/// Stores comment.
///
/// ## Implementation notes

View File

@ -1,8 +1,10 @@
use crate::{BytePos, Span, SyntaxContext};
use num_bigint::BigInt;
use std::{cell::RefCell, cmp::PartialEq, rc::Rc, sync::Arc};
use num_bigint::BigInt;
use string_cache::Atom;
use crate::{BytePos, Span, SyntaxContext};
/// Derive with `#[derive(EqIgnoreSpan)]`.
pub trait EqIgnoreSpan {
fn eq_ignore_span(&self, other: &Self) -> bool;

View File

@ -8,9 +8,10 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::fmt;
use super::{snippet::Style, Applicability, CodeSuggestion, Level, Substitution, SubstitutionPart};
use crate::syntax_pos::{MultiSpan, Span};
use std::fmt;
#[must_use]
#[derive(Clone, Debug, PartialEq, Hash)]
@ -69,12 +70,15 @@ impl DiagnosticStyledString {
pub fn new() -> DiagnosticStyledString {
Default::default()
}
pub fn push_normal<S: Into<String>>(&mut self, t: S) {
self.0.push(StringPart::Normal(t.into()));
}
pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
self.0.push(StringPart::Highlighted(t.into()));
}
pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
DiagnosticStyledString(vec![StringPart::Normal(t.into())])
}

View File

@ -8,15 +8,17 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use super::{Applicability, Diagnostic, DiagnosticId, DiagnosticStyledString, Handler, Level};
use crate::syntax_pos::{MultiSpan, Span};
use std::{
fmt::{self, Debug},
ops::{Deref, DerefMut},
thread::panicking,
};
use tracing::debug;
use super::{Applicability, Diagnostic, DiagnosticId, DiagnosticStyledString, Handler, Level};
use crate::syntax_pos::{MultiSpan, Span};
/// Used for emitting structured error messages and other diagnostic
/// information.
///
@ -90,6 +92,67 @@ impl<'a> DerefMut for DiagnosticBuilder<'a> {
}
impl<'a> DiagnosticBuilder<'a> {
forward!(pub fn note_expected_found(&mut self,
label: &dyn fmt::Display,
expected: DiagnosticStyledString,
found: DiagnosticStyledString,
) -> &mut Self);
forward!(pub fn note_expected_found_extra(&mut self,
label: &dyn fmt::Display,
expected: DiagnosticStyledString,
found: DiagnosticStyledString,
expected_extra: &dyn fmt::Display,
found_extra: &dyn fmt::Display,
) -> &mut Self);
forward!(pub fn note(&mut self, msg: &str) -> &mut Self);
forward!(pub fn span_note<S: Into<MultiSpan>>(&mut self,
sp: S,
msg: &str,
) -> &mut Self);
forward!(pub fn warn(&mut self, msg: &str) -> &mut Self);
forward!(pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self);
forward!(pub fn help(&mut self , msg: &str) -> &mut Self);
forward!(pub fn span_help<S: Into<MultiSpan>>(&mut self,
sp: S,
msg: &str,
) -> &mut Self);
forward!(pub fn span_suggestion_short(
&mut self,
sp: Span,
msg: &str,
suggestion: String,
) -> &mut Self);
forward!(pub fn multipart_suggestion(
&mut self,
msg: &str,
suggestion: Vec<(Span, String)>,
) -> &mut Self);
forward!(pub fn span_suggestion(&mut self,
sp: Span,
msg: &str,
suggestion: String,
) -> &mut Self);
forward!(pub fn span_suggestions(&mut self,
sp: Span,
msg: &str,
suggestions: Vec<String>,
) -> &mut Self);
forward!(pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self);
forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self);
/// Emit the diagnostic.
pub fn emit(&mut self) {
if self.cancelled() {
@ -163,58 +226,6 @@ impl<'a> DiagnosticBuilder<'a> {
self
}
forward!(pub fn note_expected_found(&mut self,
label: &dyn fmt::Display,
expected: DiagnosticStyledString,
found: DiagnosticStyledString,
) -> &mut Self);
forward!(pub fn note_expected_found_extra(&mut self,
label: &dyn fmt::Display,
expected: DiagnosticStyledString,
found: DiagnosticStyledString,
expected_extra: &dyn fmt::Display,
found_extra: &dyn fmt::Display,
) -> &mut Self);
forward!(pub fn note(&mut self, msg: &str) -> &mut Self);
forward!(pub fn span_note<S: Into<MultiSpan>>(&mut self,
sp: S,
msg: &str,
) -> &mut Self);
forward!(pub fn warn(&mut self, msg: &str) -> &mut Self);
forward!(pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self);
forward!(pub fn help(&mut self , msg: &str) -> &mut Self);
forward!(pub fn span_help<S: Into<MultiSpan>>(&mut self,
sp: S,
msg: &str,
) -> &mut Self);
forward!(pub fn span_suggestion_short(
&mut self,
sp: Span,
msg: &str,
suggestion: String,
) -> &mut Self);
forward!(pub fn multipart_suggestion(
&mut self,
msg: &str,
suggestion: Vec<(Span, String)>,
) -> &mut Self);
forward!(pub fn span_suggestion(&mut self,
sp: Span,
msg: &str,
suggestion: String,
) -> &mut Self);
forward!(pub fn span_suggestions(&mut self,
sp: Span,
msg: &str,
suggestions: Vec<String>,
) -> &mut Self);
pub fn multipart_suggestion_with_applicability(
&mut self,
msg: &str,
@ -277,8 +288,6 @@ impl<'a> DiagnosticBuilder<'a> {
);
self
}
forward!(pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self);
forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self);
pub fn allow_suggestions(&mut self, allow: bool) -> &mut Self {
self.allow_suggestions = allow;

View File

@ -8,6 +8,20 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::{
borrow::Cow,
cmp::{min, Reverse},
collections::HashMap,
io::{self, prelude::*},
ops::Range,
};
#[cfg(feature = "tty-emitter")]
use atty;
#[cfg(feature = "tty-emitter")]
use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
use unicode_width;
use self::Destination::*;
use super::{
snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, Style, StyledString},
@ -18,18 +32,6 @@ use crate::{
sync::Lrc,
syntax_pos::{MultiSpan, SourceFile, Span},
};
#[cfg(feature = "tty-emitter")]
use atty;
use std::{
borrow::Cow,
cmp::{min, Reverse},
collections::HashMap,
io::{self, prelude::*},
ops::Range,
};
#[cfg(feature = "tty-emitter")]
use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
use unicode_width;
const ANONYMIZED_LINE_NUM: &str = "LL";

View File

@ -8,6 +8,19 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::{
borrow::Cow,
cell::RefCell,
error, fmt,
io::Write,
panic,
sync::atomic::{AtomicUsize, Ordering::SeqCst},
};
use scoped_tls::scoped_thread_local;
#[cfg(feature = "tty-emitter")]
use termcolor::{Color, ColorSpec};
use self::Level::*;
pub use self::{
diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic},
@ -20,17 +33,6 @@ use crate::{
sync::{Lock, LockCell, Lrc},
syntax_pos::{BytePos, FileLinesResult, FileName, Loc, MultiSpan, Span, NO_EXPANSION},
};
use scoped_tls::scoped_thread_local;
use std::{
borrow::Cow,
cell::RefCell,
error, fmt,
io::Write,
panic,
sync::atomic::{AtomicUsize, Ordering::SeqCst},
};
#[cfg(feature = "tty-emitter")]
use termcolor::{Color, ColorSpec};
mod diagnostic;
mod diagnostic_builder;
@ -468,6 +470,7 @@ impl Handler {
}
result
}
pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(
&'a self,
sp: S,
@ -482,6 +485,7 @@ impl Handler {
}
result
}
pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
if !self.flags.can_emit_warnings {
@ -489,6 +493,7 @@ impl Handler {
}
result
}
pub fn struct_span_err<'a, S: Into<MultiSpan>>(
&'a self,
sp: S,
@ -498,6 +503,7 @@ impl Handler {
result.set_span(sp);
result
}
pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(
&'a self,
sp: S,
@ -509,11 +515,13 @@ impl Handler {
result.code(code);
result
}
// FIXME: This method should be removed (every error should have an associated
// error code).
pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
DiagnosticBuilder::new(self, Level::Error, msg)
}
pub fn struct_err_with_code<'a>(
&'a self,
msg: &str,
@ -523,6 +531,7 @@ impl Handler {
result.code(code);
result
}
pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(
&'a self,
sp: S,
@ -532,6 +541,7 @@ impl Handler {
result.set_span(sp);
result
}
pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(
&'a self,
sp: S,
@ -543,6 +553,7 @@ impl Handler {
result.code(code);
result
}
pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
DiagnosticBuilder::new(self, Level::Fatal, msg)
}
@ -561,6 +572,7 @@ impl Handler {
self.emit(&sp.into(), msg, Fatal);
FatalError
}
pub fn span_fatal_with_code<S: Into<MultiSpan>>(
&self,
sp: S,
@ -570,9 +582,11 @@ impl Handler {
self.emit_with_code(&sp.into(), msg, code, Fatal);
FatalError
}
pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
self.emit(&sp.into(), msg, Error);
}
pub fn mut_span_err<'a, S: Into<MultiSpan>>(
&'a self,
sp: S,
@ -582,19 +596,24 @@ impl Handler {
result.set_span(sp);
result
}
pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
self.emit_with_code(&sp.into(), msg, code, Error);
}
pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
self.emit(&sp.into(), msg, Warning);
}
pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
self.emit_with_code(&sp.into(), msg, code, Warning);
}
pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
self.emit(&sp.into(), msg, Bug);
panic!("{}", ExplicitBug);
}
pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
if self.flags.treat_err_as_bug {
// FIXME: don't abort here if report_delayed_bugs is off
@ -604,29 +623,36 @@ impl Handler {
diagnostic.set_span(sp.into());
self.delay_as_bug(diagnostic);
}
fn delay_as_bug(&self, diagnostic: Diagnostic) {
if self.flags.report_delayed_bugs {
DiagnosticBuilder::new_diagnostic(self, diagnostic.clone()).emit();
}
self.delayed_span_bugs.borrow_mut().push(diagnostic);
}
pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
self.emit(&sp.into(), msg, Bug);
}
pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
self.emit(&sp.into(), msg, Note);
}
pub fn span_note_diag<'a>(&'a self, sp: Span, msg: &str) -> DiagnosticBuilder<'a> {
let mut db = DiagnosticBuilder::new(self, Note, msg);
db.set_span(sp);
db
}
pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
self.span_bug(sp, &format!("unimplemented {}", msg));
}
pub fn failure(&self, msg: &str) {
DiagnosticBuilder::new(self, FailureNote, msg).emit()
}
pub fn fatal(&self, msg: &str) -> FatalError {
if self.flags.treat_err_as_bug {
self.bug(msg);
@ -634,6 +660,7 @@ impl Handler {
DiagnosticBuilder::new(self, Fatal, msg).emit();
FatalError
}
pub fn err(&self, msg: &str) {
if self.flags.treat_err_as_bug {
self.bug(msg);
@ -641,19 +668,23 @@ impl Handler {
let mut db = DiagnosticBuilder::new(self, Error, msg);
db.emit();
}
pub fn warn(&self, msg: &str) {
let mut db = DiagnosticBuilder::new(self, Warning, msg);
db.emit();
}
pub fn note_without_error(&self, msg: &str) {
let mut db = DiagnosticBuilder::new(self, Note, msg);
db.emit();
}
pub fn bug(&self, msg: &str) -> ! {
let mut db = DiagnosticBuilder::new(self, Bug, msg);
db.emit();
panic!("{}", ExplicitBug);
}
pub fn unimpl(&self, msg: &str) -> ! {
self.bug(&format!("unimplemented {}", msg));
}
@ -725,6 +756,7 @@ impl Handler {
}
FatalError.raise();
}
pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
if lvl == Warning && !self.flags.can_emit_warnings {
return;
@ -736,6 +768,7 @@ impl Handler {
self.abort_if_errors();
}
}
pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: DiagnosticId, lvl: Level) {
if lvl == Warning && !self.flags.can_emit_warnings {
return;

View File

@ -1,7 +1,9 @@
use crate::syntax_pos::{BytePos, SourceFile};
use debug_unreachable::debug_unreachable;
use std::str;
use debug_unreachable::debug_unreachable;
use crate::syntax_pos::{BytePos, SourceFile};
pub type SourceFileInput<'a> = StringInput<'a>;
/// Implementation of [Input].
@ -253,9 +255,10 @@ pub trait Input: Clone {
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
use crate::{FileName, FilePathMapping, SourceMap};
use std::sync::Arc;
fn with_test_sess<F>(src: &str, f: F)
where

View File

@ -30,6 +30,14 @@
#![deny(unused)]
#![cfg_attr(docsrs, feature(doc_cfg))]
use std::fmt::Debug;
pub use ast_node::{ast_node, ast_serde, DeserializeEnum, Spanned};
pub use from_variant::FromVariant;
use serde::Serialize;
pub use swc_eq_ignore_macros::{EqIgnoreSpan, TypeEq};
pub use swc_visit::chain;
pub use self::{
eq::{EqIgnoreSpan, TypeEq},
errors::{SourceMapper, SourceMapperDyn},
@ -41,12 +49,6 @@ pub use self::{
source_map::{FileLines, FileLoader, FilePathMapping, SourceMap, SpanSnippetError},
syntax_pos::LineCol,
};
pub use ast_node::{ast_node, ast_serde, DeserializeEnum, Spanned};
pub use from_variant::FromVariant;
use serde::Serialize;
use std::fmt::Debug;
pub use swc_eq_ignore_macros::{EqIgnoreSpan, TypeEq};
pub use swc_visit::chain;
#[doc(hidden)]
pub mod private;

View File

@ -1,6 +1,7 @@
//! This module reexports items from `swc_visit` with some swc-specific traits.
use std::borrow::Cow;
pub use swc_visit::*;
/// A named compiler pass.

View File

@ -4,10 +4,12 @@
//! `swc_common`.
#![allow(unused)]
use crate::{syntax_pos::Mark, SyntaxContext};
use anyhow::Error;
use std::any::type_name;
use anyhow::Error;
use crate::{syntax_pos::Mark, SyntaxContext};
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(

View File

@ -1,9 +1,10 @@
use std::{borrow::Cow, rc::Rc, sync::Arc};
pub use crate::syntax_pos::{
hygiene, BytePos, CharPos, FileName, Globals, Loc, LocWithOpt, Mark, MultiSpan, SourceFile,
SourceFileAndBytePos, SourceFileAndLine, Span, SpanLinesError, SyntaxContext, DUMMY_SP,
GLOBALS, NO_EXPANSION,
};
use std::{borrow::Cow, rc::Rc, sync::Arc};
///
/// # Derive

View File

@ -1,10 +1,11 @@
use siphasher::sip128::{Hash128, Hasher128, SipHasher24};
use std::{
hash::{BuildHasher, Hash, Hasher},
marker::PhantomData,
mem,
};
use siphasher::sip128::{Hash128, Hasher128, SipHasher24};
/// When hashing something that ends up affecting properties like symbol names,
/// we want these symbol names to be calculated independently of other factors
/// like what architecture you're compiling *from*.
@ -327,6 +328,7 @@ impl<CTX> HashStable<CTX> for String {
impl<HCX> ToStableHashKey<HCX> for String {
type KeyType = String;
#[inline]
fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
self.clone()

View File

@ -16,16 +16,6 @@
//! `spans` and used pervasively in the compiler. They are absolute positions
//! within the SourceMap, which upon request can be converted to line and column
//! information, source code snippets, etc.
pub use crate::syntax_pos::*;
use crate::{
collections::AHashMap,
errors::SourceMapper,
rustc_data_structures::stable_hasher::StableHasher,
sync::{Lock, LockGuard, Lrc, MappedLockGuard},
};
use once_cell::sync::Lazy;
#[cfg(feature = "sourcemap")]
use sourcemap::SourceMapBuilder;
use std::{
cmp,
cmp::{max, min},
@ -35,8 +25,20 @@ use std::{
path::{Path, PathBuf},
sync::atomic::{AtomicUsize, Ordering::SeqCst},
};
use once_cell::sync::Lazy;
#[cfg(feature = "sourcemap")]
use sourcemap::SourceMapBuilder;
use tracing::debug;
pub use crate::syntax_pos::*;
use crate::{
collections::AHashMap,
errors::SourceMapper,
rustc_data_structures::stable_hasher::StableHasher,
sync::{Lock, LockGuard, Lrc, MappedLockGuard},
};
static CURRENT_DIR: Lazy<Option<PathBuf>> = Lazy::new(|| env::current_dir().ok());
// _____________________________________________________________________________
@ -1200,21 +1202,27 @@ impl SourceMapper for SourceMap {
fn lookup_char_pos(&self, pos: BytePos) -> Loc {
self.lookup_char_pos(pos)
}
fn span_to_lines(&self, sp: Span) -> FileLinesResult {
self.span_to_lines(sp)
}
fn span_to_string(&self, sp: Span) -> String {
self.span_to_string(sp)
}
fn span_to_filename(&self, sp: Span) -> FileName {
self.span_to_filename(sp)
}
fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
self.merge_spans(sp_lhs, sp_rhs)
}
fn call_span_if_macro(&self, sp: Span) -> Span {
sp
}
fn doctest_offset_line(&self, line: usize) -> usize {
self.doctest_offset_line(line)
}

View File

@ -33,35 +33,37 @@
//! `rustc_erase_owner!` erases a OwningRef owner into Erased or Erased + Send +
//! Sync depending on the value of cfg!(parallel_queries).
#[cfg(feature = "concurrent")]
use parking_lot::{Mutex as InnerLock, RwLock as InnerRwLock};
#[cfg(not(feature = "concurrent"))]
use std::cell::{RefCell as InnerRwLock, RefCell as InnerLock};
use std::fmt;
#[cfg(feature = "concurrent")]
pub use self::concurrent::*;
#[cfg(not(feature = "concurrent"))]
pub use self::single::*;
use std::{
cmp::Ordering,
collections::HashMap,
fmt,
fmt::{Debug, Formatter},
hash::{BuildHasher, Hash},
};
#[cfg(feature = "concurrent")]
use parking_lot::{Mutex as InnerLock, RwLock as InnerRwLock};
#[cfg(feature = "concurrent")]
pub use self::concurrent::*;
#[cfg(not(feature = "concurrent"))]
pub use self::single::*;
#[cfg(feature = "concurrent")]
mod concurrent {
pub use std::{
marker::{Send, Sync},
sync::Arc as Lrc,
};
pub use once_cell::sync::{Lazy, OnceCell};
pub use parking_lot::{
MappedMutexGuard as MappedLockGuard, MappedRwLockReadGuard as MappedReadGuard,
MappedRwLockWriteGuard as MappedWriteGuard, MutexGuard as LockGuard,
RwLockReadGuard as ReadGuard, RwLockWriteGuard as WriteGuard,
};
pub use std::{
marker::{Send, Sync},
sync::Arc as Lrc,
};
}
#[cfg(not(feature = "concurrent"))]

View File

@ -1,8 +1,3 @@
pub use self::hygiene::{Mark, SyntaxContext};
use crate::{rustc_data_structures::stable_hasher::StableHasher, sync::Lrc};
#[cfg(feature = "parking_lot")]
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
#[cfg(not(feature = "parking_lot"))]
use std::sync::Mutex;
use std::{
@ -12,8 +7,15 @@ use std::{
ops::{Add, Sub},
path::PathBuf,
};
#[cfg(feature = "parking_lot")]
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use url::Url;
pub use self::hygiene::{Mark, SyntaxContext};
use crate::{rustc_data_structures::stable_hasher::StableHasher, sync::Lrc};
mod analyze_source_file;
pub mod hygiene;
@ -202,6 +204,7 @@ impl Span {
pub fn lo(self) -> BytePos {
self.lo
}
#[inline]
pub fn new(mut lo: BytePos, mut hi: BytePos, ctxt: SyntaxContext) -> Self {
if lo > hi {
@ -215,6 +218,7 @@ impl Span {
pub fn with_lo(&self, lo: BytePos) -> Span {
Span::new(lo, self.hi, self.ctxt)
}
#[inline]
pub fn hi(self) -> BytePos {
self.hi
@ -224,10 +228,12 @@ impl Span {
pub fn with_hi(&self, hi: BytePos) -> Span {
Span::new(self.lo, hi, self.ctxt)
}
#[inline]
pub fn ctxt(self) -> SyntaxContext {
self.ctxt
}
#[inline]
pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
Span::new(self.lo, self.hi, ctxt)
@ -245,6 +251,7 @@ impl Span {
pub fn shrink_to_lo(self) -> Span {
self.with_hi(self.lo)
}
/// Returns a new span representing an empty span at the end of this span
#[inline]
pub fn shrink_to_hi(self) -> Span {
@ -742,6 +749,7 @@ impl SourceFile {
pub fn byte_length(&self) -> u32 {
self.end_pos.0 - self.start_pos.0
}
pub fn count_lines(&self) -> usize {
self.lines.len()
}

View File

@ -7,9 +7,10 @@
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use super::*;
use unicode_width::UnicodeWidthChar;
use super::*;
/// Finds all newlines, multi-byte characters, and non-narrow characters in a
/// SourceFile.
///

View File

@ -15,14 +15,16 @@
//! and definition contexts*. J. Funct. Program. 22, 2 (March 2012), 181-216.
//! DOI=10.1017/S0956796812000093 <https://doi.org/10.1017/S0956796812000093>
use super::GLOBALS;
use crate::collections::AHashMap;
use serde::{Deserialize, Serialize};
use std::{
collections::{HashMap, HashSet},
fmt,
};
use serde::{Deserialize, Serialize};
use super::GLOBALS;
use crate::collections::AHashMap;
/// A SyntaxContext represents a chain of macro expansions (represented by
/// marks).
#[derive(Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord, Hash, Serialize, Deserialize)]
@ -75,8 +77,7 @@ impl Mark {
pub fn fresh(parent: Mark) -> Self {
// Note: msvc tries to link against proxied fn for normal build,
// have to limit build target to wasm only to avoid it.
#[cfg(feature = "plugin-mode")]
#[cfg(target_arch = "wasm32")]
#[cfg(all(feature = "plugin-mode", target_arch = "wasm32"))]
return Mark(unsafe {
__mark_fresh_proxy(
parent
@ -88,20 +89,12 @@ impl Mark {
.expect("Should able to convert i32 into mark")
});
#[cfg(not(feature = "plugin-mode"))]
return HygieneData::with(|data| {
data.marks.push(MarkData {
parent,
is_builtin: false,
});
Mark(data.marks.len() as u32 - 1)
});
// https://github.com/swc-project/swc/pull/3492#discussion_r802224857
// This is unreachable path for noraml execution. However for some
// cases like running plugin's test without targeting wasm32-*, we'll
// allow to not panic in here at least.
#[cfg(all(feature = "plugin-mode", not(target_arch = "wasm32")))]
#[cfg(not(all(feature = "plugin-mode", target_arch = "wasm32")))]
return HygieneData::with(|data| {
data.marks.push(MarkData {
parent,

View File

@ -29,6 +29,7 @@ where
I: IntoIterator<Item = B::Item>,
{
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
if let Some(b) = self.base.next() {
return Some(b);

View File

@ -1,6 +1,7 @@
use crate::{Span, DUMMY_SP};
use std::mem::replace;
use crate::{Span, DUMMY_SP};
/// Helper for people who are working on `VisitMut`.
///
///

View File

@ -1,7 +1,8 @@
#![cfg(feature = "concurrent")]
use rayon::prelude::*;
use std::{env, path::PathBuf, sync::Arc};
use rayon::prelude::*;
use swc_common::{sync::Lrc, FilePathMapping, SourceFile, SourceMap};
#[test]

View File

@ -1,6 +1,7 @@
use crate::Str;
use swc_common::{ast_node, Span};
use crate::Str;
#[ast_node("CharsetRule")]
pub struct CharsetRule {
pub span: Span,

View File

@ -1,6 +1,7 @@
use crate::{DashedIdent, DeclarationBlockItem, Ident};
use swc_common::{ast_node, Span};
use crate::{DashedIdent, DeclarationBlockItem, Ident};
#[ast_node]
pub enum ColorProfileName {
#[tag("DashedIdent")]

View File

@ -1,6 +1,7 @@
use crate::{CustomIdent, DeclarationBlockItem};
use swc_common::{ast_node, Span};
use crate::{CustomIdent, DeclarationBlockItem};
#[ast_node("CounterStyleRule")]
pub struct CounterStyleRule {
pub span: Span,

View File

@ -1,6 +1,7 @@
use crate::{Function, Rule, Url};
use swc_common::{ast_node, Span};
use crate::{Function, Rule, Url};
#[ast_node("DocumentRule")]
pub struct DocumentRule {
pub span: Span,

View File

@ -1,6 +1,7 @@
use crate::{Declaration, Function, Ident, MediaQueryList, Str, SupportsCondition, Url};
use swc_common::{ast_node, Span};
use crate::{Declaration, Function, Ident, MediaQueryList, Str, SupportsCondition, Url};
#[ast_node]
pub enum ImportHref {
#[tag("Url")]

View File

@ -1,6 +1,7 @@
use crate::{Block, CustomIdent, Ident, Percent, Str};
use swc_common::{ast_node, Span};
use crate::{Block, CustomIdent, Ident, Percent, Str};
#[ast_node("KeyframesRule")]
pub struct KeyframesRule {
pub span: Span,

View File

@ -1,6 +1,7 @@
use crate::{Ident, Rule};
use swc_common::{ast_node, Span};
use crate::{Ident, Rule};
#[ast_node("LayerName")]
pub struct LayerName {
pub span: Span,

View File

@ -1,7 +1,8 @@
use crate::{Dimension, Ident, Number, Ratio, Rule};
use string_enum::StringEnum;
use swc_common::{ast_node, EqIgnoreSpan, Span};
use crate::{Dimension, Ident, Number, Ratio, Rule};
#[ast_node("MediaRule")]
pub struct MediaRule {
pub span: Span,

View File

@ -1,10 +1,11 @@
use is_macro::Is;
use swc_common::{ast_node, Span};
pub use self::{
charset::*, color_profile::*, counter_style::*, document::*, import::*, keyframe::*, layer::*,
media::*, page::*, property::*, support::*,
};
use crate::{Block, DashedIdent, Ident, SimpleBlock, Str, Url, Value};
use is_macro::Is;
use swc_common::{ast_node, Span};
mod charset;
mod color_profile;

View File

@ -1,6 +1,7 @@
use crate::{DeclarationBlockItem, Ident};
use swc_common::{ast_node, Span};
use crate::{DeclarationBlockItem, Ident};
#[ast_node("PageRule")]
pub struct PageRule {
pub span: Span,

View File

@ -1,6 +1,7 @@
use crate::{DashedIdent, DeclarationBlockItem};
use swc_common::{ast_node, Span};
use crate::{DashedIdent, DeclarationBlockItem};
#[ast_node("PropertyRule")]
pub struct PropertyRule {
pub span: Span,

View File

@ -1,6 +1,7 @@
use crate::{Declaration, Rule};
use swc_common::{ast_node, Span};
use crate::{Declaration, Rule};
#[ast_node("SupportsRule")]
pub struct SupportsRule {
pub span: Span,

View File

@ -1,9 +1,10 @@
use crate::{Ident, Str, Tokens};
use is_macro::Is;
use string_enum::StringEnum;
use swc_atoms::JsWord;
use swc_common::{ast_node, EqIgnoreSpan, Span};
use crate::{Ident, Str, Tokens};
#[ast_node("SelectorList")]
pub struct SelectorList {
pub span: Span,

View File

@ -1,7 +1,8 @@
use crate::{AtRule, DashedIdent, Ident, SelectorList, Tokens, Value};
use is_macro::Is;
use swc_common::{ast_node, Span};
use crate::{AtRule, DashedIdent, Ident, SelectorList, Tokens, Value};
#[ast_node("Stylesheet")]
pub struct Stylesheet {
pub span: Span,

View File

@ -1,8 +1,9 @@
use crate::{DashedIdent, Ident, SimpleBlock, Str, Tokens};
use string_enum::StringEnum;
use swc_atoms::JsWord;
use swc_common::{ast_node, EqIgnoreSpan, Span};
use crate::{DashedIdent, Ident, SimpleBlock, Str, Tokens};
#[ast_node]
pub enum Value {
#[tag("SimpleBlock")]

View File

@ -1,6 +1,7 @@
use crate::{writer::CssWriter, CodeGenerator};
use std::ops::{Deref, DerefMut};
use crate::{writer::CssWriter, CodeGenerator};
impl<W> CodeGenerator<W>
where
W: CssWriter,

Some files were not shown because too many files have changed in this diff Show More