Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ jobs:
toolchain: stable
override: true
- uses: Swatinem/rust-cache@v1
- name: Clippy
run: cargo clippy --all-features --all-targets -- -D warnings
- name: Format
run: cargo fmt -- --check
- name: Retrieve toml-test
run: |
wget https://github.com/BurntSushi/toml-test/releases/download/v1.1.0/toml-test-v1.1.0-linux-amd64.gz
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ target
.vscode/settings.json
.cargo/config.toml
yarn-error.log
/.idea
46 changes: 23 additions & 23 deletions crates/lsp-async-stub/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ use lsp_types::{
NumberOrString,
};
use serde::{de::DeserializeOwned, Serialize};
use std::cell::RefCell;
use std::rc::Rc;
use std::{
collections::HashMap,
io, mem,
Expand Down Expand Up @@ -49,7 +51,7 @@ impl Cancellation {
pub fn cancel(&mut self) {
self.cancelled.store(true, Ordering::SeqCst);

if let Some(w) = std::mem::replace(&mut *self.waker.lock().unwrap(), None) {
if let Some(w) = (*self.waker.lock().unwrap()).take() {
w.wake();
}
}
Expand Down Expand Up @@ -158,7 +160,7 @@ pub struct Context<W: Clone> {
inner: Arc<AsyncMutex<Inner<W>>>,
cancel_token: CancelToken,
last_req_id: Option<rpc::RequestId>, // For cancellation
rw: Arc<AsyncMutex<Box<dyn MessageWriter>>>,
rw: Rc<RefCell<dyn MessageWriter>>,
world: W,
deferred: DeferredTasks,
}
Expand Down Expand Up @@ -212,8 +214,6 @@ impl<W: Clone> RequestWriter for Context<W> {
let req_id = inner.next_request_id;
inner.next_request_id += 1;

let mut rw = self.rw.lock().await;

let id = NumberOrString::Number(req_id);

let request = rpc::Request::new()
Expand All @@ -222,8 +222,11 @@ impl<W: Clone> RequestWriter for Context<W> {
.with_params(params);

let span = tracing::debug_span!("sending request", ?request);

rw.send(request.into_message()).instrument(span).await?;
self.rw
.borrow_mut()
.send(request.into_message())
.instrument(span)
.await?;

self.last_req_id = Some(id.clone());

Expand All @@ -249,14 +252,15 @@ impl<W: Clone> RequestWriter for Context<W> {
&mut self,
params: Option<N::Params>,
) -> Result<(), io::Error> {
let mut rw = self.rw.lock().await;
rw.send(
rpc::Request::new()
.with_method(N::METHOD)
.with_params(params)
.into_message(),
)
.await
self.rw
.borrow_mut()
.send(
rpc::Request::new()
.with_method(N::METHOD)
.with_params(params)
.into_message(),
)
.await
}

async fn cancel(&mut self) -> Result<(), io::Error> {
Expand Down Expand Up @@ -424,7 +428,7 @@ impl<W: Clone> Server<W> {

let ctx = Server::create_context(
inner.clone(),
Arc::new(AsyncMutex::new(Box::new(writer.clone()))),
Rc::new(RefCell::new(writer.clone())),
data,
&request,
)
Expand Down Expand Up @@ -506,13 +510,9 @@ impl<W: Clone> Server<W> {
let mut handler = s.handlers.get_mut(&request.method).unwrap().clone();
drop(s);

let ctx = Server::create_context(
inner,
Arc::new(AsyncMutex::new(Box::new(writer))),
data,
&request,
)
.await;
let ctx =
Server::create_context(inner, Rc::new(RefCell::new(writer)), data, &request)
.await;

let handler_span = tracing::trace_span!(
"notification handler",
Expand Down Expand Up @@ -549,7 +549,7 @@ impl<W: Clone> Server<W> {

async fn create_context<D>(
inner: Arc<AsyncMutex<Inner<W>>>,
rw: Arc<AsyncMutex<Box<dyn MessageWriter>>>,
rw: Rc<RefCell<dyn MessageWriter>>,
world: W,
req: &rpc::Request<D>,
) -> Context<W> {
Expand Down
3 changes: 2 additions & 1 deletion crates/lsp-async-stub/src/listen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ impl<W: Clone + 'static> Server<W> {
} else {
Err(anyhow!("got exit message without shutdown notice"))
}
}).await?;
})
.await?;

Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion crates/taplo-cli/src/commands/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ impl<E: Environment> Taplo<E> {
async fn lint_file(&self, file: &Path) -> Result<(), anyhow::Error> {
let source = self.env.read_file(file).await?;
let source = String::from_utf8(source)?;
self.lint_source(&*file.to_string_lossy(), &source).await
self.lint_source(&file.to_string_lossy(), &source).await
}

async fn lint_source(&self, file_path: &str, source: &str) -> Result<(), anyhow::Error> {
Expand Down
2 changes: 2 additions & 0 deletions crates/taplo-common/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ pub struct Config {
pub plugins: Option<HashMap<String, Plugin>>,
}

#[allow(clippy::missing_fields_in_debug)]
impl Debug for Config {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Config")
Expand Down Expand Up @@ -316,6 +317,7 @@ pub struct Rule {
pub file_rule: Option<GlobRule>,
}

#[allow(clippy::missing_fields_in_debug)]
impl Debug for Rule {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Rule")
Expand Down
2 changes: 1 addition & 1 deletion crates/taplo-common/src/environment/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl Environment for NativeEnvironment {
type Stdout = tokio::io::Stdout;
type Stderr = tokio::io::Stderr;

fn now(&self) -> time::OffsetDateTime {
fn now(&self) -> OffsetDateTime {
OffsetDateTime::now_utc()
}

Expand Down
19 changes: 8 additions & 11 deletions crates/taplo-common/src/schema/associations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ impl<E: Environment> SchemaAssociations<E> {
self.retain(|(_, assoc)| assoc.meta["source"] != source::BUILTIN);

self.associations.write().push((
AssociationRule::Regex(Regex::new(r#".*\.?taplo\.toml$"#).unwrap()),
AssociationRule::Regex(Regex::new(r".*\.?taplo\.toml$").unwrap()),
SchemaAssociation {
url: builtins::TAPLO_CONFIG_URL.parse().unwrap(),
meta: json!({
Expand Down Expand Up @@ -193,7 +193,7 @@ impl<E: Environment> SchemaAssociations<E> {
tracing::debug!(%error, "invalid url in directive, assuming file path instead");

if self.env.is_absolute(Path::new(value)) {
match format!("file://{}", value).parse() {
match format!("file://{value}").parse() {
Ok(u) => u,
Err(error) => {
tracing::error!(%error, "invalid schema directive");
Expand Down Expand Up @@ -256,9 +256,8 @@ impl<E: Environment> SchemaAssociations<E> {

pub fn add_from_config(&self, config: &Config) {
for rule in &config.rule {
let file_rule = match rule.file_rule.clone() {
Some(rule) => rule,
None => continue,
let Some(file_rule) = rule.file_rule.clone() else {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit afraid this forces recent compiler version (and slightly a "breaking" change regarding MSRV). Does clippy really suggests to do this?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm yeah, this let-else was stabilised in 1.65 rust which would be breaking for old versions.

continue;
};

if let Some(schema_opts) = &rule.options.schema {
Expand All @@ -279,9 +278,8 @@ impl<E: Environment> SchemaAssociations<E> {
}
}

let file_rule = match config.file_rule.clone() {
Some(rule) => rule,
None => return,
let Some(file_rule) = config.file_rule.clone() else {
return;
};

if let Some(schema_opts) = &config.global_options.schema {
Expand Down Expand Up @@ -392,7 +390,7 @@ pub enum AssociationRule {

impl AssociationRule {
pub fn glob(pattern: &str) -> Result<Self, anyhow::Error> {
Ok(Self::Glob(GlobRule::new(&[pattern], &[] as &[&str])?))
Ok(Self::Glob(GlobRule::new([pattern], &[] as &[&str])?))
}

pub fn regex(regex: &str) -> Result<Self, anyhow::Error> {
Expand Down Expand Up @@ -520,8 +518,7 @@ impl<'de> Deserialize<'de> for SchemaStoreCatalogSchema {

if s != SCHEMA_STORE_CATALOG_SCHEMA_URL {
return Err(Error::custom(format!(
"expected $schema to be {}",
SCHEMA_STORE_CATALOG_SCHEMA_URL
"expected $schema to be {SCHEMA_STORE_CATALOG_SCHEMA_URL}"
)));
}

Expand Down
5 changes: 4 additions & 1 deletion crates/taplo-common/src/schema/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ impl<E: Environment> Cache<E> {
)))),
lru_expires_by: Arc::new(Mutex::new(env.now() + DEFAULT_LRU_CACHE_EXPIRATION_TIME)),
env,
schemas: Arc::new(Mutex::new(LruCache::with_hasher(10, ahash::RandomState::new()))),
schemas: Arc::new(Mutex::new(LruCache::with_hasher(
10,
ahash::RandomState::new(),
))),
cache_path: Default::default(),
}
}
Expand Down
11 changes: 5 additions & 6 deletions crates/taplo-common/src/schema/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,14 @@ pub struct ExtLinks {

#[must_use]
pub fn schema_ext_of(schema: &Value) -> Option<TaploSchemaExt> {
schema.get(EXTENSION_KEY).and_then(|val| {
if val.is_object() {
schema
.get(EXTENSION_KEY)
.filter(|v| v.is_object())
.and_then(|val| {
serde_json::from_value(val.clone())
.tap_err(
|error| tracing::warn!(key = EXTENSION_KEY, %error, "invalid schema extension"),
)
.ok()
} else {
None
}
})
})
}
15 changes: 6 additions & 9 deletions crates/taplo-common/src/schema/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl<E: Environment> Schemas<E> {
schema_url: &Url,
root: &dom::Node,
) -> Result<Vec<NodeValidationError>, anyhow::Error> {
let value = serde_json::to_value(&root)?;
let value = serde_json::to_value(root)?;
self.validate(schema_url, &value)
.await?
.into_iter()
Expand Down Expand Up @@ -368,14 +368,11 @@ impl<E: Environment> Schemas<E> {

let include_self = schema["allOf"].is_null();

let key = match path.iter().next() {
Some(k) => k,
None => {
if include_self {
schemas.push((full_path.clone(), Arc::new(schema.clone())));
}
return Ok(());
let Some(key) = path.iter().next() else {
if include_self {
schemas.push((full_path.clone(), Arc::new(schema.clone())));
}
return Ok(());
};

let child_path = path.skip_left(1);
Expand Down Expand Up @@ -474,7 +471,7 @@ impl<E: Environment> Schemas<E> {
for (path, schema) in schemas {
self.collect_child_schemas(
schema_url,
&*schema,
&schema,
&path,
&Keys::empty(),
max_depth,
Expand Down
7 changes: 3 additions & 4 deletions crates/taplo-common/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub struct ArcHashValue(pub Arc<Value>);

impl Hash for ArcHashValue {
fn hash<H: Hasher>(&self, state: &mut H) {
HashValue(&*self.0).hash(state);
HashValue(&self.0).hash(state);
}
}

Expand Down Expand Up @@ -109,9 +109,8 @@ impl Normalize for PathBuf {
}

pub(crate) fn normalize_str(s: &str) -> Cow<str> {
let percent_decoded = match percent_decode_str(s).decode_utf8().ok() {
Some(s) => s,
None => return s.into(),
let Some(percent_decoded) = percent_decode_str(s).decode_utf8().ok() else {
return s.into();
};

if cfg!(windows) {
Expand Down
42 changes: 15 additions & 27 deletions crates/taplo-lsp/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,12 @@ pub(crate) async fn publish_diagnostics<E: Environment>(
let mut diags = Vec::new();

let workspaces = context.workspaces.read().await;
let ws = match workspaces.get(&ws_url) {
Some(d) => d,
None => {
tracing::warn!(%document_url, "workspace not found");
return;
}
let Some(ws) = workspaces.get(&ws_url) else {
tracing::warn!(%document_url, "workspace not found");
return;
};
let doc = match ws.documents.get(&document_url) {
Some(doc) => doc,
None => return,
let Some(doc) = ws.documents.get(&document_url) else {
return;
};

collect_syntax_errors(doc, &mut diags);
Expand All @@ -46,16 +42,12 @@ pub(crate) async fn publish_diagnostics<E: Environment>(
}

let workspaces = context.workspaces.read().await;
let ws = match workspaces.get(&ws_url) {
Some(d) => d,
None => {
tracing::warn!(%document_url, "workspace not found");
return;
}
let Some(ws) = workspaces.get(&ws_url) else {
tracing::warn!(%document_url, "workspace not found");
return;
};
let doc = match ws.documents.get(&document_url) {
Some(doc) => doc,
None => return,
let Some(doc) = ws.documents.get(&document_url) else {
return;
};

let dom = doc.dom.clone();
Expand All @@ -77,16 +69,12 @@ pub(crate) async fn publish_diagnostics<E: Environment>(
}

let workspaces = context.workspaces.read().await;
let ws = match workspaces.get(&ws_url) {
Some(d) => d,
None => {
tracing::warn!(%document_url, "workspace not found");
return;
}
let Some(ws) = workspaces.get(&ws_url) else {
tracing::warn!(%document_url, "workspace not found");
return;
};
let doc = match ws.documents.get(&document_url) {
Some(doc) => doc,
None => return,
let Some(doc) = ws.documents.get(&document_url) else {
return;
};

collect_schema_errors(ws, doc, &dom, &document_url, &mut diags).await;
Expand Down
Loading