From 32f3739cfaf8b45a941c7d900affdac9ad2cb15d Mon Sep 17 00:00:00 2001 From: Peefy Date: Fri, 23 Aug 2024 18:01:47 +0800 Subject: [PATCH] refactor: cargo clippy parser, resolver and tools crates (#1596) * refactor: cargo clippy parser, resolver and tools crates Signed-off-by: peefy * fix: unit tests Signed-off-by: peefy --------- Signed-off-by: peefy --- kclvm/Cargo.lock | 1 + kclvm/driver/src/test_data/kpm_update/kcl.mod | 2 +- .../test_vendor/.kpm/config/kpm.json | 2 +- kclvm/parser/Cargo.toml | 1 + kclvm/parser/src/lexer/tests.rs | 4 +- kclvm/parser/src/lib.rs | 12 +- kclvm/parser/src/session/mod.rs | 15 +-- kclvm/runner/src/lib.rs | 2 +- kclvm/sema/src/advanced_resolver/node.rs | 108 ++---------------- kclvm/tools/benches/benchmark.rs | 4 +- kclvm/tools/src/LSP/src/completion.rs | 3 +- kclvm/tools/src/LSP/src/inlay_hints.rs | 4 +- kclvm/tools/src/LSP/src/signature_help.rs | 10 +- kclvm/tools/src/LSP/src/state.rs | 4 +- .../import/external/external_0/kcl.mod | 1 - .../test_data/goto_import_def_test/kcl.mod | 1 - kclvm/tools/src/LSP/src/tests.rs | 22 +--- kclvm/tools/src/LSP/src/to_lsp.rs | 3 +- kclvm/tools/src/LSP/src/util.rs | 18 +-- kclvm/tools/src/testing/suite.rs | 3 +- kclvm/tools/src/util/loader.rs | 2 +- kclvm/tools/src/vet/expr_builder.rs | 43 +------ kclvm/tools/src/vet/tests.rs | 2 +- kclvm/tools/src/vet/validator.rs | 4 +- 24 files changed, 67 insertions(+), 204 deletions(-) diff --git a/kclvm/Cargo.lock b/kclvm/Cargo.lock index 90287017e..7cf36c42d 100644 --- a/kclvm/Cargo.lock +++ b/kclvm/Cargo.lock @@ -1907,6 +1907,7 @@ dependencies = [ "kclvm-span", "kclvm-utils", "num-bigint", + "parking_lot 0.12.3", "petgraph", "regex", "rustc_lexer", diff --git a/kclvm/driver/src/test_data/kpm_update/kcl.mod b/kclvm/driver/src/test_data/kpm_update/kcl.mod index a851352ac..7543c05d5 100644 --- a/kclvm/driver/src/test_data/kpm_update/kcl.mod +++ b/kclvm/driver/src/test_data/kpm_update/kcl.mod @@ -4,5 +4,5 @@ edition = "0.0.1" version = "0.0.1" [dependencies] -helloworld = { oci = "oci://ghcr.io/kcl-lang/helloworld", tag = "0.1.0" } flask = { git = "https://github.com/kcl-lang/flask-demo-kcl-manifests", commit = "ade147b" } +helloworld = { oci = "oci://ghcr.io/kcl-lang/helloworld", tag = "0.1.0" } diff --git a/kclvm/driver/src/test_data/test_vendor/.kpm/config/kpm.json b/kclvm/driver/src/test_data/test_vendor/.kpm/config/kpm.json index 7c459d9c7..c2aa99813 100644 --- a/kclvm/driver/src/test_data/test_vendor/.kpm/config/kpm.json +++ b/kclvm/driver/src/test_data/test_vendor/.kpm/config/kpm.json @@ -1 +1 @@ -{"DefaultOciRegistry":"ghcr.io","DefaultOciRepo":"kcl-lang","DefaultOciPlainHttp":false} \ No newline at end of file +{"DefaultOciRegistry":"ghcr.io","DefaultOciRepo":"kcl-lang"} \ No newline at end of file diff --git a/kclvm/parser/Cargo.toml b/kclvm/parser/Cargo.toml index f3727ca6f..2694d148c 100644 --- a/kclvm/parser/Cargo.toml +++ b/kclvm/parser/Cargo.toml @@ -23,6 +23,7 @@ num-bigint = "0.4" regex = "1.7.0" anyhow = "1.0" indexmap = "1.0" +parking_lot = "0.12.3" kclvm-lexer = {path = "../lexer"} kclvm-ast = {path = "../ast"} diff --git a/kclvm/parser/src/lexer/tests.rs b/kclvm/parser/src/lexer/tests.rs index 8d6ec4b75..bda1cc021 100644 --- a/kclvm/parser/src/lexer/tests.rs +++ b/kclvm/parser/src/lexer/tests.rs @@ -7,7 +7,7 @@ use compiler_base_span::{span::new_byte_pos, FilePathMapping, SourceMap}; use expect_test::{expect, Expect}; use kclvm_error::Handler; use kclvm_span::create_session_globals_then; -use std::cell::RefCell; +use parking_lot::RwLock; use std::path::PathBuf; use std::sync::Arc; @@ -16,7 +16,7 @@ impl ParseSession { pub(crate) fn with_source_map(sm: Arc) -> Self { Self( Arc::new(Session::new(sm, Arc::new(DiagnosticHandler::default()))), - RefCell::new(Handler::default()), + RwLock::new(Handler::default()), ) } } diff --git a/kclvm/parser/src/lib.rs b/kclvm/parser/src/lib.rs index 4db63194a..fa14817a2 100644 --- a/kclvm/parser/src/lib.rs +++ b/kclvm/parser/src/lib.rs @@ -402,7 +402,7 @@ impl Loader { .map(|path| format!("- {}\n", path.to_string_lossy())) .collect::(); - self.sess.1.borrow_mut().add_error( + self.sess.1.write().add_error( ErrorKind::RecursiveLoad, &[Message { range: (Position::dummy_pos(), Position::dummy_pos()), @@ -423,7 +423,7 @@ impl Loader { Ok(LoadProgramResult { program, - errors: self.sess.1.borrow().diagnostics.clone(), + errors: self.sess.1.read().diagnostics.clone(), paths, }) } @@ -452,7 +452,7 @@ impl Loader { // 3. Internal and external packages cannot be duplicated if is_external.is_some() && is_internal.is_some() { - self.sess.1.borrow_mut().add_error( + self.sess.1.write().add_error( ErrorKind::CannotFindModule, &[Message { range: Into::::into(pos), @@ -472,7 +472,7 @@ impl Loader { match is_internal.or(is_external) { Some(pkg_info) => Ok(Some(pkg_info)), None => { - self.sess.1.borrow_mut().add_error( + self.sess.1.write().add_error( ErrorKind::CannotFindModule, &[Message { range: Into::::into(pos), @@ -494,7 +494,7 @@ impl Loader { ), ); } - self.sess.1.borrow_mut().add_suggestions(suggestions); + self.sess.1.write().add_suggestions(suggestions); Ok(None) } } @@ -574,7 +574,7 @@ impl Loader { // plugin pkgs if self.is_plugin_pkg(pkgpath.as_str()) { if !self.opts.load_plugins { - self.sess.1.borrow_mut().add_error( + self.sess.1.write().add_error( ErrorKind::CannotFindModule, &[Message { range: Into::::into(pos), diff --git a/kclvm/parser/src/session/mod.rs b/kclvm/parser/src/session/mod.rs index 86d718a4f..56c8ae50d 100644 --- a/kclvm/parser/src/session/mod.rs +++ b/kclvm/parser/src/session/mod.rs @@ -5,20 +5,21 @@ use indexmap::IndexSet; use kclvm_ast::token::Token; use kclvm_error::{Diagnostic, Handler, ParseError, ParseErrorMessage}; use kclvm_span::{BytePos, Loc, Span}; -use std::{cell::RefCell, sync::Arc}; +use parking_lot::RwLock; +use std::sync::Arc; pub type ParseSessionRef = Arc; /// ParseSession represents the data associated with a parse session such as the /// source map and the error handler. -#[derive(Default, Clone)] -pub struct ParseSession(pub Arc, pub RefCell); +#[derive(Default)] +pub struct ParseSession(pub Arc, pub RwLock); impl ParseSession { /// New a parse session with the global session. #[inline] pub fn with_session(sess: Arc) -> Self { - Self(sess, RefCell::new(Handler::default())) + Self(sess, RwLock::new(Handler::default())) } /// Lookup char pos from span. @@ -96,7 +97,7 @@ impl ParseSession { fn add_parse_err(&self, err: ParseError) { let add_error = || -> Result<()> { self.0.add_err(err.clone().into_diag(&self.0)?)?; - self.1.borrow_mut().add_diagnostic(err.into_diag(&self.0)?); + self.1.write().add_diagnostic(err.into_diag(&self.0)?); Ok(()) }; if let Err(err) = add_error() { @@ -110,13 +111,13 @@ impl ParseSession { /// Append diagnostics into the parse session. pub fn append_diagnostic(&self, diagnostics: IndexSet) -> &Self { for diagnostic in diagnostics { - self.1.borrow_mut().add_diagnostic(diagnostic); + self.1.write().add_diagnostic(diagnostic); } self } /// Classify diagnostics into errors and warnings. pub fn classification(&self) -> (IndexSet, IndexSet) { - self.1.borrow().classification() + self.1.read().classification() } } diff --git a/kclvm/runner/src/lib.rs b/kclvm/runner/src/lib.rs index 9aeaa4555..dde68dcc3 100644 --- a/kclvm/runner/src/lib.rs +++ b/kclvm/runner/src/lib.rs @@ -395,7 +395,7 @@ fn emit_compile_diag_to_string( scope: &ProgramScope, include_warnings: bool, ) -> Result<()> { - let mut res_str = sess.1.borrow_mut().emit_to_string()?; + let mut res_str = sess.1.write().emit_to_string()?; let sema_err = scope.emit_diagnostics_to_string(sess.0.clone(), include_warnings); if let Err(err) = &sema_err { #[cfg(not(target_os = "windows"))] diff --git a/kclvm/sema/src/advanced_resolver/node.rs b/kclvm/sema/src/advanced_resolver/node.rs index 1ff49ebb9..73fffdba0 100644 --- a/kclvm/sema/src/advanced_resolver/node.rs +++ b/kclvm/sema/src/advanced_resolver/node.rs @@ -15,7 +15,7 @@ use crate::{ SymbolHintKind, SymbolRef, SymbolSemanticInfo, UnresolvedSymbol, ValueSymbol, }, }, - ty::{self, Type, TypeKind, SCHEMA_MEMBER_FUNCTIONS}, + ty::{Parameter, Type, TypeKind, SCHEMA_MEMBER_FUNCTIONS}, }; use super::AdvancedResolver; @@ -686,11 +686,11 @@ impl<'ctx> MutSelfTypedResultWalker<'ctx> for AdvancedResolver<'ctx> { .get_scopes_mut() .set_owner_to_scope(*cur_scope, owner); } - self.do_arguments_symbol_resolve_with_hint_schema( + self.do_arguments_symbol_resolve_with_hint( &call_expr.args, &call_expr.keywords, + &schema_ty.func.params, true, - schema_ty, )?; self.leave_scope(); @@ -711,11 +711,11 @@ impl<'ctx> MutSelfTypedResultWalker<'ctx> for AdvancedResolver<'ctx> { .set_owner_to_scope(*cur_scope, owner); } - self.do_arguments_symbol_resolve_with_hint_func( + self.do_arguments_symbol_resolve_with_hint( &call_expr.args, &call_expr.keywords, + &func_ty.params, true, - &func_ty, )?; self.leave_scope(); } @@ -1786,107 +1786,17 @@ impl<'ctx> AdvancedResolver<'ctx> { Ok(()) } - pub fn do_arguments_symbol_resolve_with_hint_func( + pub fn do_arguments_symbol_resolve_with_hint( &mut self, args: &'ctx [ast::NodeRef], kwargs: &'ctx [ast::NodeRef], + params: &[Parameter], with_hint: bool, - func_ty: &ty::FunctionType, ) -> anyhow::Result<()> { - if func_ty.params.is_empty() { + if params.is_empty() { self.do_arguments_symbol_resolve(args, kwargs)?; } else { - for (arg, param) in args.iter().zip(func_ty.params.iter()) { - self.expr(arg)?; - - if with_hint { - let symbol_data = self.gs.get_symbols_mut(); - let id = match &arg.node { - ast::Expr::Identifier(id) => id.names.last().unwrap().id.clone(), - _ => arg.id.clone(), - }; - if let Some(arg_ref) = symbol_data - .symbols_info - .node_symbol_map - .get(&self.ctx.get_node_key(&id)) - { - match arg_ref.get_kind() { - crate::core::symbol::SymbolKind::Expression => { - if let Some(expr) = symbol_data.exprs.get_mut(arg_ref.get_id()) { - expr.hint = Some(SymbolHint { - pos: arg.get_pos(), - kind: SymbolHintKind::VarHint(param.name.clone()), - }); - } - } - crate::core::symbol::SymbolKind::Unresolved => { - let mut has_hint = false; - if let Some(unresolved) = - symbol_data.unresolved.get(arg_ref.get_id()) - { - if let Some(def) = unresolved.def { - if let Some(def) = symbol_data.get_symbol(def) { - if def.get_name() != param.name { - has_hint = true; - } - } - } - } - if has_hint { - if let Some(unresolved) = - symbol_data.unresolved.get_mut(arg_ref.get_id()) - { - unresolved.hint = Some(SymbolHint { - kind: SymbolHintKind::VarHint(param.name.clone()), - pos: arg.get_pos(), - }); - } - } - } - _ => {} - } - } - } - } - - for kw in kwargs.iter() { - if let Some(value) = &kw.node.value { - self.expr(value)?; - } - let (start_pos, end_pos): Range = kw.node.arg.get_span_pos(); - let value = self.gs.get_symbols_mut().alloc_value_symbol( - ValueSymbol::new(kw.node.arg.node.get_name(), start_pos, end_pos, None, false), - self.ctx.get_node_key(&kw.id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - - if let Some(value) = self.gs.get_symbols_mut().values.get_mut(value.get_id()) { - value.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&kw.id)) - .map(|ty| ty.clone()), - doc: None, - }; - } - } - } - Ok(()) - } - - pub fn do_arguments_symbol_resolve_with_hint_schema( - &mut self, - args: &'ctx [ast::NodeRef], - kwargs: &'ctx [ast::NodeRef], - with_hint: bool, - schema_ty: &ty::SchemaType, - ) -> anyhow::Result<()> { - if schema_ty.func.params.is_empty() { - self.do_arguments_symbol_resolve(args, kwargs)?; - } else { - for (arg, param) in args.iter().zip(schema_ty.func.params.iter()) { + for (arg, param) in args.iter().zip(params.iter()) { self.expr(arg)?; if with_hint { diff --git a/kclvm/tools/benches/benchmark.rs b/kclvm/tools/benches/benchmark.rs index 0a8899c6e..e9288ea6e 100644 --- a/kclvm/tools/benches/benchmark.rs +++ b/kclvm/tools/benches/benchmark.rs @@ -65,7 +65,7 @@ impl fmt::Display for StopWatchSpan { /// Utility for writing benchmark tests. /// /// If you need to benchmark the entire test, you can directly add the macro `#[bench_test]` like this: -/// ``` +/// ```no_check /// #[test] /// #[bench_test] /// fn benchmark_foo() { @@ -76,7 +76,7 @@ impl fmt::Display for StopWatchSpan { /// If you need to skip some preparation stages and only test some parts of test, you can use the `bench()` method. /// A benchmark test looks like this: /// -/// ``` +/// ```no_check /// #[test] /// fn benchmark_foo() { /// let data = bench_fixture::some_fixture(); diff --git a/kclvm/tools/src/LSP/src/completion.rs b/kclvm/tools/src/LSP/src/completion.rs index 2333412ad..dcd77d780 100644 --- a/kclvm/tools/src/LSP/src/completion.rs +++ b/kclvm/tools/src/LSP/src/completion.rs @@ -476,7 +476,7 @@ fn completion_import_stmt( if let Some(node) = program.pos_to_stmt(line_start_pos) { if let Stmt::Import(_) = node.node { completions.extend(completion_import_builtin_pkg()); - completions.extend(completion_import_internal_pkg(&program, &line_start_pos)); + completions.extend(completion_import_internal_pkg(program, line_start_pos)); completions.extend(completion_import_external_pkg(metadata)); } } @@ -558,7 +558,6 @@ fn completion_import_external_pkg(metadata: Option) -> IndexSet metadata .packages .keys() - .into_iter() .map(|name| KCLCompletionItem { label: name.to_string(), detail: None, diff --git a/kclvm/tools/src/LSP/src/inlay_hints.rs b/kclvm/tools/src/LSP/src/inlay_hints.rs index ddf803098..6f7dab790 100644 --- a/kclvm/tools/src/LSP/src/inlay_hints.rs +++ b/kclvm/tools/src/LSP/src/inlay_hints.rs @@ -55,14 +55,14 @@ pub fn inlay_hints(file: &str, gs: &GlobalState) -> Option> { #[inline] fn generate_inlay_hint(hint: &SymbolHint) -> KCLInlayHint { - let (part, position) = get_hint_label(&hint); + let (part, position) = get_hint_label(hint); KCLInlayHint { position, part } } #[inline] fn into_lsp_inlay_hint(hint: &KCLInlayHint) -> InlayHint { InlayHint { - position: hint.position.clone(), + position: hint.position, label: lsp_types::InlayHintLabel::LabelParts(vec![hint.part.clone()]), kind: None, text_edits: None, diff --git a/kclvm/tools/src/LSP/src/signature_help.rs b/kclvm/tools/src/LSP/src/signature_help.rs index dc0f8d5f3..b356e9942 100644 --- a/kclvm/tools/src/LSP/src/signature_help.rs +++ b/kclvm/tools/src/LSP/src/signature_help.rs @@ -14,9 +14,7 @@ pub fn signature_help( gs: &GlobalState, trigger_character: Option, ) -> Option { - if trigger_character.is_none() { - return None; - } + trigger_character.as_ref()?; match trigger_character.unwrap().as_str() { // func "(" => { @@ -32,7 +30,7 @@ pub fn signature_help( .get_sema_info() .doc .clone() - .and_then(|s| Some(lsp_types::Documentation::String(s))); + .map(lsp_types::Documentation::String); return Some(SignatureHelp { signatures: vec![SignatureInformation { @@ -68,7 +66,7 @@ pub fn signature_help( .get_sema_info() .doc .clone() - .and_then(|s| Some(lsp_types::Documentation::String(s))); + .map(lsp_types::Documentation::String); // highlight parameter's index // if None, it will highlight first param(maybe default) @@ -90,7 +88,7 @@ pub fn signature_help( .collect(); let mut index: usize = 0; for (i, symbol) in actually_symbol.iter().enumerate() { - let s = gs.get_symbols().get_symbol(symbol.clone()).unwrap(); + let s = gs.get_symbols().get_symbol(*symbol).unwrap(); let start = s.get_range().0; if pos.less_equal(&start) { index = i; diff --git a/kclvm/tools/src/LSP/src/state.rs b/kclvm/tools/src/LSP/src/state.rs index d8bb2e334..1494c5d81 100644 --- a/kclvm/tools/src/LSP/src/state.rs +++ b/kclvm/tools/src/LSP/src/state.rs @@ -247,9 +247,7 @@ impl LanguageServerState { { let mut db = snapshot.db.write(); - if !db.contains_key(&file.file_id) { - db.insert(file.file_id, None); - } + db.entry(file.file_id).or_insert(None); } let (diags, compile_res) = compile_with_params(Params { file: filename.clone(), diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/import/external/external_0/kcl.mod b/kclvm/tools/src/LSP/src/test_data/completion_test/import/external/external_0/kcl.mod index 8ea06569b..4ae72f07f 100644 --- a/kclvm/tools/src/LSP/src/test_data/completion_test/import/external/external_0/kcl.mod +++ b/kclvm/tools/src/LSP/src/test_data/completion_test/import/external/external_0/kcl.mod @@ -2,4 +2,3 @@ [dependencies] k8s = { oci = "oci://ghcr.io/kcl-lang/k8s", tag = "1.28" } - diff --git a/kclvm/tools/src/LSP/src/test_data/goto_import_def_test/kcl.mod b/kclvm/tools/src/LSP/src/test_data/goto_import_def_test/kcl.mod index 05c442f22..7afba4cdb 100644 --- a/kclvm/tools/src/LSP/src/test_data/goto_import_def_test/kcl.mod +++ b/kclvm/tools/src/LSP/src/test_data/goto_import_def_test/kcl.mod @@ -5,4 +5,3 @@ version = "0.0.4" [dependencies] konfig = { git = "https://github.com/awesome-kusion/konfig.git", tag = "v0.0.1" } - diff --git a/kclvm/tools/src/LSP/src/tests.rs b/kclvm/tools/src/LSP/src/tests.rs index bb7533878..67c020fd6 100644 --- a/kclvm/tools/src/LSP/src/tests.rs +++ b/kclvm/tools/src/LSP/src/tests.rs @@ -2,7 +2,6 @@ use crossbeam_channel::after; use crossbeam_channel::select; use indexmap::IndexSet; use kclvm_ast::MAIN_PKG; -use kclvm_config::workfile::WorkSpace; use kclvm_driver::toolchain; use kclvm_driver::toolchain::Metadata; use kclvm_driver::WorkSpaceKind; @@ -2277,7 +2276,7 @@ fn kcl_workspace_init_kclwork_test() { work.push("work"); let (workspaces, failed) = - kclvm_driver::lookup_compile_workspaces(&*tool.read(), &work.to_str().unwrap(), true); + kclvm_driver::lookup_compile_workspaces(&*tool.read(), work.to_str().unwrap(), true); let mut expected = HashSet::new(); @@ -2311,10 +2310,7 @@ fn kcl_workspace_init_kclwork_test() { .join("c.k"), )); - assert_eq!( - expected, - workspaces.keys().into_iter().map(|w| w.clone()).collect() - ); + assert_eq!(expected, workspaces.keys().cloned().collect()); assert!(failed.is_some()); assert!(failed.unwrap().is_empty()); @@ -2335,7 +2331,7 @@ fn kcl_workspace_init_kclmod_test() { work.push("mod"); let (workspaces, failed) = - kclvm_driver::lookup_compile_workspaces(&*tool.read(), &work.to_str().unwrap(), true); + kclvm_driver::lookup_compile_workspaces(&*tool.read(), work.to_str().unwrap(), true); let mut expected = HashSet::new(); @@ -2349,10 +2345,7 @@ fn kcl_workspace_init_kclmod_test() { .join("kcl.mod"), )); - assert_eq!( - expected, - workspaces.keys().into_iter().map(|w| w.clone()).collect() - ); + assert_eq!(expected, workspaces.keys().cloned().collect()); assert!(failed.is_none()); } @@ -2372,7 +2365,7 @@ fn kcl_workspace_init_folder_test() { work.push("folder"); let (workspaces, failed) = - kclvm_driver::lookup_compile_workspaces(&*tool.read(), &work.to_str().unwrap(), true); + kclvm_driver::lookup_compile_workspaces(&*tool.read(), work.to_str().unwrap(), true); let mut expected = HashSet::new(); @@ -2385,10 +2378,7 @@ fn kcl_workspace_init_folder_test() { .join("folder"), )); - assert_eq!( - expected, - workspaces.keys().into_iter().map(|w| w.clone()).collect() - ); + assert_eq!(expected, workspaces.keys().cloned().collect()); assert!(failed.is_none()); } diff --git a/kclvm/tools/src/LSP/src/to_lsp.rs b/kclvm/tools/src/LSP/src/to_lsp.rs index 3b1150015..819b12ee3 100644 --- a/kclvm/tools/src/LSP/src/to_lsp.rs +++ b/kclvm/tools/src/LSP/src/to_lsp.rs @@ -69,7 +69,7 @@ fn kcl_msg_to_lsp_diags( Some( related_msg .iter() - .map(|m| match Url::from_file_path(m.range.0.filename.clone()) { + .filter_map(|m| match Url::from_file_path(m.range.0.filename.clone()) { Ok(uri) => Some(DiagnosticRelatedInformation { location: Location { uri, @@ -82,7 +82,6 @@ fn kcl_msg_to_lsp_diags( }), Err(_) => None, }) - .flatten() .collect(), ) }; diff --git a/kclvm/tools/src/LSP/src/util.rs b/kclvm/tools/src/LSP/src/util.rs index 27eea25c1..bd576c38d 100644 --- a/kclvm/tools/src/LSP/src/util.rs +++ b/kclvm/tools/src/LSP/src/util.rs @@ -91,11 +91,11 @@ pub(crate) fn lookup_compile_unit_with_cache( match &mut lookup_compile_unit_path(file) { Ok(CompileUnitPath::SettingFile(dir)) => { dir.push(DEFAULT_SETTING_FILE); - get_last_modified_time(&dir).ok() + get_last_modified_time(dir).ok() } Ok(CompileUnitPath::ModFile(dir)) => { dir.push(KCL_MOD_FILE); - get_last_modified_time(&dir).ok() + get_last_modified_time(dir).ok() } _ => None, } @@ -136,9 +136,9 @@ pub(crate) fn lookup_compile_unit_with_cache( pub(crate) fn get_last_modified_time(path: &PathBuf) -> std::io::Result { if path.is_file() { - return fs::metadata(path) + fs::metadata(path) .map(|meta| meta.modified()) - .and_then(|t| t); + .and_then(|t| t) } else if path.is_dir() { let mut last_modified_time = std::time::SystemTime::UNIX_EPOCH; for entry in fs::read_dir(path)? { @@ -173,14 +173,14 @@ pub(crate) fn compile_with_params( pub(crate) fn compile( params: Params, - files: &mut Vec, + files: &mut [String], opts: Option, ) -> (IndexSet, anyhow::Result<(Program, GlobalState)>) { // Ignore the kcl plugin sematic check. let mut opts = opts.unwrap_or_default(); opts.load_plugins = true; // Get input files - let files = match get_normalized_k_files_from_paths(&files, &opts) { + let files = match get_normalized_k_files_from_paths(files, &opts) { Ok(file_list) => file_list, Err(e) => { return ( @@ -212,7 +212,7 @@ pub(crate) fn compile( Ok(r) => r.program, Err(e) => return (diags, Err(anyhow::anyhow!("Parse failed: {:?}", e))), }; - diags.extend(sess.1.borrow().diagnostics.clone()); + diags.extend(sess.1.read().diagnostics.clone()); // Resolver if let Some(cached_scope) = params.scope_cache.as_ref() { @@ -237,7 +237,7 @@ pub(crate) fn compile( let mut default = GlobalState::default(); let mut gs_ref; - let mut gs = match ¶ms.gs_cache { + let gs = match ¶ms.gs_cache { Some(cache) => match cache.try_lock() { Ok(locked_state) => { gs_ref = locked_state; @@ -257,7 +257,7 @@ pub(crate) fn compile( }; gs.clear_cache(); - Namer::find_symbols(&program, &mut gs); + Namer::find_symbols(&program, gs); match AdvancedResolver::resolve_program(&program, gs, prog_scope.node_ty_map) { Ok(_) => (diags, Ok((program, gs.clone()))), diff --git a/kclvm/tools/src/testing/suite.rs b/kclvm/tools/src/testing/suite.rs index 4a5b98c2e..6af3667dc 100644 --- a/kclvm/tools/src/testing/suite.rs +++ b/kclvm/tools/src/testing/suite.rs @@ -170,8 +170,7 @@ pub fn load_test_suites>(path: P, opts: &TestOptions) -> Result for DataLoader { }; v.docs - .get(0) + .first() .map_or_else(|| bail!("Failed to Load YAML"), |res| Ok(res.clone())) } } diff --git a/kclvm/tools/src/vet/expr_builder.rs b/kclvm/tools/src/vet/expr_builder.rs index 11853c478..4f1204e8a 100644 --- a/kclvm/tools/src/vet/expr_builder.rs +++ b/kclvm/tools/src/vet/expr_builder.rs @@ -3,7 +3,6 @@ use kclvm_ast::{ ast::{ ConfigEntry, ConfigEntryOperation, ConfigExpr, Expr, ExprContext, Identifier, ListExpr, NameConstant, NameConstantLit, Node, NodeRef, NumberLit, NumberLitValue, SchemaExpr, - StringLit, }, node_ref, }; @@ -116,12 +115,7 @@ impl ExprGenerator for ExprBuilder { } } serde_yaml::Value::String(j_string) => { - let str_lit = match StringLit::try_from(j_string.to_string()) { - Ok(s) => s, - Err(_) => { - bail!("{FAIL_LOAD_VALIDATED_ERR_MSG}") - } - }; + let str_lit = From::from(j_string.to_string()); Ok(node_ref!(Expr::StringLit(str_lit))) } serde_yaml::Value::Sequence(j_arr) => { @@ -251,12 +245,7 @@ impl ExprGenerator for ExprBuilder { } } located_yaml::YamlElt::String(j_string) => { - let str_lit = match StringLit::try_from(j_string.to_string()) { - Ok(s) => s, - Err(_) => { - bail!("{FAIL_LOAD_VALIDATED_ERR_MSG}") - } - }; + let str_lit = From::from(j_string.to_string()); Ok(node_ref!(Expr::StringLit(str_lit), loc)) } located_yaml::YamlElt::Array(j_arr) => { @@ -409,12 +398,7 @@ impl ExprGenerator> for E } } json_spanned_value::Value::String(j_string) => { - let str_lit = match StringLit::try_from(j_string.to_string()) { - Ok(s) => s, - Err(_) => { - bail!("{FAIL_LOAD_VALIDATED_ERR_MSG}") - } - }; + let str_lit = From::from(j_string.to_string()); Ok(node_ref!(Expr::StringLit(str_lit), loc)) } @@ -439,12 +423,7 @@ impl ExprGenerator> for E for (k, v) in j_map.iter() { let k_span = k.span(); - let k = match StringLit::try_from(k.to_string()) { - Ok(s) => s, - Err(err) => { - bail!("{FAIL_LOAD_VALIDATED_ERR_MSG}, {err}") - } - }; + let k = From::from(k.to_string()); let v = self .generate(v, &None) .with_context(|| FAIL_LOAD_VALIDATED_ERR_MSG)?; @@ -559,12 +538,7 @@ impl ExprGenerator for ExprBuilder { } } serde_json::Value::String(j_string) => { - let str_lit = match StringLit::try_from(j_string.to_string()) { - Ok(s) => s, - Err(_) => { - bail!("{FAIL_LOAD_VALIDATED_ERR_MSG}") - } - }; + let str_lit = From::from(j_string.to_string()); Ok(node_ref!(Expr::StringLit(str_lit))) } @@ -585,12 +559,7 @@ impl ExprGenerator for ExprBuilder { let mut config_entries: Vec> = Vec::new(); for (k, v) in j_map.iter() { - let k = match StringLit::try_from(k.to_string()) { - Ok(s) => s, - Err(err) => { - bail!("{FAIL_LOAD_VALIDATED_ERR_MSG}, {err}") - } - }; + let k = From::from(k.to_string()); let v = self .generate(v, &None) .with_context(|| FAIL_LOAD_VALIDATED_ERR_MSG)?; diff --git a/kclvm/tools/src/vet/tests.rs b/kclvm/tools/src/vet/tests.rs index 8d0f751c8..ca9c714b4 100644 --- a/kclvm/tools/src/vet/tests.rs +++ b/kclvm/tools/src/vet/tests.rs @@ -381,7 +381,7 @@ mod test_validater { match validate(opt) { Ok(res) => assert!(res), - Err(err) => assert!(false, "{:?}", err), + Err(err) => unreachable!("{:?}", err), } } } diff --git a/kclvm/tools/src/vet/validator.rs b/kclvm/tools/src/vet/validator.rs index de1dd3050..906b67501 100644 --- a/kclvm/tools/src/vet/validator.rs +++ b/kclvm/tools/src/vet/validator.rs @@ -179,7 +179,7 @@ pub fn validate(val_opt: ValidateOption) -> Result { let sess = ParseSessionRef::default(); let mut compile_res = kclvm_parser::load_program( sess, - vec![k_path] + [k_path] .iter() .map(|s| s.as_str()) .collect::>() @@ -196,7 +196,7 @@ pub fn validate(val_opt: ValidateOption) -> Result { let schemas = filter_schema_stmt_from_prog(&compile_res.program); let schema_name = match val_opt.schema_name { Some(name) => Some(name), - None => schemas.get(0).map(|schema| schema.name.node.clone()), + None => schemas.first().map(|schema| schema.name.node.clone()), }; let expr_builder =