diff options
Diffstat (limited to 'cli')
-rw-r--r-- | cli/ast.rs | 24 | ||||
-rw-r--r-- | cli/bench/http.rs | 6 | ||||
-rw-r--r-- | cli/bench/lsp.rs | 10 | ||||
-rw-r--r-- | cli/bench/main.rs | 17 | ||||
-rw-r--r-- | cli/bench/throughput.rs | 6 | ||||
-rw-r--r-- | cli/file_fetcher.rs | 28 | ||||
-rw-r--r-- | cli/fs_util.rs | 2 | ||||
-rw-r--r-- | cli/lsp/analysis.rs | 8 | ||||
-rw-r--r-- | cli/lsp/diagnostics.rs | 46 | ||||
-rw-r--r-- | cli/lsp/documents.rs | 2 | ||||
-rw-r--r-- | cli/lsp/tsc.rs | 35 | ||||
-rw-r--r-- | cli/main.rs | 4 | ||||
-rw-r--r-- | cli/media_type.rs | 36 | ||||
-rw-r--r-- | cli/module_graph.rs | 50 | ||||
-rw-r--r-- | cli/program_state.rs | 10 | ||||
-rw-r--r-- | cli/source_maps.rs | 6 | ||||
-rw-r--r-- | cli/tools/coverage.rs | 14 | ||||
-rw-r--r-- | cli/tools/installer.rs | 3 | ||||
-rw-r--r-- | cli/tools/test_runner.rs | 3 | ||||
-rw-r--r-- | cli/tsc.rs | 8 | ||||
-rw-r--r-- | cli/tsc_config.rs | 4 |
21 files changed, 143 insertions, 179 deletions
diff --git a/cli/ast.rs b/cli/ast.rs index 3979af0ce..bbd4df74d 100644 --- a/cli/ast.rs +++ b/cli/ast.rs @@ -59,11 +59,11 @@ pub struct Location { pub col: usize, } -impl Into<Location> for swc_common::Loc { - fn into(self) -> Location { +impl From<swc_common::Loc> for Location { + fn from(swc_loc: swc_common::Loc) -> Self { use swc_common::FileName::*; - let filename = match &self.file.name { + let filename = match &swc_loc.file.name { Real(path_buf) => path_buf.to_string_lossy().to_string(), Custom(str_) => str_.to_string(), _ => panic!("invalid filename"), @@ -71,15 +71,15 @@ impl Into<Location> for swc_common::Loc { Location { filename, - line: self.line, - col: self.col_display, + line: swc_loc.line, + col: swc_loc.col_display, } } } -impl Into<ModuleSpecifier> for Location { - fn into(self) -> ModuleSpecifier { - resolve_url_or_path(&self.filename).unwrap() +impl From<Location> for ModuleSpecifier { + fn from(loc: Location) -> Self { + resolve_url_or_path(&loc.filename).unwrap() } } @@ -174,10 +174,10 @@ fn get_ts_config(tsx: bool, dts: bool) -> TsConfig { pub fn get_syntax(media_type: &MediaType) -> Syntax { match media_type { MediaType::JavaScript => Syntax::Es(get_es_config(false)), - MediaType::JSX => Syntax::Es(get_es_config(true)), + MediaType::Jsx => Syntax::Es(get_es_config(true)), MediaType::TypeScript => Syntax::Typescript(get_ts_config(false, false)), MediaType::Dts => Syntax::Typescript(get_ts_config(false, true)), - MediaType::TSX => Syntax::Typescript(get_ts_config(true, false)), + MediaType::Tsx => Syntax::Typescript(get_ts_config(true, false)), _ => Syntax::Es(get_es_config(false)), } } @@ -429,10 +429,10 @@ pub fn parse_with_source_map( comments.with_leading(module.span.lo, |comments| comments.to_vec()); Ok(ParsedModule { + comments, leading_comments, module, source_map, - comments, source_file, }) } @@ -711,7 +711,7 @@ mod tests { } } "#; - let module = parse(specifier.as_str(), source, &MediaType::TSX) + let module = parse(specifier.as_str(), source, &MediaType::Tsx) .expect("could not parse module"); let (code, _) = module .transpile(&EmitOptions::default()) diff --git a/cli/bench/http.rs b/cli/bench/http.rs index af7eef942..f954223a0 100644 --- a/cli/bench/http.rs +++ b/cli/bench/http.rs @@ -1,9 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. use super::Result; -use std::{ - collections::HashMap, path::PathBuf, process::Command, time::Duration, -}; +use std::{collections::HashMap, path::Path, process::Command, time::Duration}; pub use test_util::{parse_wrk_output, WrkOutput as HttpBenchmarkResult}; // Some of the benchmarks in this file have been renamed. In case the history @@ -15,7 +13,7 @@ pub use test_util::{parse_wrk_output, WrkOutput as HttpBenchmarkResult}; const DURATION: &str = "20s"; pub(crate) fn benchmark( - target_path: &PathBuf, + target_path: &Path, ) -> Result<HashMap<String, HttpBenchmarkResult>> { let deno_exe = test_util::deno_exe_path(); let deno_exe = deno_exe.to_str().unwrap(); diff --git a/cli/bench/lsp.rs b/cli/bench/lsp.rs index 63e1821d4..da02db486 100644 --- a/cli/bench/lsp.rs +++ b/cli/bench/lsp.rs @@ -14,7 +14,7 @@ use std::collections::HashMap; use std::io::BufRead; use std::io::Read; use std::io::Write; -use std::path::PathBuf; +use std::path::Path; use std::process::ChildStdin; use std::process::ChildStdout; use std::process::Command; @@ -135,7 +135,7 @@ impl Drop for LspClient { } impl LspClient { - fn new(deno_exe: &PathBuf) -> Result<Self, AnyError> { + fn new(deno_exe: &Path) -> Result<Self, AnyError> { let mut child = Command::new(deno_exe) .arg("lsp") .stdin(Stdio::piped()) @@ -244,7 +244,7 @@ impl LspClient { /// A benchmark that opens a 8000+ line TypeScript document, adds a function to /// the end of the document and does a level of hovering and gets quick fix /// code actions. -fn bench_big_file_edits(deno_exe: &PathBuf) -> Result<Duration, AnyError> { +fn bench_big_file_edits(deno_exe: &Path) -> Result<Duration, AnyError> { let mut client = LspClient::new(deno_exe)?; let params: Value = serde_json::from_slice(FIXTURE_INIT_JSON)?; @@ -302,7 +302,7 @@ fn bench_big_file_edits(deno_exe: &PathBuf) -> Result<Duration, AnyError> { } /// A test that starts up the LSP, opens a single line document, and exits. -fn bench_startup_shutdown(deno_exe: &PathBuf) -> Result<Duration, AnyError> { +fn bench_startup_shutdown(deno_exe: &Path) -> Result<Duration, AnyError> { let mut client = LspClient::new(deno_exe)?; let params: Value = serde_json::from_slice(FIXTURE_INIT_JSON)?; @@ -338,7 +338,7 @@ fn bench_startup_shutdown(deno_exe: &PathBuf) -> Result<Duration, AnyError> { /// Generate benchmarks for the LSP server. pub(crate) fn benchmarks( - deno_exe: &PathBuf, + deno_exe: &Path, ) -> Result<HashMap<String, u64>, AnyError> { println!("-> Start benchmarking lsp"); let mut exec_times = HashMap::new(); diff --git a/cli/bench/main.rs b/cli/bench/main.rs index 8a91b86d6..8890ec79c 100644 --- a/cli/bench/main.rs +++ b/cli/bench/main.rs @@ -8,6 +8,7 @@ use std::collections::HashMap; use std::convert::From; use std::env; use std::fs; +use std::path::Path; use std::path::PathBuf; use std::process::Command; use std::process::Stdio; @@ -126,8 +127,8 @@ const EXEC_TIME_BENCHMARKS: &[(&str, &[&str], Option<i32>)] = &[ const RESULT_KEYS: &[&str] = &["mean", "stddev", "user", "system", "min", "max"]; fn run_exec_time( - deno_exe: &PathBuf, - target_dir: &PathBuf, + deno_exe: &Path, + target_dir: &Path, ) -> Result<HashMap<String, HashMap<String, f64>>> { let hyperfine_exe = test_util::prebuilt_tool_path("hyperfine"); @@ -218,7 +219,7 @@ fn rlib_size(target_dir: &std::path::Path, prefix: &str) -> u64 { const BINARY_TARGET_FILES: &[&str] = &["CLI_SNAPSHOT.bin", "COMPILER_SNAPSHOT.bin"]; -fn get_binary_sizes(target_dir: &PathBuf) -> Result<HashMap<String, u64>> { +fn get_binary_sizes(target_dir: &Path) -> Result<HashMap<String, u64>> { let mut sizes = HashMap::<String, u64>::new(); let mut mtimes = HashMap::<String, SystemTime>::new(); @@ -276,7 +277,7 @@ const BUNDLES: &[(&str, &str)] = &[ ("file_server", "./test_util/std/http/file_server.ts"), ("gist", "./test_util/std/examples/gist.ts"), ]; -fn bundle_benchmark(deno_exe: &PathBuf) -> Result<HashMap<String, u64>> { +fn bundle_benchmark(deno_exe: &Path) -> Result<HashMap<String, u64>> { let mut sizes = HashMap::<String, u64>::new(); for (name, url) in BUNDLES { @@ -304,7 +305,7 @@ fn bundle_benchmark(deno_exe: &PathBuf) -> Result<HashMap<String, u64>> { Ok(sizes) } -fn run_throughput(deno_exe: &PathBuf) -> Result<HashMap<String, f64>> { +fn run_throughput(deno_exe: &Path) -> Result<HashMap<String, f64>> { let mut m = HashMap::<String, f64>::new(); m.insert("100M_tcp".to_string(), throughput::tcp(deno_exe, 100)?); @@ -315,7 +316,7 @@ fn run_throughput(deno_exe: &PathBuf) -> Result<HashMap<String, f64>> { Ok(m) } -fn run_http(target_dir: &PathBuf, new_data: &mut BenchResult) -> Result<()> { +fn run_http(target_dir: &Path, new_data: &mut BenchResult) -> Result<()> { let stats = http::benchmark(target_dir)?; new_data.req_per_sec = stats @@ -332,7 +333,7 @@ fn run_http(target_dir: &PathBuf, new_data: &mut BenchResult) -> Result<()> { } fn run_strace_benchmarks( - deno_exe: &PathBuf, + deno_exe: &Path, new_data: &mut BenchResult, ) -> Result<()> { use std::io::Read; @@ -372,7 +373,7 @@ fn run_strace_benchmarks( Ok(()) } -fn run_max_mem_benchmark(deno_exe: &PathBuf) -> Result<HashMap<String, u64>> { +fn run_max_mem_benchmark(deno_exe: &Path) -> Result<HashMap<String, u64>> { let mut results = HashMap::<String, u64>::new(); for (name, args, return_code) in EXEC_TIME_BENCHMARKS { diff --git a/cli/bench/throughput.rs b/cli/bench/throughput.rs index 83032e7a1..de18089bb 100644 --- a/cli/bench/throughput.rs +++ b/cli/bench/throughput.rs @@ -2,7 +2,7 @@ use super::Result; use std::{ - path::PathBuf, + path::Path, process::Command, time::{Duration, Instant}, }; @@ -11,7 +11,7 @@ const MB: usize = 1024 * 1024; const SERVER_ADDR: &str = "0.0.0.0:4544"; const CLIENT_ADDR: &str = "127.0.0.1 4544"; -pub(crate) fn cat(deno_exe: &PathBuf, megs: usize) -> f64 { +pub(crate) fn cat(deno_exe: &Path, megs: usize) -> f64 { let size = megs * MB; let shell_cmd = format!( "{} run --allow-read cli/tests/cat.ts /dev/zero | head -c {}", @@ -28,7 +28,7 @@ pub(crate) fn cat(deno_exe: &PathBuf, megs: usize) -> f64 { (end - start).as_secs_f64() } -pub(crate) fn tcp(deno_exe: &PathBuf, megs: usize) -> Result<f64> { +pub(crate) fn tcp(deno_exe: &Path, megs: usize) -> Result<f64> { let size = megs * MB; // The GNU flavor of `nc` requires the `-N` flag to shutdown the network socket after EOF on stdin diff --git a/cli/file_fetcher.rs b/cli/file_fetcher.rs index 4223654dc..3803c93c9 100644 --- a/cli/file_fetcher.rs +++ b/cli/file_fetcher.rs @@ -223,8 +223,8 @@ pub fn map_content_type( | "application/node" => { map_js_like_extension(specifier, MediaType::JavaScript) } - "text/jsx" => MediaType::JSX, - "text/tsx" => MediaType::TSX, + "text/jsx" => MediaType::Jsx, + "text/tsx" => MediaType::Tsx, "application/json" | "text/json" => MediaType::Json, "application/wasm" => MediaType::Wasm, // Handle plain and possibly webassembly @@ -264,8 +264,8 @@ fn map_js_like_extension( None => default, Some(os_str) => match os_str.to_str() { None => default, - Some("jsx") => MediaType::JSX, - Some("tsx") => MediaType::TSX, + Some("jsx") => MediaType::Jsx, + Some("tsx") => MediaType::Tsx, // Because DTS files do not have a separate media type, or a unique // extension, we have to "guess" at those things that we consider that // look like TypeScript, and end with `.d.ts` are DTS files. @@ -685,8 +685,8 @@ mod tests { ("data:text/plain,Hello%2C%20Deno!", true, MediaType::Unknown, "text/plain", "Hello, Deno!"), ("data:,Hello%2C%20Deno!", true, MediaType::Unknown, "", "Hello, Deno!"), ("data:application/javascript,console.log(\"Hello, Deno!\");%0A", true, MediaType::JavaScript, "application/javascript", "console.log(\"Hello, Deno!\");\n"), - ("data:text/jsx;base64,ZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24oKSB7CiAgcmV0dXJuIDxkaXY+SGVsbG8gRGVubyE8L2Rpdj4KfQo=", true, MediaType::JSX, "text/jsx;base64", "export default function() {\n return <div>Hello Deno!</div>\n}\n"), - ("data:text/tsx;base64,ZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24oKSB7CiAgcmV0dXJuIDxkaXY+SGVsbG8gRGVubyE8L2Rpdj4KfQo=", true, MediaType::TSX, "text/tsx;base64", "export default function() {\n return <div>Hello Deno!</div>\n}\n"), + ("data:text/jsx;base64,ZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24oKSB7CiAgcmV0dXJuIDxkaXY+SGVsbG8gRGVubyE8L2Rpdj4KfQo=", true, MediaType::Jsx, "text/jsx;base64", "export default function() {\n return <div>Hello Deno!</div>\n}\n"), + ("data:text/tsx;base64,ZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24oKSB7CiAgcmV0dXJuIDxkaXY+SGVsbG8gRGVubyE8L2Rpdj4KfQo=", true, MediaType::Tsx, "text/tsx;base64", "export default function() {\n return <div>Hello Deno!</div>\n}\n"), ]; for ( @@ -744,10 +744,10 @@ mod tests { let fixtures = vec![ // Extension only (file_url!("/foo/bar.ts"), None, MediaType::TypeScript, None), - (file_url!("/foo/bar.tsx"), None, MediaType::TSX, None), + (file_url!("/foo/bar.tsx"), None, MediaType::Tsx, None), (file_url!("/foo/bar.d.ts"), None, MediaType::Dts, None), (file_url!("/foo/bar.js"), None, MediaType::JavaScript, None), - (file_url!("/foo/bar.jsx"), None, MediaType::JSX, None), + (file_url!("/foo/bar.jsx"), None, MediaType::Jsx, None), (file_url!("/foo/bar.json"), None, MediaType::Json, None), (file_url!("/foo/bar.wasm"), None, MediaType::Wasm, None), (file_url!("/foo/bar.cjs"), None, MediaType::JavaScript, None), @@ -823,13 +823,13 @@ mod tests { ( "https://deno.land/x/mod", Some("text/jsx".to_string()), - MediaType::JSX, + MediaType::Jsx, None, ), ( "https://deno.land/x/mod", Some("text/tsx".to_string()), - MediaType::TSX, + MediaType::Tsx, None, ), ( @@ -860,25 +860,25 @@ mod tests { ( "https://deno.land/x/mod.tsx", Some("application/typescript".to_string()), - MediaType::TSX, + MediaType::Tsx, None, ), ( "https://deno.land/x/mod.tsx", Some("application/javascript".to_string()), - MediaType::TSX, + MediaType::Tsx, None, ), ( "https://deno.land/x/mod.jsx", Some("application/javascript".to_string()), - MediaType::JSX, + MediaType::Jsx, None, ), ( "https://deno.land/x/mod.jsx", Some("application/x-typescript".to_string()), - MediaType::JSX, + MediaType::Jsx, None, ), ( diff --git a/cli/fs_util.rs b/cli/fs_util.rs index 04cdfff75..584d62598 100644 --- a/cli/fs_util.rs +++ b/cli/fs_util.rs @@ -248,7 +248,7 @@ mod tests { #[test] fn test_collect_files() { - fn create_files(dir_path: &PathBuf, files: &[&str]) { + fn create_files(dir_path: &Path, files: &[&str]) { std::fs::create_dir(dir_path).expect("Failed to create directory"); for f in files { let path = dir_path.join(f); diff --git a/cli/lsp/analysis.rs b/cli/lsp/analysis.rs index 4c087cfa2..3359fc666 100644 --- a/cli/lsp/analysis.rs +++ b/cli/lsp/analysis.rs @@ -274,7 +274,7 @@ pub fn analyze_dependencies( let resolved_import = resolve_import(&import, specifier, maybe_import_map); if media_type == &MediaType::JavaScript - || media_type == &MediaType::JSX + || media_type == &MediaType::Jsx { maybe_type = Some(resolved_import) } else { @@ -297,11 +297,7 @@ pub fn analyze_dependencies( let maybe_resolved_type_dependency = // Check for `@deno-types` pragmas that affect the import if let Some(comment) = desc.leading_comments.last() { - if let Some(deno_types) = parse_deno_types(&comment.text).as_ref() { - Some(resolve_import(deno_types, specifier, maybe_import_map)) - } else { - None - } + parse_deno_types(&comment.text).as_ref().map(|deno_types| resolve_import(deno_types, specifier, maybe_import_map)) } else { None }; diff --git a/cli/lsp/diagnostics.rs b/cli/lsp/diagnostics.rs index f720299d7..d4ec3d494 100644 --- a/cli/lsp/diagnostics.rs +++ b/cli/lsp/diagnostics.rs @@ -461,31 +461,27 @@ fn get_diagnostic_message(diagnostic: &diagnostics::Diagnostic) -> String { fn to_lsp_related_information( related_information: &Option<Vec<diagnostics::Diagnostic>>, ) -> Option<Vec<lsp::DiagnosticRelatedInformation>> { - if let Some(related) = related_information { - Some( - related - .iter() - .filter_map(|ri| { - if let (Some(source), Some(start), Some(end)) = - (&ri.source, &ri.start, &ri.end) - { - let uri = lsp::Url::parse(&source).unwrap(); - Some(lsp::DiagnosticRelatedInformation { - location: lsp::Location { - uri, - range: to_lsp_range(start, end), - }, - message: get_diagnostic_message(&ri), - }) - } else { - None - } - }) - .collect(), - ) - } else { - None - } + related_information.as_ref().map(|related| { + related + .iter() + .filter_map(|ri| { + if let (Some(source), Some(start), Some(end)) = + (&ri.source, &ri.start, &ri.end) + { + let uri = lsp::Url::parse(&source).unwrap(); + Some(lsp::DiagnosticRelatedInformation { + location: lsp::Location { + uri, + range: to_lsp_range(start, end), + }, + message: get_diagnostic_message(&ri), + }) + } else { + None + } + }) + .collect() + }) } fn ts_json_to_diagnostics( diff --git a/cli/lsp/documents.rs b/cli/lsp/documents.rs index da393fbac..47a23eb49 100644 --- a/cli/lsp/documents.rs +++ b/cli/lsp/documents.rs @@ -154,7 +154,7 @@ impl DocumentCache { } pub fn len(&self) -> usize { - self.docs.iter().count() + self.docs.len() } pub fn line_index(&self, specifier: &ModuleSpecifier) -> Option<LineIndex> { diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs index 7569036f5..d3fec5d64 100644 --- a/cli/lsp/tsc.rs +++ b/cli/lsp/tsc.rs @@ -166,11 +166,7 @@ pub async fn get_asset( .request(state_snapshot, RequestMethod::GetAsset(specifier.clone())) .await?; let maybe_text: Option<String> = serde_json::from_value(res)?; - let maybe_asset = if let Some(text) = maybe_text { - Some(AssetDocument::new(text)) - } else { - None - }; + let maybe_asset = maybe_text.map(AssetDocument::new); Ok(maybe_asset) } } @@ -183,7 +179,7 @@ fn display_parts_to_string(parts: &[SymbolDisplayPart]) -> String { .join("") } -fn get_tag_body_text(tag: &JSDocTagInfo) -> Option<String> { +fn get_tag_body_text(tag: &JsDocTagInfo) -> Option<String> { tag.text.as_ref().map(|text| match tag.name.as_str() { "example" => { let caption_regex = @@ -209,7 +205,7 @@ fn get_tag_body_text(tag: &JSDocTagInfo) -> Option<String> { }) } -fn get_tag_documentation(tag: &JSDocTagInfo) -> String { +fn get_tag_documentation(tag: &JsDocTagInfo) -> String { match tag.name.as_str() { "augments" | "extends" | "param" | "template" => { if let Some(text) = &tag.text { @@ -439,7 +435,7 @@ pub struct SymbolDisplayPart { #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct JSDocTagInfo { +pub struct JsDocTagInfo { name: String, text: Option<String>, } @@ -452,7 +448,7 @@ pub struct QuickInfo { text_span: TextSpan, display_parts: Option<Vec<SymbolDisplayPart>>, documentation: Option<Vec<SymbolDisplayPart>>, - tags: Option<Vec<JSDocTagInfo>>, + tags: Option<Vec<JsDocTagInfo>>, } impl QuickInfo { @@ -536,10 +532,11 @@ impl DocumentSpan { let origin_selection_range = if let Some(original_context_span) = &self.original_context_span { Some(original_context_span.to_range(line_index)) - } else if let Some(original_text_span) = &self.original_text_span { - Some(original_text_span.to_range(line_index)) } else { - None + self + .original_text_span + .as_ref() + .map(|original_text_span| original_text_span.to_range(line_index)) }; let link = lsp::LocationLink { origin_selection_range, @@ -927,7 +924,7 @@ pub struct CompletionEntryDetails { kind_modifiers: String, display_parts: Vec<SymbolDisplayPart>, documentation: Option<Vec<SymbolDisplayPart>>, - tags: Option<Vec<JSDocTagInfo>>, + tags: Option<Vec<JsDocTagInfo>>, code_actions: Option<Vec<CodeAction>>, source: Option<Vec<SymbolDisplayPart>>, } @@ -1261,7 +1258,7 @@ pub struct SignatureHelpItem { separator_display_parts: Vec<SymbolDisplayPart>, parameters: Vec<SignatureHelpParameter>, documentation: Vec<SymbolDisplayPart>, - tags: Vec<JSDocTagInfo>, + tags: Vec<JsDocTagInfo>, } impl SignatureHelpItem { @@ -1328,12 +1325,9 @@ impl SelectionRange { ) -> lsp::SelectionRange { lsp::SelectionRange { range: self.text_span.to_range(line_index), - parent: match &self.parent { - Some(parent_selection) => { - Some(Box::new(parent_selection.to_selection_range(line_index))) - } - None => None, - }, + parent: self.parent.as_ref().map(|parent_selection| { + Box::new(parent_selection.to_selection_range(line_index)) + }), } } } @@ -1345,6 +1339,7 @@ struct Response { } struct State<'a> { + #[allow(unused)] asset: Option<String>, last_id: usize, response: Option<Response>, diff --git a/cli/main.rs b/cli/main.rs index c73da5e06..c2fa20c1c 100644 --- a/cli/main.rs +++ b/cli/main.rs @@ -497,11 +497,11 @@ async fn eval_command( media_type: if ext.as_str() == "ts" { MediaType::TypeScript } else if ext.as_str() == "tsx" { - MediaType::TSX + MediaType::Tsx } else if ext.as_str() == "js" { MediaType::JavaScript } else { - MediaType::JSX + MediaType::Jsx }, source: String::from_utf8(source_code)?, specifier: main_module.clone(), diff --git a/cli/media_type.rs b/cli/media_type.rs index 922784902..c83716f67 100644 --- a/cli/media_type.rs +++ b/cli/media_type.rs @@ -14,10 +14,10 @@ use std::path::PathBuf; #[derive(Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Debug)] pub enum MediaType { JavaScript = 0, - JSX = 1, + Jsx = 1, TypeScript = 2, Dts = 3, - TSX = 4, + Tsx = 4, Json = 5, Wasm = 6, TsBuildInfo = 7, @@ -29,10 +29,10 @@ impl fmt::Display for MediaType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let value = match self { MediaType::JavaScript => "JavaScript", - MediaType::JSX => "JSX", + MediaType::Jsx => "JSX", MediaType::TypeScript => "TypeScript", MediaType::Dts => "Dts", - MediaType::TSX => "TSX", + MediaType::Tsx => "TSX", MediaType::Json => "Json", MediaType::Wasm => "Wasm", MediaType::TsBuildInfo => "TsBuildInfo", @@ -103,9 +103,9 @@ impl MediaType { } MediaType::TypeScript } - Some("tsx") => MediaType::TSX, + Some("tsx") => MediaType::Tsx, Some("js") => MediaType::JavaScript, - Some("jsx") => MediaType::JSX, + Some("jsx") => MediaType::Jsx, Some("mjs") => MediaType::JavaScript, Some("cjs") => MediaType::JavaScript, Some("json") => MediaType::Json, @@ -124,10 +124,10 @@ impl MediaType { pub fn as_ts_extension(&self) -> &str { match self { MediaType::JavaScript => ".js", - MediaType::JSX => ".jsx", + MediaType::Jsx => ".jsx", MediaType::TypeScript => ".ts", MediaType::Dts => ".d.ts", - MediaType::TSX => ".tsx", + MediaType::Tsx => ".tsx", MediaType::Json => ".json", // TypeScript doesn't have an "unknown", so we will treat WASM as JS for // mapping purposes, though in reality, it is unlikely to ever be passed @@ -149,10 +149,10 @@ impl MediaType { pub fn as_ts_script_kind(&self) -> i32 { match self { MediaType::JavaScript => 1, - MediaType::JSX => 2, + MediaType::Jsx => 2, MediaType::TypeScript => 3, MediaType::Dts => 3, - MediaType::TSX => 4, + MediaType::Tsx => 4, MediaType::Json => 5, _ => 0, } @@ -166,10 +166,10 @@ impl Serialize for MediaType { { let value = match self { MediaType::JavaScript => 0_i32, - MediaType::JSX => 1_i32, + MediaType::Jsx => 1_i32, MediaType::TypeScript => 2_i32, MediaType::Dts => 3_i32, - MediaType::TSX => 4_i32, + MediaType::Tsx => 4_i32, MediaType::Json => 5_i32, MediaType::Wasm => 6_i32, MediaType::TsBuildInfo => 7_i32, @@ -208,13 +208,13 @@ mod tests { MediaType::from(Path::new("foo/bar.ts")), MediaType::TypeScript ); - assert_eq!(MediaType::from(Path::new("foo/bar.tsx")), MediaType::TSX); + assert_eq!(MediaType::from(Path::new("foo/bar.tsx")), MediaType::Tsx); assert_eq!(MediaType::from(Path::new("foo/bar.d.ts")), MediaType::Dts); assert_eq!( MediaType::from(Path::new("foo/bar.js")), MediaType::JavaScript ); - assert_eq!(MediaType::from(Path::new("foo/bar.jsx")), MediaType::JSX); + assert_eq!(MediaType::from(Path::new("foo/bar.jsx")), MediaType::Jsx); assert_eq!(MediaType::from(Path::new("foo/bar.json")), MediaType::Json); assert_eq!(MediaType::from(Path::new("foo/bar.wasm")), MediaType::Wasm); assert_eq!( @@ -256,10 +256,10 @@ mod tests { #[test] fn test_serialization() { assert_eq!(json!(MediaType::JavaScript), json!(0)); - assert_eq!(json!(MediaType::JSX), json!(1)); + assert_eq!(json!(MediaType::Jsx), json!(1)); assert_eq!(json!(MediaType::TypeScript), json!(2)); assert_eq!(json!(MediaType::Dts), json!(3)); - assert_eq!(json!(MediaType::TSX), json!(4)); + assert_eq!(json!(MediaType::Tsx), json!(4)); assert_eq!(json!(MediaType::Json), json!(5)); assert_eq!(json!(MediaType::Wasm), json!(6)); assert_eq!(json!(MediaType::TsBuildInfo), json!(7)); @@ -270,10 +270,10 @@ mod tests { #[test] fn test_display() { assert_eq!(MediaType::JavaScript.to_string(), "JavaScript"); - assert_eq!(MediaType::JSX.to_string(), "JSX"); + assert_eq!(MediaType::Jsx.to_string(), "JSX"); assert_eq!(MediaType::TypeScript.to_string(), "TypeScript"); assert_eq!(MediaType::Dts.to_string(), "Dts"); - assert_eq!(MediaType::TSX.to_string(), "TSX"); + assert_eq!(MediaType::Tsx.to_string(), "TSX"); assert_eq!(MediaType::Json.to_string(), "Json"); assert_eq!(MediaType::Wasm.to_string(), "Wasm"); assert_eq!(MediaType::TsBuildInfo.to_string(), "TsBuildInfo"); diff --git a/cli/module_graph.rs b/cli/module_graph.rs index ad6d01589..f70fc1c41 100644 --- a/cli/module_graph.rs +++ b/cli/module_graph.rs @@ -197,12 +197,10 @@ pub fn parse_ts_reference(comment: &str) -> Option<TypeScriptReference> { Some(TypeScriptReference::Path( captures.get(1).unwrap().as_str().to_string(), )) - } else if let Some(captures) = TYPES_REFERENCE_RE.captures(comment) { - Some(TypeScriptReference::Types( - captures.get(1).unwrap().as_str().to_string(), - )) } else { - None + TYPES_REFERENCE_RE.captures(comment).map(|captures| { + TypeScriptReference::Types(captures.get(1).unwrap().as_str().to_string()) + }) } } @@ -300,17 +298,14 @@ impl Module { module.is_parsed = true; } } - module.maybe_types = if let Some(ref specifier) = cached_module.maybe_types - { - Some(( + module.maybe_types = cached_module.maybe_types.map(|specifier| { + ( specifier.clone(), module .resolve_import(&specifier, None) .expect("could not resolve module"), - )) - } else { - None - }; + ) + }); module } @@ -348,7 +343,7 @@ impl Module { let specifier = self.resolve_import(&import, Some(location.clone()))?; if self.media_type == MediaType::JavaScript - || self.media_type == MediaType::JSX + || self.media_type == MediaType::Jsx { // TODO(kitsonk) we need to specifically update the cache when // this value changes @@ -1073,8 +1068,8 @@ impl Graph { for (_, module_slot) in self.modules.iter_mut() { if let ModuleSlot::Module(module) = module_slot { if !(emit_options.check_js - || module.media_type == MediaType::JSX - || module.media_type == MediaType::TSX + || module.media_type == MediaType::Jsx + || module.media_type == MediaType::Tsx || module.media_type == MediaType::TypeScript) { emitted_files @@ -1274,9 +1269,9 @@ impl Graph { let mut specifiers = HashSet::<&ModuleSpecifier>::new(); for (_, module_slot) in self.modules.iter() { if let ModuleSlot::Module(module) = module_slot { - if module.media_type == MediaType::JSX + if module.media_type == MediaType::Jsx || module.media_type == MediaType::TypeScript - || module.media_type == MediaType::TSX + || module.media_type == MediaType::Tsx { specifiers.insert(&module.specifier); } @@ -1418,7 +1413,7 @@ impl Graph { self.modules.iter().all(|(_, m)| { if let ModuleSlot::Module(m) = m { let needs_emit = match m.media_type { - MediaType::TypeScript | MediaType::TSX | MediaType::JSX => true, + MediaType::TypeScript | MediaType::Tsx | MediaType::Jsx => true, MediaType::JavaScript => check_js, _ => false, }; @@ -1462,7 +1457,7 @@ impl Graph { let check_js = config.get_check_js(); self.modules.iter().any(|(_, m)| match m { ModuleSlot::Module(m) => match m.media_type { - MediaType::TypeScript | MediaType::TSX | MediaType::JSX => true, + MediaType::TypeScript | MediaType::Tsx | MediaType::Jsx => true, MediaType::JavaScript => check_js, _ => false, }, @@ -1618,8 +1613,8 @@ impl Graph { // if we don't have check_js enabled, we won't touch non TypeScript or JSX // modules if !(emit_options.check_js - || module.media_type == MediaType::JSX - || module.media_type == MediaType::TSX + || module.media_type == MediaType::Jsx + || module.media_type == MediaType::Tsx || module.media_type == MediaType::TypeScript) { continue; @@ -1734,11 +1729,8 @@ impl GraphBuilder { maybe_import_map: Option<ImportMap>, maybe_lockfile: Option<Arc<Mutex<Lockfile>>>, ) -> Self { - let internal_import_map = if let Some(import_map) = maybe_import_map { - Some(Arc::new(Mutex::new(import_map))) - } else { - None - }; + let internal_import_map = + maybe_import_map.map(|import_map| Arc::new(Mutex::new(import_map))); GraphBuilder { graph: Graph::new(handler, maybe_lockfile), maybe_import_map: internal_import_map, @@ -2069,8 +2061,8 @@ pub mod tests { let source = "console.log(42);".to_string(); let maybe_version = Some(get_version(&source, &version::deno(), b"")); let module = Module { - source, maybe_version, + source, ..Module::default() }; assert!(module.is_emit_valid(b"")); @@ -2079,8 +2071,8 @@ pub mod tests { let old_source = "console.log(43);"; let maybe_version = Some(get_version(old_source, &version::deno(), b"")); let module = Module { - source, maybe_version, + source, ..Module::default() }; assert!(!module.is_emit_valid(b"")); @@ -2088,8 +2080,8 @@ pub mod tests { let source = "console.log(42);".to_string(); let maybe_version = Some(get_version(&source, "0.0.0", b"")); let module = Module { - source, maybe_version, + source, ..Module::default() }; assert!(!module.is_emit_valid(b"")); diff --git a/cli/program_state.rs b/cli/program_state.rs index bced6a9bc..ebe223ab0 100644 --- a/cli/program_state.rs +++ b/cli/program_state.rs @@ -110,13 +110,9 @@ impl ProgramState { }; let maybe_inspect_host = flags.inspect.or(flags.inspect_brk); - let maybe_inspector_server = match maybe_inspect_host { - Some(host) => Some(Arc::new(InspectorServer::new( - host, - version::get_user_agent(), - ))), - None => None, - }; + let maybe_inspector_server = maybe_inspect_host.map(|host| { + Arc::new(InspectorServer::new(host, version::get_user_agent())) + }); let coverage_dir = flags .coverage_dir diff --git a/cli/source_maps.rs b/cli/source_maps.rs index 3fa265761..8bc070418 100644 --- a/cli/source_maps.rs +++ b/cli/source_maps.rs @@ -48,11 +48,7 @@ pub fn apply_source_map<G: SourceMapGetter>( // source file map. let end_column = match js_error.end_column { Some(ec) => { - if let Some(sc) = start_column { - Some(ec - (js_error.start_column.unwrap() - sc)) - } else { - None - } + start_column.map(|sc| ec - (js_error.start_column.unwrap() - sc)) } _ => None, }; diff --git a/cli/tools/coverage.rs b/cli/tools/coverage.rs index 9e97688a3..9a197eabd 100644 --- a/cli/tools/coverage.rs +++ b/cli/tools/coverage.rs @@ -157,11 +157,8 @@ impl CoverageReporter for LcovCoverageReporter { ) { // TODO(caspervonb) cleanup and reduce duplication between reporters, pre-compute line coverage // elsewhere. - let maybe_source_map = if let Some(source_map) = maybe_source_map { - Some(SourceMap::from_slice(&source_map).unwrap()) - } else { - None - }; + let maybe_source_map = maybe_source_map + .map(|source_map| SourceMap::from_slice(&source_map).unwrap()); let url = Url::parse(&script_coverage.url).unwrap(); let file_path = url.to_file_path().unwrap(); @@ -374,11 +371,8 @@ impl CoverageReporter for PrettyCoverageReporter { maybe_source_map: Option<Vec<u8>>, maybe_original_source: Option<String>, ) { - let maybe_source_map = if let Some(source_map) = maybe_source_map { - Some(SourceMap::from_slice(&source_map).unwrap()) - } else { - None - }; + let maybe_source_map = maybe_source_map + .map(|source_map| SourceMap::from_slice(&source_map).unwrap()); let mut ignored_spans: Vec<Span> = Vec::new(); for item in ast::lex("", script_source, &MediaType::JavaScript) { diff --git a/cli/tools/installer.rs b/cli/tools/installer.rs index 20b0b17ef..a616db7ef 100644 --- a/cli/tools/installer.rs +++ b/cli/tools/installer.rs @@ -14,6 +14,7 @@ use std::io; use std::io::Write; #[cfg(not(windows))] use std::os::unix::fs::PermissionsExt; +use std::path::Path; use std::path::PathBuf; lazy_static! { @@ -318,7 +319,7 @@ pub fn install( Ok(()) } -fn is_in_path(dir: &PathBuf) -> bool { +fn is_in_path(dir: &Path) -> bool { if let Some(paths) = env::var_os("PATH") { for p in env::split_paths(&paths) { if *dir == p { diff --git a/cli/tools/test_runner.rs b/cli/tools/test_runner.rs index e91cad011..df792bd53 100644 --- a/cli/tools/test_runner.rs +++ b/cli/tools/test_runner.rs @@ -6,7 +6,6 @@ use deno_core::error::AnyError; use deno_core::serde_json::json; use deno_core::url::Url; use std::path::Path; -use std::path::PathBuf; fn is_supported(p: &Path) -> bool { use std::path::Component; @@ -34,7 +33,7 @@ fn is_supported(p: &Path) -> bool { pub fn prepare_test_modules_urls( include: Vec<String>, - root_path: &PathBuf, + root_path: &Path, ) -> Result<Vec<Url>, AnyError> { let (include_paths, include_urls): (Vec<String>, Vec<String>) = include.into_iter().partition(|n| !is_remote_url(n)); diff --git a/cli/tsc.rs b/cli/tsc.rs index 78a472dfa..4026f9329 100644 --- a/cli/tsc.rs +++ b/cli/tsc.rs @@ -134,9 +134,9 @@ fn get_tsc_media_type(specifier: &ModuleSpecifier) -> MediaType { } MediaType::TypeScript } - Some("tsx") => MediaType::TSX, + Some("tsx") => MediaType::Tsx, Some("js") => MediaType::JavaScript, - Some("jsx") => MediaType::JSX, + Some("jsx") => MediaType::Jsx, _ => MediaType::Unknown, }, } @@ -634,10 +634,10 @@ mod tests { fn test_get_tsc_media_type() { let fixtures = vec![ ("file:///a.ts", MediaType::TypeScript), - ("file:///a.tsx", MediaType::TSX), + ("file:///a.tsx", MediaType::Tsx), ("file:///a.d.ts", MediaType::Dts), ("file:///a.js", MediaType::JavaScript), - ("file:///a.jsx", MediaType::JSX), + ("file:///a.jsx", MediaType::Jsx), ("file:///a.cjs", MediaType::Unknown), ("file:///a.mjs", MediaType::Unknown), ("file:///a.json", MediaType::Unknown), diff --git a/cli/tsc_config.rs b/cli/tsc_config.rs index 54ed34bf1..b89b3bf61 100644 --- a/cli/tsc_config.rs +++ b/cli/tsc_config.rs @@ -175,7 +175,7 @@ fn jsonc_to_serde(j: JsonValue) -> Value { #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] -struct TSConfigJson { +struct TsConfigJson { compiler_options: Option<HashMap<String, Value>>, exclude: Option<Vec<String>>, extends: Option<String>, @@ -221,7 +221,7 @@ pub fn parse_config( ) -> Result<(Value, Option<IgnoredCompilerOptions>), AnyError> { assert!(!config_text.is_empty()); let jsonc = jsonc_parser::parse_to_value(config_text)?.unwrap(); - let config: TSConfigJson = serde_json::from_value(jsonc_to_serde(jsonc))?; + let config: TsConfigJson = serde_json::from_value(jsonc_to_serde(jsonc))?; if let Some(compiler_options) = config.compiler_options { parse_compiler_options(&compiler_options, Some(path.to_owned()), false) |