From ce447185d12461838790e243353051ff9eb55b12 Mon Sep 17 00:00:00 2001 From: QuadnucYard <50077758+QuadnucYard@users.noreply.github.com> Date: Mon, 1 Sep 2025 16:46:54 +0800 Subject: [PATCH] dev: drop if_chain and collapse if statements (#2097) --- Cargo.lock | 2 - Cargo.toml | 1 - crates/tinymist-analysis/Cargo.toml | 1 - .../tinymist-analysis/src/syntax/matcher.rs | 94 +++++------ crates/tinymist-analysis/src/track_values.rs | 17 +- crates/tinymist-analysis/src/upstream/mod.rs | 11 +- .../tinymist-analysis/src/upstream/tooltip.rs | 44 +++-- crates/tinymist-debug/src/cov.rs | 14 +- crates/tinymist-lint/src/lib.rs | 22 +-- crates/tinymist-project/src/entry.rs | 26 +-- crates/tinymist-project/src/model.rs | 8 +- crates/tinymist-query/Cargo.toml | 1 - crates/tinymist-query/src/adt/revision.rs | 8 +- .../src/analysis/code_action.rs | 23 ++- .../tinymist-query/src/analysis/completion.rs | 9 +- .../src/analysis/completion/import.rs | 113 +++++++------ .../src/analysis/completion/mode.rs | 155 +++++++++--------- .../src/analysis/completion/scope.rs | 16 +- .../src/analysis/completion/typst_specific.rs | 18 +- crates/tinymist-query/src/analysis/global.rs | 8 +- .../tinymist-query/src/analysis/link_expr.rs | 8 +- .../src/analysis/semantic_tokens.rs | 39 ++--- .../tinymist-query/src/analysis/tyck/apply.rs | 16 +- .../tinymist-query/src/analysis/tyck/docs.rs | 16 +- crates/tinymist-query/src/docs/convert.rs | 12 +- crates/tinymist-query/src/docs/module.rs | 9 +- crates/tinymist-query/src/docs/package.rs | 49 +++--- crates/tinymist-query/src/hover.rs | 8 +- crates/tinymist-query/src/jump.rs | 18 +- crates/tinymist-query/src/syntax/expr.rs | 11 +- .../src/syntax/lexical_hierarchy.rs | 8 +- crates/tinymist-query/src/tests.rs | 20 +-- crates/tinymist-world/src/font/info.rs | 8 +- crates/tinymist-world/src/font/web/mod.rs | 10 +- crates/tinymist-world/src/snapshot.rs | 16 +- crates/tinymist/src/actor/editor.rs | 4 +- crates/typlite/src/main.rs | 8 +- crates/typlite/src/parser/list.rs | 91 +++++----- crates/typlite/src/parser/table.rs | 90 +++++----- crates/typlite/src/writer/docx/writer.rs | 14 +- crates/typlite/src/writer/text.rs | 8 +- crates/typst-preview/src/actor/render.rs | 11 +- 42 files changed, 520 insertions(+), 545 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 98cba8d9..9e05a57a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4205,7 +4205,6 @@ dependencies = [ "ecow", "ena", "hashbrown 0.14.5", - "if_chain", "insta", "itertools 0.13.0", "log", @@ -4487,7 +4486,6 @@ dependencies = [ "ena", "hayagriva", "hex", - "if_chain", "indexmap 2.10.0", "itertools 0.13.0", "log", diff --git a/Cargo.toml b/Cargo.toml index 3be5a6f8..6d93989b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,6 @@ members = ["benches/*", "crates/*", "tests"] # Basic Infra anyhow = "1" -if_chain = "1" itertools = "0.13" paste = "1.0" cfg-if = "1.0" diff --git a/crates/tinymist-analysis/Cargo.toml b/crates/tinymist-analysis/Cargo.toml index c4e5b1bb..94ab1cac 100644 --- a/crates/tinymist-analysis/Cargo.toml +++ b/crates/tinymist-analysis/Cargo.toml @@ -17,7 +17,6 @@ dashmap.workspace = true ecow.workspace = true ena.workspace = true hashbrown.workspace = true -if_chain.workspace = true itertools.workspace = true log.workspace = true lsp-types.workspace = true diff --git a/crates/tinymist-analysis/src/syntax/matcher.rs b/crates/tinymist-analysis/src/syntax/matcher.rs index 9512abfa..fb26b28d 100644 --- a/crates/tinymist-analysis/src/syntax/matcher.rs +++ b/crates/tinymist-analysis/src/syntax/matcher.rs @@ -228,10 +228,10 @@ pub fn previous_decls( if let Some(t) = recv(PreviousDecl::Ident(new_name)) { return Some(t); } - } else if import.imports().is_none() { - if let Some(t) = recv(PreviousDecl::ImportSource(import.source())) { - return Some(t); - } + } else if import.imports().is_none() + && let Some(t) = recv(PreviousDecl::ImportSource(import.source())) + { + return Some(t); } } (PreviousItem::Parent(parent, child), ast::Expr::For(for_expr)) => { @@ -269,10 +269,10 @@ pub fn previous_decls( } } ast::Param::Spread(spread) => { - if let Some(sink_ident) = spread.sink_ident() { - if let Some(t) = recv(PreviousDecl::Ident(sink_ident)) { - return Some(t); - } + if let Some(sink_ident) = spread.sink_ident() + && let Some(t) = recv(PreviousDecl::Ident(sink_ident)) + { + return Some(t); } } } @@ -506,12 +506,11 @@ pub fn adjust_expr(mut node: LinkedNode) -> Option { while let Some(paren_expr) = node.cast::() { node = node.find(paren_expr.expr().span())?; } - if let Some(parent) = node.parent() { - if let Some(field_access) = parent.cast::() { - if node.span() == field_access.field().span() { - return Some(parent.clone()); - } - } + if let Some(parent) = node.parent() + && let Some(field_access) = parent.cast::() + && node.span() == field_access.field().span() + { + return Some(parent.clone()); } Some(node) } @@ -789,26 +788,26 @@ pub fn classify_syntax(node: LinkedNode<'_>, cursor: usize) -> Option, cursor: usize) -> Option( } _ => { let parent = node.parent(); - if let Some(parent) = parent { - if parent.kind() == SyntaxKind::Named { - let param_ident = parent.cast::()?; - let name = param_ident.name(); - let init = param_ident.expr(); - let init = parent.find(init.span())?; - if init.range().contains(&node.offset()) { - let name = args_node.find(name.span())?; - return Some(ArgClass::Named(name)); - } + if let Some(parent) = parent + && parent.kind() == SyntaxKind::Named + { + let param_ident = parent.cast::()?; + let name = param_ident.name(); + let init = param_ident.expr(); + let init = parent.find(init.span())?; + if init.range().contains(&node.offset()) { + let name = args_node.find(name.span())?; + return Some(ArgClass::Named(name)); } } diff --git a/crates/tinymist-analysis/src/track_values.rs b/crates/tinymist-analysis/src/track_values.rs index 59e03f27..459cd81e 100644 --- a/crates/tinymist-analysis/src/track_values.rs +++ b/crates/tinymist-analysis/src/track_values.rs @@ -13,10 +13,11 @@ use typst_shim::eval::Vm; /// Try to determine a set of possible values for an expression. pub fn analyze_expr(world: &dyn World, node: &LinkedNode) -> EcoVec<(Value, Option)> { - if let Some(parent) = node.parent() { - if parent.kind() == SyntaxKind::FieldAccess && node.index() > 0 { - return analyze_expr(world, parent); - } + if let Some(parent) = node.parent() + && parent.kind() == SyntaxKind::FieldAccess + && node.index() > 0 + { + return analyze_expr(world, parent); } analyze_expr_(world, node.get()) @@ -38,10 +39,10 @@ pub fn analyze_expr_(world: &dyn World, node: &SyntaxNode) -> EcoVec<(Value, Opt ast::Expr::Numeric(v) => Value::numeric(v.get()), ast::Expr::Str(v) => Value::Str(v.get().into()), _ => { - if node.kind() == SyntaxKind::Contextual { - if let Some(child) = node.children().last() { - return analyze_expr_(world, child); - } + if node.kind() == SyntaxKind::Contextual + && let Some(child) = node.children().last() + { + return analyze_expr_(world, child); } return typst::trace::(world, node.span()); diff --git a/crates/tinymist-analysis/src/upstream/mod.rs b/crates/tinymist-analysis/src/upstream/mod.rs index 5e283244..b819dafb 100644 --- a/crates/tinymist-analysis/src/upstream/mod.rs +++ b/crates/tinymist-analysis/src/upstream/mod.rs @@ -226,14 +226,13 @@ fn resolve_definition(head: &str, base: &str) -> StrResult { if let Ok(field) = value.field(next, ()) { route.push_str("/#definitions-"); route.push_str(next); - if let Some(next) = parts.next() { - if field + if let Some(next) = parts.next() + && field .cast::() .is_ok_and(|func| func.param(next).is_some()) - { - route.push('-'); - route.push_str(next); - } + { + route.push('-'); + route.push_str(next); } } else if value .clone() diff --git a/crates/tinymist-analysis/src/upstream/tooltip.rs b/crates/tinymist-analysis/src/upstream/tooltip.rs index 3d04da8b..8e1e564d 100644 --- a/crates/tinymist-analysis/src/upstream/tooltip.rs +++ b/crates/tinymist-analysis/src/upstream/tooltip.rs @@ -1,7 +1,6 @@ use std::fmt::Write; use ecow::{EcoString, eco_format}; -use if_chain::if_chain; use typst::World; use typst::engine::Sink; use typst::foundations::{Capturer, Value, repr}; @@ -55,10 +54,10 @@ pub fn expr_tooltip(world: &dyn World, leaf: &LinkedNode) -> Option { let values = analyze_expr(world, ancestor); - if let [(Value::Length(length), _)] = values.as_slice() { - if let Some(tooltip) = length_tooltip(*length) { - return Some(tooltip); - } + if let [(Value::Length(length), _)] = values.as_slice() + && let Some(tooltip) = length_tooltip(*length) + { + return Some(tooltip); } if expr.is_literal() { @@ -105,10 +104,10 @@ pub fn expr_tooltip(world: &dyn World, leaf: &LinkedNode) -> Option { return None; } - if let Some((_, count)) = last { - if count > 1 { - write!(pieces.last_mut().unwrap(), " (x{count})").unwrap(); - } + if let Some((_, count)) = last + && count > 1 + { + write!(pieces.last_mut().unwrap(), " (x{count})").unwrap(); } if iter.next().is_some() { @@ -170,27 +169,24 @@ fn length_tooltip(length: Length) -> Option { /// Tooltip for font. fn font_tooltip(world: &dyn World, leaf: &LinkedNode) -> Option { - if_chain! { - // Ensure that we are on top of a string. - if let Some(string) = leaf.cast::(); - let lower = string.get().to_lowercase(); + // Ensure that we are on top of a string. + if let Some(string) = leaf.cast::() + &&let lower = string.get().to_lowercase() // Ensure that we are in the arguments to the text function. - if let Some(parent) = leaf.parent(); - if let Some(named) = parent.cast::(); - if named.name().as_str() == "font"; + && let Some(parent) = leaf.parent() + && let Some(named) = parent.cast::() + && named.name().as_str() == "font" // Find the font family. - if let Some((_, iter)) = world + && let Some((_, iter)) = world .book() .families() - .find(|&(family, _)| family.to_lowercase().as_str() == lower.as_str()); - - then { - let detail = summarize_font_family(iter); - return Some(Tooltip::Text(detail)); - } - }; + .find(|&(family, _)| family.to_lowercase().as_str() == lower.as_str()) + { + let detail = summarize_font_family(iter); + return Some(Tooltip::Text(detail)); + } None } diff --git a/crates/tinymist-debug/src/cov.rs b/crates/tinymist-debug/src/cov.rs index 8f4ef25b..a5029f5b 100644 --- a/crates/tinymist-debug/src/cov.rs +++ b/crates/tinymist-debug/src/cov.rs @@ -211,13 +211,13 @@ pub fn __cov_pc(span: Span, pc: i64) { return; }; let mut map = COVERAGE_MAP.lock(); - if let Some(last_hit) = map.last_hit.as_ref() { - if last_hit.0 == fid { - let mut hits = last_hit.1.hits.lock(); - let c = &mut hits[pc as usize]; - *c = c.saturating_add(1); - return; - } + if let Some(last_hit) = map.last_hit.as_ref() + && last_hit.0 == fid + { + let mut hits = last_hit.1.hits.lock(); + let c = &mut hits[pc as usize]; + *c = c.saturating_add(1); + return; } let region = map.regions.entry(fid).or_default(); diff --git a/crates/tinymist-lint/src/lib.rs b/crates/tinymist-lint/src/lib.rs index ebb0c667..6a145f44 100644 --- a/crates/tinymist-lint/src/lib.rs +++ b/crates/tinymist-lint/src/lib.rs @@ -218,13 +218,13 @@ impl<'w> Linter<'w> { fn check_variable_font<'a>(&mut self, args: impl IntoIterator>) { for arg in args { - if let ast::Arg::Named(arg) = arg { - if arg.name().as_str() == "font" { - self.check_variable_font_object(arg.expr().to_untyped()); - if let Some(array) = arg.expr().to_untyped().cast::() { - for item in array.items() { - self.check_variable_font_object(item.to_untyped()); - } + if let ast::Arg::Named(arg) = arg + && arg.name().as_str() == "font" + { + self.check_variable_font_object(arg.expr().to_untyped()); + if let Some(array) = arg.expr().to_untyped().cast::() { + for item in array.items() { + self.check_variable_font_object(item.to_untyped()); } } } @@ -234,10 +234,10 @@ impl<'w> Linter<'w> { fn check_variable_font_object(&mut self, expr: &SyntaxNode) -> Option<()> { if let Some(font_dict) = expr.cast::() { for item in font_dict.items() { - if let ast::DictItem::Named(arg) = item { - if arg.name().as_str() == "name" { - self.check_variable_font_str(arg.expr().to_untyped()); - } + if let ast::DictItem::Named(arg) = item + && arg.name().as_str() == "name" + { + self.check_variable_font_str(arg.expr().to_untyped()); } } } diff --git a/crates/tinymist-project/src/entry.rs b/crates/tinymist-project/src/entry.rs index 273cbdfd..70d61e71 100644 --- a/crates/tinymist-project/src/entry.rs +++ b/crates/tinymist-project/src/entry.rs @@ -169,25 +169,25 @@ impl EntryResolver { pub fn resolve_default(&self) -> Option { let entry = self.entry.as_ref(); // todo: pre-compute this when updating config - if let Some(entry) = entry { - if entry.is_relative() { - let root = self.root(None)?; - return Some(root.join(entry).as_path().into()); - } + if let Some(entry) = entry + && entry.is_relative() + { + let root = self.root(None)?; + return Some(root.join(entry).as_path().into()); } entry.cloned() } /// Validates the configuration. pub fn validate(&self) -> Result<()> { - if let Some(root) = &self.root_path { - if !root.is_absolute() { - tinymist_l10n::bail!( - "tinymist-project.validate-error.root-path-not-absolute", - "rootPath or typstExtraArgs.root must be an absolute path: {root:?}", - root = root.debug_l10n() - ); - } + if let Some(root) = &self.root_path + && !root.is_absolute() + { + tinymist_l10n::bail!( + "tinymist-project.validate-error.root-path-not-absolute", + "rootPath or typstExtraArgs.root must be an absolute path: {root:?}", + root = root.debug_l10n() + ); } Ok(()) diff --git a/crates/tinymist-project/src/model.rs b/crates/tinymist-project/src/model.rs index 463f77f5..e93edb50 100644 --- a/crates/tinymist-project/src/model.rs +++ b/crates/tinymist-project/src/model.rs @@ -102,10 +102,10 @@ pub struct ProjectInput { impl ProjectInput { /// Returns a new project input relative to the provided lock directory. pub fn relative_to(&self, that: &Path) -> Self { - if let Some(lock_dir) = &self.lock_dir { - if lock_dir == that { - return self.clone(); - } + if let Some(lock_dir) = &self.lock_dir + && lock_dir == that + { + return self.clone(); } todo!() diff --git a/crates/tinymist-query/Cargo.toml b/crates/tinymist-query/Cargo.toml index 97865f7a..f68a2a44 100644 --- a/crates/tinymist-query/Cargo.toml +++ b/crates/tinymist-query/Cargo.toml @@ -22,7 +22,6 @@ dirs.workspace = true ena.workspace = true ecow.workspace = true hayagriva.workspace = true -if_chain.workspace = true itertools.workspace = true indexmap.workspace = true log.workspace = true diff --git a/crates/tinymist-query/src/adt/revision.rs b/crates/tinymist-query/src/adt/revision.rs index c517c71c..0fb5bdb8 100644 --- a/crates/tinymist-query/src/adt/revision.rs +++ b/crates/tinymist-query/src/adt/revision.rs @@ -88,10 +88,10 @@ impl RevisionManager { .filter(|slot| slot.revision <= revision.get()) .reduce(|x, y| if x.revision > y.revision { x } else { y }); - if let Some(slot) = slot_base { - if slot.revision == revision.get() { - return slot.clone(); - } + if let Some(slot) = slot_base + && slot.revision == revision.get() + { + return slot.clone(); } let slot = Arc::new(RevisionSlot { diff --git a/crates/tinymist-query/src/analysis/code_action.rs b/crates/tinymist-query/src/analysis/code_action.rs index 951b3854..10375c44 100644 --- a/crates/tinymist-query/src/analysis/code_action.rs +++ b/crates/tinymist-query/src/analysis/code_action.rs @@ -62,14 +62,13 @@ impl<'a> CodeActionWorker<'a> { range: &Range, context: &lsp_types::CodeActionContext, ) -> Option<()> { - if let Some(only) = &context.only { - if !only.is_empty() - && !only - .iter() - .any(|kind| *kind == CodeActionKind::EMPTY || *kind == CodeActionKind::QUICKFIX) - { - return None; - } + if let Some(only) = &context.only + && !only.is_empty() + && !only + .iter() + .any(|kind| *kind == CodeActionKind::EMPTY || *kind == CodeActionKind::QUICKFIX) + { + return None; } for diag in &context.diagnostics { @@ -546,10 +545,10 @@ impl<'a> CodeActionWorker<'a> { ), ]; - if !new_text.is_empty() { - if let Some((_, edit)) = &punc_modify { - edits.push(edit.clone()); - } + if !new_text.is_empty() + && let Some((_, edit)) = &punc_modify + { + edits.push(edit.clone()); } Some(CodeAction { diff --git a/crates/tinymist-query/src/analysis/completion.rs b/crates/tinymist-query/src/analysis/completion.rs index ec4be09a..1b00ed19 100644 --- a/crates/tinymist-query/src/analysis/completion.rs +++ b/crates/tinymist-query/src/analysis/completion.rs @@ -5,7 +5,6 @@ use std::collections::{BTreeMap, HashSet}; use std::ops::Range; use ecow::{EcoString, eco_format}; -use if_chain::if_chain; use lsp_types::InsertTextFormat; use regex::{Captures, Regex}; use serde::{Deserialize, Serialize}; @@ -300,10 +299,10 @@ impl<'a> CompletionCursor<'a> { /// Gets the LSP range of a given range with caching. fn lsp_range_of(&mut self, rng: Range) -> LspRange { // self.ctx.to_lsp_range(rng, &self.source) - if let Some((last_rng, last_lsp_rng)) = &self.last_lsp_range_pair { - if *last_rng == rng { - return *last_lsp_rng; - } + if let Some((last_rng, last_lsp_rng)) = &self.last_lsp_range_pair + && *last_rng == rng + { + return *last_lsp_rng; } let lsp_rng = self.ctx.to_lsp_range(rng.clone(), &self.source); diff --git a/crates/tinymist-query/src/analysis/completion/import.rs b/crates/tinymist-query/src/analysis/completion/import.rs index 628d4f98..6e2d8a06 100644 --- a/crates/tinymist-query/src/analysis/completion/import.rs +++ b/crates/tinymist-query/src/analysis/completion/import.rs @@ -6,81 +6,78 @@ impl CompletionPair<'_, '_, '_> { pub fn complete_imports(&mut self) -> bool { // On the colon marker of an import list: // "#import "path.typ":|" - if_chain! { - if matches!(self.cursor.leaf.kind(), SyntaxKind::Colon); - if let Some(parent) = self.cursor.leaf.clone().parent(); - if let Some(ast::Expr::Import(import)) = parent.get().cast(); - if !matches!(import.imports(), Some(ast::Imports::Wildcard)); - if let Some(source) = parent.children().find(|child| child.is::()); - then { - let items = match import.imports() { - Some(ast::Imports::Items(items)) => items, - _ => Default::default(), - }; + if matches!(self.cursor.leaf.kind(), SyntaxKind::Colon) + && let Some(parent) = self.cursor.leaf.clone().parent() + && let Some(ast::Expr::Import(import)) = parent.get().cast() + && !matches!(import.imports(), Some(ast::Imports::Wildcard)) + && let Some(source) = parent.children().find(|child| child.is::()) + { + let items = match import.imports() { + Some(ast::Imports::Items(items)) => items, + _ => Default::default(), + }; - self.cursor.from = self.cursor.cursor; + self.cursor.from = self.cursor.cursor; - self.import_item_completions(items, vec![], &source); - if items.iter().next().is_some() { - self.worker.enrich("", ", "); - } - return true; + self.import_item_completions(items, vec![], &source); + if items.iter().next().is_some() { + self.worker.enrich("", ", "); } + return true; } // Behind an import list: // "#import "path.typ": |", // "#import "path.typ": a, b, |". - if_chain! { - if let Some(prev) = self.cursor.leaf.prev_sibling(); - if let Some(ast::Expr::Import(import)) = prev.get().cast(); - if !self.cursor.text[prev.offset()..self.cursor.cursor].contains('\n'); - if let Some(ast::Imports::Items(items)) = import.imports(); - if let Some(source) = prev.children().find(|child| child.is::()); - then { - self. cursor.from = self.cursor.cursor; - self.import_item_completions(items, vec![], &source); - return true; - } + + if let Some(prev) = self.cursor.leaf.prev_sibling() + && let Some(ast::Expr::Import(import)) = prev.get().cast() + && !self.cursor.text[prev.offset()..self.cursor.cursor].contains('\n') + && let Some(ast::Imports::Items(items)) = import.imports() + && let Some(source) = prev.children().find(|child| child.is::()) + { + self.cursor.from = self.cursor.cursor; + self.import_item_completions(items, vec![], &source); + return true; } // Behind a comma in an import list: // "#import "path.typ": this,|". - if_chain! { - if matches!(self.cursor.leaf.kind(), SyntaxKind::Comma); - if let Some(parent) = self.cursor.leaf.clone().parent(); - if parent.kind() == SyntaxKind::ImportItems; - if let Some(grand) = parent.parent(); - if let Some(ast::Expr::Import(import)) = grand.get().cast(); - if let Some(ast::Imports::Items(items)) = import.imports(); - if let Some(source) = grand.children().find(|child| child.is::()); - then { - self.import_item_completions(items, vec![], &source); - self.worker.enrich(" ", ""); - return true; - } + if matches!(self.cursor.leaf.kind(), SyntaxKind::Comma) + && let Some(parent) = self.cursor.leaf.clone().parent() + && parent.kind() == SyntaxKind::ImportItems + && let Some(grand) = parent.parent() + && let Some(ast::Expr::Import(import)) = grand.get().cast() + && let Some(ast::Imports::Items(items)) = import.imports() + && let Some(source) = grand.children().find(|child| child.is::()) + { + self.import_item_completions(items, vec![], &source); + self.worker.enrich(" ", ""); + return true; } // Behind a half-started identifier in an import list: // "#import "path.typ": th|". - if_chain! { - if matches!(self.cursor.leaf.kind(), SyntaxKind::Ident | SyntaxKind::Dot); - if let Some(path_ctx) = self.cursor.leaf.clone().parent(); - if path_ctx.kind() == SyntaxKind::ImportItemPath; - if let Some(parent) = path_ctx.parent(); - if parent.kind() == SyntaxKind::ImportItems; - if let Some(grand) = parent.parent(); - if let Some(ast::Expr::Import(import)) = grand.get().cast(); - if let Some(ast::Imports::Items(items)) = import.imports(); - if let Some(source) = grand.children().find(|child| child.is::()); - then { - if self.cursor.leaf.kind() == SyntaxKind::Ident { - self.cursor.from = self.cursor.leaf.offset(); - } - let path = path_ctx.cast::().map(|path| path.iter().take_while(|ident| ident.span() != self.cursor.leaf.span()).collect()); - self.import_item_completions( items, path.unwrap_or_default(), &source); - return true; + if matches!(self.cursor.leaf.kind(), SyntaxKind::Ident | SyntaxKind::Dot) + && let Some(path_ctx) = self.cursor.leaf.clone().parent() + && path_ctx.kind() == SyntaxKind::ImportItemPath + && let Some(parent) = path_ctx.parent() + && parent.kind() == SyntaxKind::ImportItems + && let Some(grand) = parent.parent() + && let Some(ast::Expr::Import(import)) = grand.get().cast() + && let Some(ast::Imports::Items(items)) = import.imports() + && let Some(source) = grand.children().find(|child| child.is::()) + { + if self.cursor.leaf.kind() == SyntaxKind::Ident { + self.cursor.from = self.cursor.leaf.offset(); } + let path = path_ctx.cast::().map(|path| { + path.iter() + .take_while(|ident| ident.span() != self.cursor.leaf.span()) + .collect() + }); + self.import_item_completions(items, path.unwrap_or_default(), &source); + return true; } false diff --git a/crates/tinymist-query/src/analysis/completion/mode.rs b/crates/tinymist-query/src/analysis/completion/mode.rs index 6205a659..5fca42cc 100644 --- a/crates/tinymist-query/src/analysis/completion/mode.rs +++ b/crates/tinymist-query/src/analysis/completion/mode.rs @@ -6,67 +6,63 @@ impl CompletionPair<'_, '_, '_> { pub fn complete_comments(&mut self) -> bool { let text = self.cursor.leaf.get().text(); // check if next line defines a function - if_chain! { - if text == "///" || text == "/// "; + if (text == "///" || text == "/// ") // hash node - if let Some(hash_node) = self.cursor.leaf.next_leaf(); + && let Some(hash_node) = self.cursor.leaf.next_leaf() // let node - if let Some(let_node) = hash_node.next_leaf(); - if let Some(let_closure) = let_node.next_leaf(); - if matches!(let_closure.parent_kind(), Some(SyntaxKind::Closure)); - if let Some(closure) = let_closure.parent(); - if let Some(closure) = closure.cast::(); - if let ast::Expr::Closure(c) = closure; - then { - // Only completes if the next line is a function definition - let rng = self.cursor.leaf.offset()..hash_node.offset(); - let text_between = &self.cursor.source.text()[rng]; - let mut line_count = 0; - for ch in text_between.chars() { - if ch == '\n' { - line_count += 1; - } - if line_count > 1 { - return false; - } + && let Some(let_node) = hash_node.next_leaf() + && let Some(let_closure) = let_node.next_leaf() + && matches!(let_closure.parent_kind(), Some(SyntaxKind::Closure)) + && let Some(closure) = let_closure.parent() + && let Some(closure) = closure.cast::() + && let ast::Expr::Closure(c) = closure + { + // Only completes if the next line is a function definition + let rng = self.cursor.leaf.offset()..hash_node.offset(); + let text_between = &self.cursor.source.text()[rng]; + let mut line_count = 0; + for ch in text_between.chars() { + if ch == '\n' { + line_count += 1; } - - let mut doc_snippet: String = if text == "///" { - " $0\n///".to_string() - } else { - "$0\n///".to_string() - }; - let mut i = 0; - for param in c.params().children() { - // TODO: Properly handle Pos and Spread argument - let param: &EcoString = match param { - Param::Pos(p) => { - match p { - ast::Pattern::Normal(ast::Expr::Ident(ident)) => ident.get(), - _ => &"_".into() - } - } - Param::Named(n) => n.name().get(), - Param::Spread(s) => { - if let Some(ident) = s.sink_ident() { - &eco_format!("{}", ident.get()) - } else { - &EcoString::new() - } - } - }; - log::info!("param: {param}, index: {i}"); - doc_snippet += &format!("\n/// - {param} (${}): ${}", i + 1, i + 2); - i += 2; + if line_count > 1 { + return false; } - doc_snippet += &format!("\n/// -> ${}", i + 1); - self.push_completion(Completion { - label: "Document function".into(), - apply: Some(doc_snippet.into()), - ..Completion::default() - }); } - }; + + let mut doc_snippet: String = if text == "///" { + " $0\n///".to_string() + } else { + "$0\n///".to_string() + }; + let mut i = 0; + for param in c.params().children() { + // TODO: Properly handle Pos and Spread argument + let param: &EcoString = match param { + Param::Pos(p) => match p { + ast::Pattern::Normal(ast::Expr::Ident(ident)) => ident.get(), + _ => &"_".into(), + }, + Param::Named(n) => n.name().get(), + Param::Spread(s) => { + if let Some(ident) = s.sink_ident() { + &eco_format!("{}", ident.get()) + } else { + &EcoString::new() + } + } + }; + log::info!("param: {param}, index: {i}"); + doc_snippet += &format!("\n/// - {param} (${}): ${}", i + 1, i + 2); + i += 2; + } + doc_snippet += &format!("\n/// -> ${}", i + 1); + self.push_completion(Completion { + label: "Document function".into(), + apply: Some(doc_snippet.into()), + ..Completion::default() + }); + } true } @@ -77,26 +73,25 @@ impl CompletionPair<'_, '_, '_> { node_ancestors(&self.cursor.leaf).find(|node| matches!(node.kind(), SyntaxKind::Raw)); // Behind a half-completed binding: "#let x = |" or `#let f(x) = |`. - if_chain! { - if let Some(prev) = self.cursor.leaf.prev_leaf(); - if matches!(prev.kind(), SyntaxKind::Eq | SyntaxKind::Arrow); - if matches!( prev.parent_kind(), Some(SyntaxKind::LetBinding | SyntaxKind::Closure)); - then { - self.cursor.from = self.cursor.cursor; - self.code_completions( false); - return true; - } + if let Some(prev) = self.cursor.leaf.prev_leaf() + && matches!(prev.kind(), SyntaxKind::Eq | SyntaxKind::Arrow) + && matches!( + prev.parent_kind(), + Some(SyntaxKind::LetBinding | SyntaxKind::Closure) + ) + { + self.cursor.from = self.cursor.cursor; + self.code_completions(false); + return true; } // Behind a half-completed context block: "#context |". - if_chain! { - if let Some(prev) = self.cursor.leaf.prev_leaf(); - if prev.kind() == SyntaxKind::Context; - then { - self.cursor.from = self.cursor.cursor; - self.code_completions(false); - return true; - } + if let Some(prev) = self.cursor.leaf.prev_leaf() + && prev.kind() == SyntaxKind::Context + { + self.cursor.from = self.cursor.cursor; + self.code_completions(false); + return true; } // Directly after a raw block. @@ -171,14 +166,12 @@ impl CompletionPair<'_, '_, '_> { } // Behind a half-completed context block: "context |". - if_chain! { - if let Some(prev) = self.cursor.leaf.prev_leaf(); - if prev.kind() == SyntaxKind::Context; - then { - self.cursor.from = self.cursor.cursor; - self.code_completions(false); - return true; - } + if let Some(prev) = self.cursor.leaf.prev_leaf() + && prev.kind() == SyntaxKind::Context + { + self.cursor.from = self.cursor.cursor; + self.code_completions(false); + return true; } // An existing identifier: "{ pa| }". diff --git a/crates/tinymist-query/src/analysis/completion/scope.rs b/crates/tinymist-query/src/analysis/completion/scope.rs index 204f798e..750cf022 100644 --- a/crates/tinymist-query/src/analysis/completion/scope.rs +++ b/crates/tinymist-query/src/analysis/completion/scope.rs @@ -139,10 +139,10 @@ impl CompletionPair<'_, '_, '_> { SurroundingSyntax::SetRule => 'set_rule: { // todo: user defined elements for func in &checker.functions { - if let Some(elem) = func.element() { - if elem.params().iter().any(|param| param.settable) { - break 'set_rule true; - } + if let Some(elem) = func.element() + && elem.params().iter().any(|param| param.settable) + { + break 'set_rule true; } } @@ -196,10 +196,10 @@ impl CompletionPair<'_, '_, '_> { } fn analyze_import_source(ctx: &LocalContext, types: &TypeInfo, s: ast::Expr) -> Option { - if let Some(res) = types.type_of_span(s.span()) { - if !matches!(res.value(), Some(Value::Str(..))) { - return Some(types.simplify(res, false)); - } + if let Some(res) = types.type_of_span(s.span()) + && !matches!(res.value(), Some(Value::Str(..))) + { + return Some(types.simplify(res, false)); } let m = ctx.module_by_syntax(s.to_untyped())?; diff --git a/crates/tinymist-query/src/analysis/completion/typst_specific.rs b/crates/tinymist-query/src/analysis/completion/typst_specific.rs index 92f6c5eb..9d666348 100644 --- a/crates/tinymist-query/src/analysis/completion/typst_specific.rs +++ b/crates/tinymist-query/src/analysis/completion/typst_specific.rs @@ -226,16 +226,18 @@ impl CompletionPair<'_, '_, '_> { apply = Some(eco_format!("at(\"{label}\")")); } else { let apply_label = &mut label.as_str(); - if apply_label.ends_with('"') && self.cursor.after.starts_with('"') { - if let Some(trimmed) = apply_label.strip_suffix('"') { - *apply_label = trimmed; - } + if apply_label.ends_with('"') + && self.cursor.after.starts_with('"') + && let Some(trimmed) = apply_label.strip_suffix('"') + { + *apply_label = trimmed; } let from_before = slice_at(self.cursor.text, 0..self.cursor.from); - if apply_label.starts_with('"') && from_before.ends_with('"') { - if let Some(trimmed) = apply_label.strip_prefix('"') { - *apply_label = trimmed; - } + if apply_label.starts_with('"') + && from_before.ends_with('"') + && let Some(trimmed) = apply_label.strip_prefix('"') + { + *apply_label = trimmed; } if apply_label.len() != label.len() { diff --git a/crates/tinymist-query/src/analysis/global.rs b/crates/tinymist-query/src/analysis/global.rs index df19cb66..cec837a0 100644 --- a/crates/tinymist-query/src/analysis/global.rs +++ b/crates/tinymist-query/src/analysis/global.rs @@ -653,10 +653,10 @@ impl SharedContext { // e.g. `f(x|)`, we will select the `x` if cursor == node.offset() + 1 && is_mark(node.kind()) { let prev_leaf = node.prev_leaf(); - if let Some(prev_leaf) = prev_leaf { - if prev_leaf.range().end == node.offset() { - node = prev_leaf; - } + if let Some(prev_leaf) = prev_leaf + && prev_leaf.range().end == node.offset() + { + node = prev_leaf; } } diff --git a/crates/tinymist-query/src/analysis/link_expr.rs b/crates/tinymist-query/src/analysis/link_expr.rs index 20c73746..fbe22757 100644 --- a/crates/tinymist-query/src/analysis/link_expr.rs +++ b/crates/tinymist-query/src/analysis/link_expr.rs @@ -141,10 +141,10 @@ impl LinkStrWorker { for item in call.args().items() { match item { ast::Arg::Named(named) if named.name().get().as_str() == "style" => { - if let ast::Expr::Str(style) = named.expr() { - if hayagriva::archive::ArchivedStyle::by_name(&style.get()).is_some() { - return Some(()); - } + if let ast::Expr::Str(style) = named.expr() + && hayagriva::archive::ArchivedStyle::by_name(&style.get()).is_some() + { + return Some(()); } self.analyze_path_expr(node, named.expr()); return Some(()); diff --git a/crates/tinymist-query/src/analysis/semantic_tokens.rs b/crates/tinymist-query/src/analysis/semantic_tokens.rs index 238059fd..edcd5fe6 100644 --- a/crates/tinymist-query/src/analysis/semantic_tokens.rs +++ b/crates/tinymist-query/src/analysis/semantic_tokens.rs @@ -349,18 +349,19 @@ impl Tokenizer { .map(|token_type| Token::new(token_type, modifiers, range.clone())); // Push start - if let Some(prev_token) = self.token.as_mut() { - if !prev_token.range.is_empty() && prev_token.range.start < range.start { - let end = prev_token.range.end.min(range.start); - let sliced = Token { - token_type: prev_token.token_type, - modifiers: prev_token.modifiers, - range: prev_token.range.start..end, - }; - // Slice the previous token - prev_token.range.start = end; - self.push(sliced); - } + if let Some(prev_token) = self.token.as_mut() + && !prev_token.range.is_empty() + && prev_token.range.start < range.start + { + let end = prev_token.range.end.min(range.start); + let sliced = Token { + token_type: prev_token.token_type, + modifiers: prev_token.modifiers, + range: prev_token.range.start..end, + }; + // Slice the previous token + prev_token.range.start = end; + self.push(sliced); } if !is_leaf { @@ -372,14 +373,14 @@ impl Tokenizer { } // Push end - if let Some(token) = token.clone() { - if !token.range.is_empty() { - // Slice the previous token - if let Some(prev_token) = self.token.as_mut() { - prev_token.range.start = token.range.end; - } - self.push(token); + if let Some(token) = token.clone() + && !token.range.is_empty() + { + // Slice the previous token + if let Some(prev_token) = self.token.as_mut() { + prev_token.range.start = token.range.end; } + self.push(token); } } diff --git a/crates/tinymist-query/src/analysis/tyck/apply.rs b/crates/tinymist-query/src/analysis/tyck/apply.rs index 91457f3c..0dbab7ba 100644 --- a/crates/tinymist-query/src/analysis/tyck/apply.rs +++ b/crates/tinymist-query/src/analysis/tyck/apply.rs @@ -21,20 +21,18 @@ impl ApplyChecker for ApplyTypeChecker<'_, '_> { sig => (sig, false), }; - if !is_partialize { - if let Some(ty) = sig.call(args, pol, self.base) { - self.resultant.push(ty); - } + if !is_partialize && let Some(ty) = sig.call(args, pol, self.base) { + self.resultant.push(ty); } // todo: remove this after we implemented dependent types match sig { Sig::TypeCons { val, .. } => { - if *val == typst::foundations::Type::of::() { - if let Some(p0) = args.pos(0) { - self.resultant - .push(Ty::Unary(TypeUnary::new(UnaryOp::TypeOf, p0.clone()))); - } + if *val == typst::foundations::Type::of::() + && let Some(p0) = args.pos(0) + { + self.resultant + .push(Ty::Unary(TypeUnary::new(UnaryOp::TypeOf, p0.clone()))); } } Sig::Builtin(BuiltinSig::TupleMap(this)) => { diff --git a/crates/tinymist-query/src/analysis/tyck/docs.rs b/crates/tinymist-query/src/analysis/tyck/docs.rs index a43ee568..3ef9e9bd 100644 --- a/crates/tinymist-query/src/analysis/tyck/docs.rs +++ b/crates/tinymist-query/src/analysis/tyck/docs.rs @@ -25,17 +25,17 @@ impl TypeChecker<'_> { }; let mut vars = vars; for (_name, doc) in vars.iter_mut() { - if let Some(ty) = &mut doc.ty { - if let Some(mutated) = ty.mutate(true, &mut renamer) { - *ty = mutated; - } - } - } - if let Some(ty) = res_ty.as_mut() { - if let Some(mutated) = ty.mutate(true, &mut renamer) { + if let Some(ty) = &mut doc.ty + && let Some(mutated) = ty.mutate(true, &mut renamer) + { *ty = mutated; } } + if let Some(ty) = res_ty.as_mut() + && let Some(mutated) = ty.mutate(true, &mut renamer) + { + *ty = mutated; + } DocString { docs, var_bounds, diff --git a/crates/tinymist-query/src/docs/convert.rs b/crates/tinymist-query/src/docs/convert.rs index d9322d3e..898999b4 100644 --- a/crates/tinymist-query/src/docs/convert.rs +++ b/crates/tinymist-query/src/docs/convert.rs @@ -34,12 +34,12 @@ pub(crate) fn convert_docs( } let mut imports = Vec::new(); - if WorkspaceResolver::is_package_file(fid) { - if let Some(pkg) = fid.package() { - let pkg_spec = pkg.to_string(); - imports.push(format!("#import {pkg_spec:?}")); - imports.push(format!("#import {pkg_spec:?}: *")); - } + if WorkspaceResolver::is_package_file(fid) + && let Some(pkg) = fid.package() + { + let pkg_spec = pkg.to_string(); + imports.push(format!("#import {pkg_spec:?}")); + imports.push(format!("#import {pkg_spec:?}: *")); } imports.push(format!( "#import {:?}: *", diff --git a/crates/tinymist-query/src/docs/module.rs b/crates/tinymist-query/src/docs/module.rs index 623a9d9a..5435d6c9 100644 --- a/crates/tinymist-query/src/docs/module.rs +++ b/crates/tinymist-query/src/docs/module.rs @@ -229,12 +229,11 @@ impl ScanDefCtx<'_> { }; if let Some((span, mod_fid)) = head.decl.as_ref().and_then(|decl| decl.file_id()).zip(site) + && span != *mod_fid { - if span != *mod_fid { - head.is_external = true; - head.oneliner = head.docs.map(|docs| oneliner(&docs).to_owned()); - head.docs = None; - } + head.is_external = true; + head.oneliner = head.docs.map(|docs| oneliner(&docs).to_owned()); + head.docs = None; } // Insert module that is not exported diff --git a/crates/tinymist-query/src/docs/package.rs b/crates/tinymist-query/src/docs/package.rs index 93530453..1988f268 100644 --- a/crates/tinymist-query/src/docs/package.rs +++ b/crates/tinymist-query/src/docs/package.rs @@ -130,31 +130,30 @@ pub fn package_docs(ctx: &mut LocalContext, spec: &PackageInfo) -> StrResult Option { let value = def.value(); - if matches!(value, Some(Value::Func(..))) { - if let Some(builtin) = Self::builtin_func_tooltip("https://typst.app/docs/", def) { - return Some(builtin); - } + if matches!(value, Some(Value::Func(..))) + && let Some(builtin) = Self::builtin_func_tooltip("https://typst.app/docs/", def) + { + return Some(builtin); }; value.and_then(|value| Self::builtin_value_tooltip("https://typst.app/docs/", &value)) diff --git a/crates/tinymist-query/src/jump.rs b/crates/tinymist-query/src/jump.rs index 08eb04c0..226ac3c7 100644 --- a/crates/tinymist-query/src/jump.rs +++ b/crates/tinymist-query/src/jump.rs @@ -22,11 +22,11 @@ pub fn jump_from_click( ) -> Option<(SourceSpanOffset, SourceSpanOffset)> { // Try to find a link first. for (pos, item) in frame.items() { - if let FrameItem::Link(_dest, size) = item { - if is_in_rect(*pos, *size, click) { - // todo: url reaction - return None; - } + if let FrameItem::Link(_dest, size) = item + && is_in_rect(*pos, *size, click) + { + // todo: url reaction + return None; } } @@ -140,10 +140,10 @@ fn jump_from_cursor_( // In a page, we try to find a closer span than the existing found one. let mut p_dis = min_dis; - if let Some(point) = find_in_frame(&page.frame, span, &mut p_dis, &mut min_point) { - if let Some(page) = NonZeroUsize::new(idx + 1) { - positions.push(Position { page, point }); - } + if let Some(point) = find_in_frame(&page.frame, span, &mut p_dis, &mut min_point) + && let Some(page) = NonZeroUsize::new(idx + 1) + { + positions.push(Position { page, point }); } // In this page, we found a closer span and update. diff --git a/crates/tinymist-query/src/syntax/expr.rs b/crates/tinymist-query/src/syntax/expr.rs index 01fc946e..caa16434 100644 --- a/crates/tinymist-query/src/syntax/expr.rs +++ b/crates/tinymist-query/src/syntax/expr.rs @@ -55,12 +55,11 @@ pub(crate) fn expr_of( // If there is a cycle, the expression will be stable as the source is // unchanged. - if let Some(exports) = ei { - if prev_exports.size() != exports.size() - || hash128(&prev_exports) != hash128(&exports) - { - return None; - } + if let Some(exports) = ei + && (prev_exports.size() != exports.size() + || hash128(&prev_exports) != hash128(&exports)) + { + return None; } } diff --git a/crates/tinymist-query/src/syntax/lexical_hierarchy.rs b/crates/tinymist-query/src/syntax/lexical_hierarchy.rs index ffe7a58e..a4cf44c1 100644 --- a/crates/tinymist-query/src/syntax/lexical_hierarchy.rs +++ b/crates/tinymist-query/src/syntax/lexical_hierarchy.rs @@ -384,10 +384,10 @@ impl LexicalHierarchyWorker { SyntaxKind::Closure => { let first_child = node.children().next(); let current = self.stack.last_mut().unwrap().1.len(); - if let Some(first_child) = first_child { - if first_child.kind() == SyntaxKind::Ident { - self.check_node_with(first_child, IdentContext::Func)?; - } + if let Some(first_child) = first_child + && first_child.kind() == SyntaxKind::Ident + { + self.check_node_with(first_child, IdentContext::Func)?; } let body = node .children() diff --git a/crates/tinymist-query/src/tests.rs b/crates/tinymist-query/src/tests.rs index eede0567..d27c1402 100644 --- a/crates/tinymist-query/src/tests.rs +++ b/crates/tinymist-query/src/tests.rs @@ -251,20 +251,20 @@ fn match_by_pos(mut n: LinkedNode, prev: bool, ident: bool) -> usize { match n.kind() { SyntaxKind::Closure => { let closure = n.cast::().unwrap(); - if let Some(name) = closure.name() { - if let Some(m) = n.find(name.span()) { - n = m; - break 'match_loop; - } + if let Some(name) = closure.name() + && let Some(m) = n.find(name.span()) + { + n = m; + break 'match_loop; } } SyntaxKind::LetBinding => { let let_binding = n.cast::().unwrap(); - if let Some(name) = let_binding.kind().bindings().first() { - if let Some(m) = n.find(name.span()) { - n = m; - break 'match_loop; - } + if let Some(name) = let_binding.kind().bindings().first() + && let Some(m) = n.find(name.span()) + { + n = m; + break 'match_loop; } } _ => {} diff --git a/crates/tinymist-world/src/font/info.rs b/crates/tinymist-world/src/font/info.rs index 7fd984fb..5c9450f0 100644 --- a/crates/tinymist-world/src/font/info.rs +++ b/crates/tinymist-world/src/font/info.rs @@ -56,10 +56,10 @@ pub fn typst_typographic_family(mut family: &str) -> &str { // Also allow an extra modifier, but apply it only if it is separated it // from the text before it (to prevent false positives). - if let Some(t) = MODIFIERS.iter().find_map(|s| t.strip_suffix(s)) { - if let Some(stripped) = t.strip_suffix(SEPARATORS) { - trimmed = stripped; - } + if let Some(t) = MODIFIERS.iter().find_map(|s| t.strip_suffix(s)) + && let Some(stripped) = t.strip_suffix(SEPARATORS) + { + trimmed = stripped; } } diff --git a/crates/tinymist-world/src/font/web/mod.rs b/crates/tinymist-world/src/font/web/mod.rs index bd25611a..c63feea7 100644 --- a/crates/tinymist-world/src/font/web/mod.rs +++ b/crates/tinymist-world/src/font/web/mod.rs @@ -188,11 +188,11 @@ fn infer_info_from_web_font( _ => None, }; - if let Some(guess_stretch) = guess_stretch { - if idx == 0 { - stretch = Some(guess_stretch); - break 'searchLoop; - } + if let Some(guess_stretch) = guess_stretch + && idx == 0 + { + stretch = Some(guess_stretch); + break 'searchLoop; } } } diff --git a/crates/tinymist-world/src/snapshot.rs b/crates/tinymist-world/src/snapshot.rs index d816095c..f13d4112 100644 --- a/crates/tinymist-world/src/snapshot.rs +++ b/crates/tinymist-world/src/snapshot.rs @@ -131,15 +131,15 @@ impl CompileSnapshot { /// tasks break this assumption. pub fn task(mut self, inputs: TaskInputs) -> Self { 'check_changed: { - if let Some(entry) = &inputs.entry { - if *entry != self.world.entry_state() { - break 'check_changed; - } + if let Some(entry) = &inputs.entry + && *entry != self.world.entry_state() + { + break 'check_changed; } - if let Some(inputs) = &inputs.inputs { - if inputs.clone() != self.world.inputs() { - break 'check_changed; - } + if let Some(inputs) = &inputs.inputs + && inputs.clone() != self.world.inputs() + { + break 'check_changed; } return self; diff --git a/crates/tinymist/src/actor/editor.rs b/crates/tinymist/src/actor/editor.rs index 649b3f44..84541633 100644 --- a/crates/tinymist/src/actor/editor.rs +++ b/crates/tinymist/src/actor/editor.rs @@ -11,7 +11,6 @@ use serde::{Deserialize, Serialize}; use tinymist_project::CompileReport; use tinymist_query::DiagnosticsMap; use tokio::sync::mpsc; -use typst::utils::OptionExt; use crate::project::ProjectInsId; use crate::{tool::word_count::WordsCount, LspClient}; @@ -116,7 +115,8 @@ impl EditorActor { self.status.path = compile_status .compiling_id - .map_or_default(|fid| unix_slash(fid.vpath().as_rooted_path())); + .map(|fid| unix_slash(fid.vpath().as_rooted_path())) + .unwrap_or_default(); self.status.page_count = compile_status.page_count; self.status.status = match &compile_status.status { Compiling => CompileStatusEnum::Compiling, diff --git a/crates/typlite/src/main.rs b/crates/typlite/src/main.rs index ddad1aeb..2d8ca13f 100644 --- a/crates/typlite/src/main.rs +++ b/crates/typlite/src/main.rs @@ -81,10 +81,10 @@ fn run(args: CompileArgs, world: Arc) -> Result<()> { _ => Format::Md, }; - if let Some(assets_path) = args.assets_path.as_ref() { - if !assets_path.exists() { - std::fs::create_dir_all(assets_path).context("failed to create assets directory")?; - } + if let Some(assets_path) = args.assets_path.as_ref() + && !assets_path.exists() + { + std::fs::create_dir_all(assets_path).context("failed to create assets directory")?; } let doc = Typlite::new(world.clone()) diff --git a/crates/typlite/src/parser/list.rs b/crates/typlite/src/parser/list.rs index 76e38044..37c4e3f9 100644 --- a/crates/typlite/src/parser/list.rs +++ b/crates/typlite/src/parser/list.rs @@ -25,58 +25,57 @@ impl ListParser { let mut all_items = Vec::new(); for child in &element.children { - if let HtmlNode::Element(li) = child { - if li.tag == tag::li { - let attrs = ListItemAttr::parse(&li.attrs)?; - let mut item_content = Vec::new(); + if let HtmlNode::Element(li) = child + && li.tag == tag::li + { + let attrs = ListItemAttr::parse(&li.attrs)?; + let mut item_content = Vec::new(); - let mut li_buffer = Vec::new(); + let mut li_buffer = Vec::new(); - if parser.feat.annotate_elem { - li_buffer.push(Node::Custom(Box::new(super::core::Comment(eco_format!( - "typlite:begin:list-item {}", - parser.list_level - 1 - ))))); - } + if parser.feat.annotate_elem { + li_buffer.push(Node::Custom(Box::new(super::core::Comment(eco_format!( + "typlite:begin:list-item {}", + parser.list_level - 1 + ))))); + } - for li_child in &li.children { - match li_child { - HtmlNode::Text(text, _) => { - li_buffer.push(Node::Text(text.clone())); - } - HtmlNode::Element(child_elem) => { - let element_content = - parser.process_list_item_element(child_elem)?; - - if !element_content.is_empty() { - li_buffer.extend(element_content); - } - } - _ => {} + for li_child in &li.children { + match li_child { + HtmlNode::Text(text, _) => { + li_buffer.push(Node::Text(text.clone())); } - } + HtmlNode::Element(child_elem) => { + let element_content = parser.process_list_item_element(child_elem)?; - if parser.feat.annotate_elem { - li_buffer.push(Node::Custom(Box::new(super::core::Comment(eco_format!( - "typlite:end:list-item {}", - parser.list_level - 1 - ))))); - } - - if !li_buffer.is_empty() { - item_content.push(Node::Paragraph(li_buffer)); - } - if !item_content.is_empty() { - if is_ordered { - all_items.push(ListItem::Ordered { - number: attrs.value, - content: item_content, - }); - } else { - all_items.push(ListItem::Unordered { - content: item_content, - }); + if !element_content.is_empty() { + li_buffer.extend(element_content); + } } + _ => {} + } + } + + if parser.feat.annotate_elem { + li_buffer.push(Node::Custom(Box::new(super::core::Comment(eco_format!( + "typlite:end:list-item {}", + parser.list_level - 1 + ))))); + } + + if !li_buffer.is_empty() { + item_content.push(Node::Paragraph(li_buffer)); + } + if !item_content.is_empty() { + if is_ordered { + all_items.push(ListItem::Ordered { + number: attrs.value, + content: item_content, + }); + } else { + all_items.push(ListItem::Unordered { + content: item_content, + }); } } } diff --git a/crates/typlite/src/parser/table.rs b/crates/typlite/src/parser/table.rs index 153e8e5e..33df5d75 100644 --- a/crates/typlite/src/parser/table.rs +++ b/crates/typlite/src/parser/table.rs @@ -59,15 +59,15 @@ impl TableParser { fn find_table_in_grid(grid_element: &HtmlElement) -> Option<&HtmlElement> { for child in &grid_element.children { - if let HtmlNode::Element(table_elem) = child { - if table_elem.tag == md_tag::table { - // Find table tag within m1table - for inner_child in &table_elem.children { - if let HtmlNode::Element(inner) = inner_child { - if inner.tag == tag::table { - return Some(inner); - } - } + if let HtmlNode::Element(table_elem) = child + && table_elem.tag == md_tag::table + { + // Find table tag within m1table + for inner_child in &table_elem.children { + if let HtmlNode::Element(inner) = inner_child + && inner.tag == tag::table + { + return Some(inner); } } } @@ -77,10 +77,10 @@ impl TableParser { fn find_table_direct(element: &HtmlElement) -> Option<&HtmlElement> { for child in &element.children { - if let HtmlNode::Element(table_elem) = child { - if table_elem.tag == tag::table { - return Some(table_elem); - } + if let HtmlNode::Element(table_elem) = child + && table_elem.tag == tag::table + { + return Some(table_elem); } } None @@ -134,14 +134,14 @@ impl TableParser { is_header_section: bool, ) -> Result<()> { for row_node in §ion.children { - if let HtmlNode::Element(row_elem) = row_node { - if row_elem.tag == tag::tr { - let current_row = - Self::process_table_row(parser, row_elem, is_header_section, headers)?; + if let HtmlNode::Element(row_elem) = row_node + && row_elem.tag == tag::tr + { + let current_row = + Self::process_table_row(parser, row_elem, is_header_section, headers)?; - if !is_header_section && !current_row.is_empty() { - rows.push(current_row); - } + if !is_header_section && !current_row.is_empty() { + rows.push(current_row); } } } @@ -158,20 +158,20 @@ impl TableParser { // Process cells in this row for cell_node in &row_elem.children { - if let HtmlNode::Element(cell) = cell_node { - if cell.tag == tag::td || cell.tag == tag::th { - let mut cell_content = Vec::new(); - parser.convert_children_into(&mut cell_content, cell)?; + if let HtmlNode::Element(cell) = cell_node + && (cell.tag == tag::td || cell.tag == tag::th) + { + let mut cell_content = Vec::new(); + parser.convert_children_into(&mut cell_content, cell)?; - // Merge cell content into a single node - let merged_cell = Self::merge_cell_content(cell_content); + // Merge cell content into a single node + let merged_cell = Self::merge_cell_content(cell_content); - // Add to appropriate section - if is_header || cell.tag == tag::th { - headers.push(merged_cell); - } else { - current_row.push(merged_cell); - } + // Add to appropriate section + if is_header || cell.tag == tag::th { + headers.push(merged_cell); + } else { + current_row.push(merged_cell); } } } @@ -214,10 +214,11 @@ impl TableParser { fn check_section_for_complex_cells(section: &HtmlElement) -> bool { for row_node in §ion.children { - if let HtmlNode::Element(row_elem) = row_node { - if row_elem.tag == tag::tr && Self::check_row_for_complex_cells(row_elem) { - return true; - } + if let HtmlNode::Element(row_elem) = row_node + && row_elem.tag == tag::tr + && Self::check_row_for_complex_cells(row_elem) + { + return true; } } false @@ -225,15 +226,14 @@ impl TableParser { fn check_row_for_complex_cells(row_elem: &HtmlElement) -> bool { for cell_node in &row_elem.children { - if let HtmlNode::Element(cell) = cell_node { - if (cell.tag == tag::td || cell.tag == tag::th) - && cell.attrs.0.iter().any(|(name, _)| { - let name = name.into_inner(); - name == PicoStr::constant("colspan") || name == PicoStr::constant("rowspan") - }) - { - return true; - } + if let HtmlNode::Element(cell) = cell_node + && (cell.tag == tag::td || cell.tag == tag::th) + && cell.attrs.0.iter().any(|(name, _)| { + let name = name.into_inner(); + name == PicoStr::constant("colspan") || name == PicoStr::constant("rowspan") + }) + { + return true; } } false diff --git a/crates/typlite/src/writer/docx/writer.rs b/crates/typlite/src/writer/docx/writer.rs index a7e8ba84..3e911488 100644 --- a/crates/typlite/src/writer/docx/writer.rs +++ b/crates/typlite/src/writer/docx/writer.rs @@ -397,13 +397,13 @@ impl DocxWriter { block_type: _, } => { // Add language information - if let Some(lang) = language { - if !lang.is_empty() { - let lang_para = Paragraph::new() - .style("CodeBlock") - .add_run(Run::new().add_text(lang)); - docx = docx.add_paragraph(lang_para); - } + if let Some(lang) = language + && !lang.is_empty() + { + let lang_para = Paragraph::new() + .style("CodeBlock") + .add_run(Run::new().add_text(lang)); + docx = docx.add_paragraph(lang_para); } // Process code line by line, preserving line breaks diff --git a/crates/typlite/src/writer/text.rs b/crates/typlite/src/writer/text.rs index eb998286..76f45cef 100644 --- a/crates/typlite/src/writer/text.rs +++ b/crates/typlite/src/writer/text.rs @@ -155,10 +155,10 @@ impl TextWriter { } } node if node.is_custom_type::() => { - if let Some(external_frame) = node.as_custom_type::() { - if !external_frame.alt_text.is_empty() { - output.push_str(&external_frame.alt_text); - } + if let Some(external_frame) = node.as_custom_type::() + && !external_frame.alt_text.is_empty() + { + output.push_str(&external_frame.alt_text); } } node if node.is_custom_type::() => { diff --git a/crates/typst-preview/src/actor/render.rs b/crates/typst-preview/src/actor/render.rs index 6fe8ecee..a454a6bb 100644 --- a/crates/typst-preview/src/actor/render.rs +++ b/crates/typst-preview/src/actor/render.rs @@ -225,12 +225,11 @@ impl RenderActor { // order let range_res = { let mut range_res = range_res; - if let Some(info) = &mut range_res { - if let Some((x, y)) = info.start.zip(info.end) { - if y <= x { - std::mem::swap(&mut info.start, &mut info.end); - } - } + if let Some(info) = &mut range_res + && let Some((x, y)) = info.start.zip(info.end) + && y <= x + { + std::mem::swap(&mut info.start, &mut info.end); } range_res