From 8be099f0ad4d762e75335293b0ec47decf63aded Mon Sep 17 00:00:00 2001 From: Jamie Quigley Date: Tue, 22 Mar 2022 15:32:37 +0000 Subject: [PATCH 1/2] Run rustfmt --- src/error.rs | 5 +- src/eval.rs | 10 ++-- src/lookup.rs | 134 ++++++++++++++++++++++++++------------------------ src/main.rs | 4 +- src/parse.rs | 8 ++- src/tests.rs | 65 +++++++++++++++++------- src/utils.rs | 59 ++++++++++++++-------- 7 files changed, 172 insertions(+), 113 deletions(-) diff --git a/src/error.rs b/src/error.rs index 8886ab1..ad3174e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -2,7 +2,6 @@ use gc::{Finalize, Trace}; pub const ERR_PARSING: EvalError = EvalError::Internal(InternalError::Parsing); - #[derive(Debug, Clone, Trace, Finalize)] pub enum EvalError { Internal(InternalError), @@ -69,7 +68,9 @@ impl std::fmt::Display for ValueError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { ValueError::DivisionByZero => write!(f, "division by zero"), - ValueError::AttrAlreadyDefined(name) => write!(f, "attribute `{}` defined more than once", name), + ValueError::AttrAlreadyDefined(name) => { + write!(f, "attribute `{}` defined more than once", name) + } ValueError::TypeError(msg) => write!(f, "{}", msg), } } diff --git a/src/eval.rs b/src/eval.rs index 0871c22..20bea50 100644 --- a/src/eval.rs +++ b/src/eval.rs @@ -119,7 +119,7 @@ impl Expr { // from an .eval(), which is probably infinite recursion. return Err(EvalError::Internal(InternalError::Unimplemented( "infinite recursion".to_string(), - ))) + ))); } }; if let Some(ref value) = *value_borrow { @@ -285,9 +285,7 @@ impl Expr { ExprSource::Implication { left, right } => vec![left, right], ExprSource::UnaryInvert { value } => vec![value], ExprSource::UnaryNegate { value } => vec![value], - ExprSource::AttrSet { - definitions, - } => { + ExprSource::AttrSet { definitions } => { let mut out = vec![]; out.extend(definitions); // This looks similar to code at the end of the function, but @@ -402,7 +400,9 @@ pub fn merge_set_literal(name: String, a: Gc, b: Gc) -> Result = vec![ @@ -52,7 +56,11 @@ impl LSPDetails { } } - fn builtin_with_doc(deprecated: bool, params: Option, documentation: String) -> LSPDetails { + fn builtin_with_doc( + deprecated: bool, + params: Option, + documentation: String, + ) -> LSPDetails { LSPDetails { datatype: Datatype::Lambda, var: None, @@ -87,7 +95,6 @@ impl App { root: &SyntaxNode, offset: usize, ) -> Option<(Ident, HashMap, String)> { - let mut file = Rc::new(file); let info = utils::ident_at(&root, offset)?; let ident = info.ident; @@ -177,7 +184,9 @@ impl App { } fn fallback_builtins(&self, list: Vec) -> HashMap { - list.into_iter().map(|x| (x, LSPDetails::builtin_fallback())).collect::>() + list.into_iter() + .map(|x| (x, LSPDetails::builtin_fallback())) + .collect::>() } fn load_builtins(&self) -> HashMap { @@ -191,32 +200,52 @@ impl App { Ok(out) => { match str::from_utf8(&out.stdout) { Ok(v) => { - let re = regex::Regex::new(r"^nix \(Nix\) (?P\d)\.(?P\d).*").unwrap(); + let re = regex::Regex::new(r"^nix \(Nix\) (?P\d)\.(?P\d).*") + .unwrap(); let m = re.captures(v).unwrap(); - let major = m.name("major").map_or(1, |m| m.as_str().parse::().unwrap()); - let minor = m.name("minor").map_or(1, |m| m.as_str().parse::().unwrap()); + let major = m + .name("major") + .map_or(1, |m| m.as_str().parse::().unwrap()); + let minor = m + .name("minor") + .map_or(1, |m| m.as_str().parse::().unwrap()); if major == 2 && minor >= 4 || major > 2 { - let builtins_raw = process::Command::new("nix").args(&["__dump-builtins"]).output().unwrap(); - let v: serde_json::Value = serde_json::from_str(str::from_utf8(&builtins_raw.stdout).unwrap()).unwrap(); - - v.as_object().unwrap() - .iter().map(|(x, v)| { + let builtins_raw = process::Command::new("nix") + .args(&["__dump-builtins"]) + .output() + .unwrap(); + let v: serde_json::Value = + serde_json::from_str(str::from_utf8(&builtins_raw.stdout).unwrap()) + .unwrap(); + + v.as_object() + .unwrap() + .iter() + .map(|(x, v)| { let doc = String::from(v["doc"].as_str().unwrap()); - (String::from(x), LSPDetails::builtin_with_doc( - doc.starts_with("**DEPRECATED.**"), - // FIXME make sure that `lib.flip` is taken into account here - v["args"].as_array().map(|x| x.iter().map(|y| y.as_str().unwrap()).collect::>().join(" -> ")), - doc - )) + ( + String::from(x), + LSPDetails::builtin_with_doc( + doc.starts_with("**DEPRECATED.**"), + // FIXME make sure that `lib.flip` is taken into account here + v["args"].as_array().map(|x| { + x.iter() + .map(|y| y.as_str().unwrap()) + .collect::>() + .join(" -> ") + }), + doc, + ), + ) }) .collect::>() } else { self.fallback_builtins(BUILTINS.to_vec()) } - }, + } Err(_) => self.fallback_builtins(BUILTINS.to_vec()), } - }, + } Err(_) => self.fallback_builtins(BUILTINS.to_vec()), } } @@ -235,11 +264,8 @@ mod tests { let suggestions = (App { files: HashMap::new(), conn: c.0, - }).scope_for_ident( - Url::parse("file:///default.nix").unwrap(), - &root, - 15 - ); + }) + .scope_for_ident(Url::parse("file:///default.nix").unwrap(), &root, 15); assert!(suggestions.is_some()); let val = suggestions.unwrap(); @@ -256,21 +282,15 @@ mod tests { files: HashMap::new(), conn: Connection::memory().0, }; - let suggestions = app.scope_for_ident( - Url::parse("file:///default.nix").unwrap(), - &root, - 37 - ); + let suggestions = + app.scope_for_ident(Url::parse("file:///default.nix").unwrap(), &root, 37); assert!(suggestions.is_some()); let val = suggestions.unwrap(); assert!(val.1.contains_key("ab")); - let suggestions_attr_set = app.scope_for_ident( - Url::parse("file:///default.nix").unwrap(), - &root, - 41 - ); + let suggestions_attr_set = + app.scope_for_ident(Url::parse("file:///default.nix").unwrap(), &root, 41); assert!(suggestions_attr_set.is_some()); let val = suggestions_attr_set.unwrap(); assert!(val.1.contains_key("abc")); @@ -284,11 +304,8 @@ mod tests { conn: Connection::memory().0, }; - let suggestions = app.scope_for_ident( - Url::parse("file:///default.nix").unwrap(), - &root, - 28 - ); + let suggestions = + app.scope_for_ident(Url::parse("file:///default.nix").unwrap(), &root, 28); assert!(suggestions.is_some()); let val = suggestions.unwrap(); @@ -307,11 +324,7 @@ mod tests { conn: Connection::memory().0, }; - let suggestions = app.scope_for_ident( - Url::parse("file:///default.nix").unwrap(), - &root, - 9 - ); + let suggestions = app.scope_for_ident(Url::parse("file:///default.nix").unwrap(), &root, 9); assert!(suggestions.is_some()); let val = suggestions.unwrap(); @@ -330,11 +343,7 @@ mod tests { conn: Connection::memory().0, }; - let suggestions = app.scope_for_ident( - Url::parse("file:///default.nix").unwrap(), - &root, - 9 - ); + let suggestions = app.scope_for_ident(Url::parse("file:///default.nix").unwrap(), &root, 9); let val = suggestions.unwrap(); @@ -353,7 +362,7 @@ mod tests { let builtin = LSPDetails::builtin_with_doc( false, Some(String::from("from -> to")), - String::from("foo") + String::from("foo"), ); assert_eq!(Datatype::Lambda, builtin.datatype); assert_eq!("Lambda: from -> to -> Result", builtin.render_detail()); @@ -376,11 +385,7 @@ mod tests { }; let url = Url::parse("file:///code/default.nix").unwrap(); - app.scope_for_ident( - url, - &root, - 32 - ); + app.scope_for_ident(url, &root, 32); let f = app.files.get(&Url::parse("file:///code/foo.nix").unwrap()); assert!(f.is_some()); @@ -399,13 +404,12 @@ mod tests { }; let url = Url::parse("file:///code/default.nix").unwrap(); - app.scope_for_ident( - url, - &root, - 43 - ); + app.scope_for_ident(url, &root, 43); println!("{:?}", app.files.keys()); - assert!(app.files.get(&Url::parse("file:///code/foo.nix").unwrap()).is_some()); + assert!(app + .files + .get(&Url::parse("file:///code/foo.nix").unwrap()) + .is_some()); } } diff --git a/src/main.rs b/src/main.rs index a7bf037..4916f3c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -352,7 +352,7 @@ impl App { let start: usize = range.start().into(); let end: usize = range.end().into(); if start <= offset && offset < end { - return None + return None; } let (_definition_ast, definition_content, _) = self.files.get(&var.file)?; @@ -377,7 +377,7 @@ impl App { let start: usize = range.start().into(); let end: usize = range.end().into(); if start <= offset && offset < end { - return None + return None; } let def_path = def.scope.root_path()?; diff --git a/src/parse.rs b/src/parse.rs index c590fcb..d0a4cf8 100644 --- a/src/parse.rs +++ b/src/parse.rs @@ -211,7 +211,9 @@ impl Expr { let name = name.to_string(); match value_map.entry(name.clone()) { Entry::Occupied(_) => { - return Err(EvalError::Value(ValueError::AttrAlreadyDefined(name))) + return Err(EvalError::Value(ValueError::AttrAlreadyDefined( + name, + ))) } Entry::Vacant(entry) => entry.insert(attr), }; @@ -232,7 +234,9 @@ impl Expr { let name = name.to_string(); match value_map.entry(name.clone()) { Entry::Occupied(_) => { - return Err(EvalError::Value(ValueError::AttrAlreadyDefined(name))) + return Err(EvalError::Value(ValueError::AttrAlreadyDefined( + name, + ))) } Entry::Vacant(entry) => entry.insert(attr), }; diff --git a/src/tests.rs b/src/tests.rs index 983199c..39982b0 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -57,7 +57,10 @@ fn prepare_integration_test(code: &str, filename: &str) -> (Connection, Stoppabl // indefinetely for a message to be able to exit as soon as the test is finished // and the thread is stopped. let h = spawn(move |stopped| { - let mut app = App { files: HashMap::new(), conn: server }; + let mut app = App { + files: HashMap::new(), + conn: server, + }; loop { if let Ok(msg) = app.conn.receiver.recv_timeout(Duration::from_millis(100)) { @@ -79,16 +82,22 @@ fn prepare_integration_test(code: &str, filename: &str) -> (Connection, Stoppabl method: String::from("textDocument/didOpen"), params: json!({ "textDocument": { "uri": filename, "text": code, "version": 1, "languageId": "nix" } - }) + }), }; - client.sender.send(open.into()).expect("Cannot send didOpen!"); + client + .sender + .send(open.into()) + .expect("Cannot send didOpen!"); (client, h) } #[cfg(test)] fn recv_msg(client: &Connection) -> lsp_server::Message { - client.receiver.recv_timeout(Duration::new(5, 0)).expect("No message within 5 secs!") + client + .receiver + .recv_timeout(Duration::new(5, 0)) + .expect("No message within 5 secs!") } #[cfg(test)] @@ -128,18 +137,34 @@ fn test_hover_integration() { "line": 0, "character": 7 } - }) + }), }; - client.sender.send(r.into()).expect("Cannot send hover notification!"); + client + .sender + .send(r.into()) + .expect("Cannot send hover notification!"); expect_diagnostics(&client); let msg = recv_msg(&client); - let hover_json = coerce_response(msg).result.expect("Expected hover response!"); + let hover_json = coerce_response(msg) + .result + .expect("Expected hover response!"); let hover_value = &hover_json.as_object().unwrap()["contents"]["value"]; - assert_eq!("2", *hover_value.to_string().split("\\n").collect::>().get(1).unwrap()); - - handle.stop().join().expect("Failed to gracefully terminate LSP worker thread!"); + assert_eq!( + "2", + *hover_value + .to_string() + .split("\\n") + .collect::>() + .get(1) + .unwrap() + ); + + handle + .stop() + .join() + .expect("Failed to gracefully terminate LSP worker thread!"); } #[test] @@ -159,17 +184,20 @@ fn test_rename() { "character": 24, }, "newName": "c", - }) + }), }; - client.sender.send(r.into()).expect("Cannot send rename request!"); + client + .sender + .send(r.into()) + .expect("Cannot send rename request!"); expect_diagnostics(&client); let msg = recv_msg(&client); - let response = coerce_response(msg).result.expect("Expected rename response!"); - let changes = &response - .as_object() - .unwrap()["changes"]["file:///code/default.nix"] + let response = coerce_response(msg) + .result + .expect("Expected rename response!"); + let changes = &response.as_object().unwrap()["changes"]["file:///code/default.nix"] .as_array() .expect("Changes must be an array!"); @@ -212,7 +240,10 @@ fn test_rename() { assert_eq!(0, third["range"]["start"]["line"]); assert_eq!(0, third["range"]["end"]["line"]); - handle.stop().join().expect("Failed to gracefully terminate LSP worker thread!"); + handle + .stop() + .join() + .expect("Failed to gracefully terminate LSP worker thread!"); } #[test] diff --git a/src/utils.rs b/src/utils.rs index a1651b8..01e4678 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -336,10 +336,7 @@ mod tests { assert_eq!(0, start.start.character); assert_eq!(1, start.end.character); - let actual_pos = range(expr, TextRange::new( - TextSize::from(15), - TextSize::from(20) - )); + let actual_pos = range(expr, TextRange::new(TextSize::from(15), TextSize::from(20))); assert_eq!(1, actual_pos.start.line); assert_eq!(1, actual_pos.end.line); @@ -368,10 +365,13 @@ mod tests { #[test] fn test_lookup_pos_in_expr() { let expr = "let a = 1;\nbuiltins.trace a 23"; - let pos = lookup_pos(expr, Position { - line: 0, - character: 0, - }); + let pos = lookup_pos( + expr, + Position { + line: 0, + character: 0, + }, + ); assert_eq!(0, pos.expect("expected position to be not None!")); } @@ -379,17 +379,29 @@ mod tests { #[test] fn test_lookup_pos_out_of_range() { let expr = "let a = 1;\na"; - let pos_wrong_line = lookup_pos(expr, Position { - line: 5, - character: 23, - }); + let pos_wrong_line = lookup_pos( + expr, + Position { + line: 5, + character: 23, + }, + ); assert!(pos_wrong_line.is_none()); // if the character is greater than the length of a line, the offset of the last // char of the line is returned. - let pos_char_out_of_range = lookup_pos(expr, Position { line: 0, character: 100, }); - assert_eq!(10, pos_char_out_of_range.expect("expected position to be not None!")); + let pos_char_out_of_range = lookup_pos( + expr, + Position { + line: 0, + character: 100, + }, + ); + assert_eq!( + 10, + pos_char_out_of_range.expect("expected position to be not None!") + ); } #[test] @@ -398,21 +410,26 @@ mod tests { let root = rnix::parse(expr).node(); let scope = scope_for( &Rc::new(Url::parse("file:///default.nix").unwrap()), - root.children().next().unwrap() + root.children().next().unwrap(), ); assert!(scope.is_some()); let scope_entries = scope.unwrap(); assert_eq!(5, scope_entries.keys().len()); - assert!(scope_entries.values().into_iter().all(|x| x.datatype == Datatype::Lambda)); - assert!(vec!["n", "a", "b", "c", "d"].into_iter().all(|x| scope_entries.contains_key(x))); + assert!(scope_entries + .values() + .into_iter() + .all(|x| x.datatype == Datatype::Lambda)); + assert!(vec!["n", "a", "b", "c", "d"] + .into_iter() + .all(|x| scope_entries.contains_key(x))); let mut iter = root.children().next().unwrap().children(); iter.next(); let scope_let = scope_for( &Rc::new(Url::parse("file:///default.nix").unwrap()), - iter.next().unwrap() + iter.next().unwrap(), ); assert!(scope_let.is_some()); @@ -427,14 +444,16 @@ mod tests { let root = rnix::parse(expr).node(); let scope = scope_for( &Rc::new(Url::parse("file:///default.nix").unwrap()), - root.children().next().unwrap() + root.children().next().unwrap(), ); assert!(scope.is_some()); let scope_entries = scope.unwrap(); assert_eq!(2, scope_entries.keys().len()); - assert!(vec!["a", "body"].into_iter().all(|x| scope_entries.contains_key(x))); + assert!(vec!["a", "body"] + .into_iter() + .all(|x| scope_entries.contains_key(x))); } #[test] From 9d2bcb06eaaae6bbb15017f991954d7e9597e86f Mon Sep 17 00:00:00 2001 From: Jamie Quigley Date: Tue, 22 Mar 2022 15:46:02 +0000 Subject: [PATCH 2/2] Apply a bunch of clippy lints --- src/eval.rs | 12 +++++++----- src/lookup.rs | 23 +++++++++++------------ src/main.rs | 22 +++++++--------------- src/parse.rs | 8 ++++---- src/tests.rs | 2 +- src/utils.rs | 31 +++++++++++++------------------ 6 files changed, 43 insertions(+), 55 deletions(-) diff --git a/src/eval.rs b/src/eval.rs index 20bea50..aada515 100644 --- a/src/eval.rs +++ b/src/eval.rs @@ -247,10 +247,12 @@ impl Expr { .get(name) // We don't have everything implemented yet, so silently fail, // assuming we're at fault - .ok_or(EvalError::Internal(InternalError::Unimplemented(format!( - "not found in scope: {}", - name - ))))? + .ok_or_else(|| { + EvalError::Internal(InternalError::Unimplemented(format!( + "not found in scope: {}", + name + ))) + })? .eval(), ExprSource::Select { from, index } => { let key = index.as_ref()?.as_ident()?; @@ -338,7 +340,7 @@ impl Expr { pub fn get_definition(&self) -> Option> { use ExprSource::*; match &self.source { - Ident { name } => self.scope.get(&name), + Ident { name } => self.scope.get(name), Select { from, index } => { let idx = index.as_ref().ok()?.as_ident().ok()?; let out = from diff --git a/src/lookup.rs b/src/lookup.rs index aad6bb2..7b55302 100644 --- a/src/lookup.rs +++ b/src/lookup.rs @@ -7,7 +7,7 @@ use lsp_types::Url; use rnix::{types::*, value::Value as ParsedValue, SyntaxNode}; use std::{ collections::{hash_map::Entry, HashMap}, - path::PathBuf, + path::Path, rc::Rc, }; @@ -18,7 +18,6 @@ use lazy_static::lazy_static; use crate::scope::Scope; use gc::Gc; -use regex; use std::{process, str}; lazy_static! { @@ -83,7 +82,7 @@ impl LSPDetails { pub fn render_detail(&self) -> String { match &self.params { None => self.datatype.to_string(), - Some(params) => format!("{}: {} -> Result", self.datatype.to_string(), params), + Some(params) => format!("{}: {} -> Result", self.datatype, params), } } } @@ -96,11 +95,11 @@ impl App { offset: usize, ) -> Option<(Ident, HashMap, String)> { let mut file = Rc::new(file); - let info = utils::ident_at(&root, offset)?; + let info = utils::ident_at(root, offset)?; let ident = info.ident; let mut entries = utils::scope_for(&file, ident.node().clone())? .into_iter() - .map(|(x, var)| (x.to_owned(), LSPDetails::from_scope(var.datatype, var))) + .map(|(x, var)| (x, LSPDetails::from_scope(var.datatype, var))) .collect::>(); for var in info.path { if !entries.contains_key(&var) && var == "builtins" { @@ -112,7 +111,7 @@ impl App { entries = self .scope_from_node(&mut file, node)? .into_iter() - .map(|(x, var)| (x.to_owned(), LSPDetails::from_scope(var.datatype, var))) + .map(|(x, var)| (x, LSPDetails::from_scope(var.datatype, var))) .collect::>(); } } @@ -154,7 +153,7 @@ impl App { // TODO use anchor *file = Rc::new(file.join(&path).ok()?); - let path = utils::uri_path(&file)?; + let path = utils::uri_path(file)?; node = match self.files.entry((**file).clone()) { Entry::Occupied(entry) => { let (ast, _code, _) = entry.get(); @@ -173,13 +172,13 @@ impl App { } if let Some(set) = AttrSet::cast(node) { - utils::populate(&file, &mut scope, &set, Datatype::Attribute); + utils::populate(file, &mut scope, &set, Datatype::Attribute); } Some(scope) } #[cfg(not(test))] - fn read_from_str(p: &PathBuf) -> Option { + fn read_from_str(p: &Path) -> Option { fs::read_to_string(&p).ok() } @@ -271,7 +270,7 @@ mod tests { let val = suggestions.unwrap(); assert_eq!("a", val.2); assert!(val.1.contains_key("ab")); - assert_eq!(Datatype::Variable, val.1.get("ab").unwrap().datatype); + assert_eq!(Datatype::Variable, val.1["ab"].datatype); } #[test] @@ -347,7 +346,7 @@ mod tests { let val = suggestions.unwrap(); - assert!(val.1.get("abort").unwrap().documentation.is_some()); + assert!(val.1["abort"].documentation.is_some()); } #[test] @@ -370,7 +369,7 @@ mod tests { impl App { #[cfg(test)] - pub fn read_from_str(_p: &PathBuf) -> Option { + pub fn read_from_str(_p: &Path) -> Option { Some(String::from("(1 + 1)")) } } diff --git a/src/main.rs b/src/main.rs index 4916f3c..e660506 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,16 +10,11 @@ clippy::decimal_literal_representation, clippy::float_cmp_const, clippy::get_unwrap, - clippy::integer_arithmetic, clippy::integer_division, clippy::pedantic, )] -#![allow( - // filter().map() can sometimes be more readable - clippy::filter_map, - // Most integer arithmetics are within an allocated region, so we know it's safe - clippy::integer_arithmetic, -)] +// filter().map() can sometimes be more readable +#![allow(clippy::manual_filter_map)] mod error; mod eval; @@ -208,7 +203,7 @@ impl App { let changes = if let Some((ast, code, _)) = self.files.get(¶ms.text_document.uri) { let fmt = nixpkgs_fmt::reformat_node(&ast.node()); vec![TextEdit { - range: utils::range(&code, TextRange::up_to(ast.node().text().len())), + range: utils::range(code, TextRange::up_to(ast.node().text().len())), new_text: fmt.text().to_string(), }] } else { @@ -277,7 +272,7 @@ impl App { .files .get(&uri) .map(|f| f.1.clone()) - .unwrap_or("".to_string()); + .unwrap_or_else(|| "".to_string()); for change in params.content_changes.into_iter() { let range = match change.range { Some(x) => x, @@ -324,8 +319,7 @@ impl App { let gc_root = Gc::new(Scope::Root(path)); let parsed_root = parsed.root().inner().ok_or(ERR_PARSING); let evaluated = parsed_root.and_then(|x| Expr::parse(x, gc_root)); - self.files - .insert(uri, (parsed, content.to_owned().to_string(), evaluated)); + self.files.insert(uri, (parsed, content, evaluated)); } } _ => (), @@ -402,7 +396,7 @@ impl App { } } }; - let child_expr = climb_expr(expr, offset).clone(); + let child_expr = climb_expr(expr, offset); let range = utils::range(content, child_expr.range?); let msg = match child_expr.eval() { Ok(value) => value.format_markdown(), @@ -435,9 +429,7 @@ impl App { let det = data.render_detail(); completions.push(CompletionItem { label: var.clone(), - documentation: data - .documentation - .map(|x| lsp_types::Documentation::String(x)), + documentation: data.documentation.map(lsp_types::Documentation::String), deprecated: Some(data.deprecated), text_edit: Some(CompletionTextEdit::Edit(TextEdit { range: utils::range(content, node.node().text_range()), diff --git a/src/parse.rs b/src/parse.rs index d0a4cf8..1c861b5 100644 --- a/src/parse.rs +++ b/src/parse.rs @@ -43,9 +43,9 @@ impl Expr { /// rnix::SyntaxNode isn't recognized, we don't get tooling for its children. pub fn parse(node: SyntaxNode, scope: Gc) -> Result { let range = Some(node.text_range()); - let recurse_box = |node| Expr::parse(node, scope.clone()).map(|x| Box::new(x)); - let recurse_gc = |node| Expr::parse(node, scope.clone()).map(|x| Gc::new(x)); - let source = match ParsedType::try_from(node.clone()).map_err(|_| ERR_PARSING)? { + let recurse_box = |node| Expr::parse(node, scope.clone()).map(Box::new); + let recurse_gc = |node| Expr::parse(node, scope.clone()).map(Gc::new); + let source = match ParsedType::try_from(node).map_err(|_| ERR_PARSING)? { ParsedType::Select(select) => ExprSource::Select { from: recurse_gc(select.set().ok_or(ERR_PARSING)?), index: recurse_box(select.index().ok_or(ERR_PARSING)?), @@ -146,7 +146,7 @@ impl Expr { key: element, value: Ok(tmp_attr_set), }, - range: Some(cursor_range.clone()), + range: Some(cursor_range), scope: new_scope.clone(), }); } diff --git a/src/tests.rs b/src/tests.rs index 39982b0..a8f55a7 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -14,7 +14,7 @@ use stoppable_thread::*; #[allow(dead_code)] fn eval(code: &str) -> NixValue { - let ast = rnix::parse(&code); + let ast = rnix::parse(code); let root = ast.root().inner().unwrap(); let path = std::env::current_dir().unwrap(); let out = Expr::parse(root, Gc::new(Scope::Root(path))).unwrap(); diff --git a/src/utils.rs b/src/utils.rs index 01e4678..283a3bf 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -128,22 +128,17 @@ pub fn ident_at(root: &SyntaxNode, offset: usize) -> Option { if let Some(node) = parent.clone().and_then(Inherit::cast) { if let Some(node) = node.from() { if let Some(tok) = node.inner() { - if let Some(_) = Ident::cast(tok.clone()) { - return Some(CursorInfo::new( - vec![tok.text().to_string()], - ident.clone(), - None, - )); - } else if let Some(mut attr) = Select::cast(tok.clone()) { - let mut result = Vec::new(); - result.push(attr.index()?.to_string().into()); + if Ident::cast(tok.clone()).is_some() { + return Some(CursorInfo::new(vec![tok.text().to_string()], ident, None)); + } else if let Some(mut attr) = Select::cast(tok) { + let mut result = vec![attr.index()?.to_string()]; while let Some(new) = Select::cast(attr.set()?) { result.push(Ident::cast(new.index()?)?.as_str().into()); attr = new; } result.push(Ident::cast(attr.set()?)?.as_str().into()); result.reverse(); - return Some(CursorInfo::new(result, ident.clone(), None)); + return Some(CursorInfo::new(result, ident, None)); } } } @@ -214,7 +209,7 @@ pub fn populate( set: set.node().to_owned(), key: ident.node().to_owned(), value: Some(entry.value()?.to_owned()), - datatype: datatype, + datatype, }, ); } @@ -229,14 +224,14 @@ pub fn scope_for(file: &Rc, node: SyntaxNode) -> Option { - populate(&file, &mut scope, &let_in, Datatype::Variable); + populate(file, &mut scope, &let_in, Datatype::Variable); } Ok(ParsedType::LegacyLet(let_)) => { - populate(&file, &mut scope, &let_, Datatype::Variable); + populate(file, &mut scope, &let_, Datatype::Variable); } Ok(ParsedType::AttrSet(set)) => { if set.recursive() { - populate(&file, &mut scope, &set, Datatype::Attribute); + populate(file, &mut scope, &set, Datatype::Attribute); } } Ok(ParsedType::Lambda(lambda)) => match ParsedType::try_from(lambda.arg()?) { @@ -245,7 +240,7 @@ pub fn scope_for(file: &Rc, node: SyntaxNode) -> Option, node: SyntaxNode) -> Option, node: SyntaxNode) -> Option