From 6c936b399fabbe4c8be98d29a91b76d727ff2bb9 Mon Sep 17 00:00:00 2001 From: John-John Tedro Date: Tue, 28 Nov 2023 10:21:31 +0100 Subject: [PATCH] Remove unecessary re-export (#657) * Remove unecessary re-export * Format everything --- crates/rune/src/cli.rs | 77 ++++--- crates/rune/src/cli/benches.rs | 6 +- crates/rune/src/cli/check.rs | 2 +- crates/rune/src/cli/doc.rs | 4 +- crates/rune/src/cli/format.rs | 37 ++-- crates/rune/src/cli/loader.rs | 2 +- crates/rune/src/cli/naming.rs | 14 +- crates/rune/src/cli/run.rs | 22 +- crates/rune/src/cli/tests.rs | 72 ++++--- crates/rune/src/cli/visitor.rs | 5 +- crates/rune/src/diagnostics/emit.rs | 104 +++++----- crates/rune/src/doc.rs | 2 +- crates/rune/src/doc/artifacts.rs | 16 +- crates/rune/src/doc/build.rs | 158 ++++++++++----- crates/rune/src/doc/build/enum_.rs | 7 +- crates/rune/src/doc/build/markdown.rs | 51 +++-- crates/rune/src/doc/build/type_.rs | 42 +++- crates/rune/src/doc/context.rs | 80 +++++--- crates/rune/src/doc/templating.rs | 26 ++- crates/rune/src/doc/visitor.rs | 43 ++-- crates/rune/src/workspace.rs | 6 +- crates/rune/src/workspace/build.rs | 13 +- crates/rune/src/workspace/diagnostics.rs | 18 +- crates/rune/src/workspace/emit.rs | 17 +- crates/rune/src/workspace/error.rs | 85 ++++---- crates/rune/src/workspace/glob.rs | 2 +- crates/rune/src/workspace/manifest.rs | 211 +++++++++++++------- crates/rune/src/workspace/source_loader.rs | 4 +- crates/rune/src/workspace/spanned_value.rs | 34 +++- crates/rune/tests/ui/install_with_compat.rs | 6 +- 30 files changed, 737 insertions(+), 429 deletions(-) diff --git a/crates/rune/src/cli.rs b/crates/rune/src/cli.rs index ae06d5ba6..cf4f0bc40 100644 --- a/crates/rune/src/cli.rs +++ b/crates/rune/src/cli.rs @@ -12,16 +12,16 @@ mod doc; mod format; mod languageserver; mod loader; +mod naming; mod run; mod tests; mod visitor; -mod naming; +use rust_alloc::string::String; +use rust_alloc::vec::Vec; use std::fmt; use std::io::{self, Write}; use std::path::{Path, PathBuf}; -use rust_alloc::string::String; -use rust_alloc::vec::Vec; use crate::alloc; use crate::alloc::prelude::*; @@ -34,7 +34,7 @@ use tracing_subscriber::filter::EnvFilter; use crate::compile::{ItemBuf, ParseOptionError}; use crate::modules::capture_io::CaptureIo; use crate::termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; -use crate::{Context, ContextError, Options, Hash}; +use crate::{Context, ContextError, Hash, Options}; /// Default about splash. const DEFAULT_ABOUT: &str = "The Rune Language Interpreter"; @@ -83,7 +83,11 @@ impl<'a> Entry<'a> { /// .run(); ///``` pub fn about(mut self, about: impl fmt::Display) -> Self { - self.about = Some(about.try_to_string().expect("Failed to format about string")); + self.about = Some( + about + .try_to_string() + .expect("Failed to format about string"), + ); self } @@ -266,7 +270,10 @@ where command: T, } -impl CommandShared where T: CommandBase + clap::Args { +impl CommandShared +where + T: CommandBase + clap::Args, +{ /// Construct compiler options from arguments. fn options(&self) -> Result { let mut options = Options::default(); @@ -379,8 +386,7 @@ trait CommandBase { /// Propagate related flags from command and config. #[inline] - fn propagate(&mut self, _: &mut Config, _: &mut SharedFlags) { - } + fn propagate(&mut self, _: &mut Config, _: &mut SharedFlags) {} } #[derive(Subcommand, Debug)] @@ -442,10 +448,7 @@ impl Command { Command::Hash(..) => return None, }; - Some(CommandSharedRef { - shared, - command, - }) + Some(CommandSharedRef { shared, command }) } } @@ -488,25 +491,25 @@ impl Config { build_paths.try_push(BuildPath::Package(p))?; } } - + if let Some(test) = cmd.find_tests() { for p in self.manifest.find_tests(test)? { build_paths.try_push(BuildPath::Package(p))?; } } - + if let Some(example) = cmd.find_examples() { for p in self.manifest.find_examples(example)? { build_paths.try_push(BuildPath::Package(p))?; } } - + if let Some(bench) = cmd.find_benches() { for p in self.manifest.find_benches(bench)? { build_paths.try_push(BuildPath::Package(p))?; } } - + Ok(build_paths) } } @@ -525,7 +528,11 @@ impl SharedFlags { test: c.test, }; - let mut context = entry.context.as_mut().context("Context builder not configured with Entry::context")?(opts)?; + let mut context = + entry + .context + .as_mut() + .context("Context builder not configured with Entry::context")?(opts)?; if let Some(capture) = capture { context.install(crate::modules::capture_io::module(capture)?)?; @@ -681,12 +688,8 @@ fn find_manifest() -> Option<(PathBuf, PathBuf)> { } fn populate_config(io: &mut Io<'_>, c: &mut Config, cmd: CommandSharedRef<'_>) -> Result<()> { - c.found_paths.try_extend( - cmd.shared - .paths - .iter() - .map(|p| p.as_path().into()), - )?; + c.found_paths + .try_extend(cmd.shared.paths.iter().map(|p| p.as_path().into()))?; if !c.found_paths.is_empty() && !cmd.shared.workspace { return Ok(()); @@ -744,18 +747,18 @@ async fn main_with_out(io: &mut Io<'_>, entry: &mut Entry<'_>, mut args: Args) - return Ok(ExitCode::Failure); } }; - + let mut entrys = alloc::Vec::new(); if let Some(cmd) = cmd.as_command_shared_ref() { populate_config(io, &mut c, cmd)?; let build_paths = c.build_paths(cmd)?; - + let what = cmd.command.describe(); let verbose = c.verbose; let recursive = cmd.shared.recursive; - + for build_path in build_paths { match build_path { BuildPath::Path(path) => { @@ -771,9 +774,15 @@ async fn main_with_out(io: &mut Io<'_>, entry: &mut Entry<'_>, mut args: Args) - o.set_color(&ColorSpec::new())?; o.flush()?; result?; - writeln!(o, " {} `{}` (from {})", p.found.kind, p.found.path.display(), p.package.name)?; + writeln!( + o, + " {} `{}` (from {})", + p.found.kind, + p.found.path.display(), + p.package.name + )?; } - + entrys.try_push(EntryPoint::Package(p))?; } } @@ -823,17 +832,7 @@ where Command::Test(f) => { let options = f.options()?; - match tests::run( - io, - c, - &f.command, - &f.shared, - &options, - entry, - entries, - ) - .await? - { + match tests::run(io, c, &f.command, &f.shared, &options, entry, entries).await? { ExitCode::Success => (), other => return Ok(other), } diff --git a/crates/rune/src/cli/benches.rs b/crates/rune/src/cli/benches.rs index b53cc61e6..5b770aba3 100644 --- a/crates/rune/src/cli/benches.rs +++ b/crates/rune/src/cli/benches.rs @@ -6,13 +6,13 @@ use std::time::Instant; use clap::Parser; use crate::alloc::Vec; -use crate::cli::{ExitCode, Io, CommandBase, AssetKind, Config, SharedFlags}; +use crate::cli::{AssetKind, CommandBase, Config, ExitCode, Io, SharedFlags}; use crate::compile::{Item, ItemBuf}; use crate::modules::capture_io::CaptureIo; -use crate::runtime::{Function, Unit, Value}; -use crate::{Context, Hash, Sources, Vm}; use crate::modules::test::Bencher; +use crate::runtime::{Function, Unit, Value}; use crate::support::Result; +use crate::{Context, Hash, Sources, Vm}; #[derive(Parser, Debug)] pub(super) struct Flags { diff --git a/crates/rune/src/cli/check.rs b/crates/rune/src/cli/check.rs index fe2d55676..3a7feeb49 100644 --- a/crates/rune/src/cli/check.rs +++ b/crates/rune/src/cli/check.rs @@ -4,7 +4,7 @@ use std::path::Path; use anyhow::{Context, Result}; use clap::Parser; -use crate::cli::{visitor, Config, Entry, ExitCode, Io, SharedFlags, CommandBase, AssetKind}; +use crate::cli::{visitor, AssetKind, CommandBase, Config, Entry, ExitCode, Io, SharedFlags}; use crate::compile::FileSourceLoader; use crate::{Diagnostics, Options, Source, Sources}; diff --git a/crates/rune/src/cli/doc.rs b/crates/rune/src/cli/doc.rs index eda31f509..0e400a70d 100644 --- a/crates/rune/src/cli/doc.rs +++ b/crates/rune/src/cli/doc.rs @@ -6,10 +6,10 @@ use crate::doc::Artifacts; use anyhow::{Context, Result}; use clap::Parser; -use crate::alloc::Vec; use crate::alloc::prelude::*; -use crate::cli::{Config, Entry, EntryPoint, ExitCode, Io, SharedFlags, CommandBase, AssetKind}; +use crate::alloc::Vec; use crate::cli::naming::Naming; +use crate::cli::{AssetKind, CommandBase, Config, Entry, EntryPoint, ExitCode, Io, SharedFlags}; use crate::compile::{FileSourceLoader, ItemBuf}; use crate::{Diagnostics, Options, Source, Sources}; diff --git a/crates/rune/src/cli/format.rs b/crates/rune/src/cli/format.rs index 6e7b38ac8..266c5f1da 100644 --- a/crates/rune/src/cli/format.rs +++ b/crates/rune/src/cli/format.rs @@ -5,12 +5,12 @@ use std::io::Write; use clap::Parser; use similar::{ChangeTag, TextDiff}; -use crate::support::{Context, Result}; -use crate::alloc::BTreeSet; use crate::alloc::prelude::*; -use crate::cli::{Entry, ExitCode, Io, EntryPoint, SharedFlags, Config, CommandBase, AssetKind}; -use crate::termcolor::{WriteColor, ColorSpec, Color}; -use crate::{Source, Sources, Options, Diagnostics}; +use crate::alloc::BTreeSet; +use crate::cli::{AssetKind, CommandBase, Config, Entry, EntryPoint, ExitCode, Io, SharedFlags}; +use crate::support::{Context, Result}; +use crate::termcolor::{Color, ColorSpec, WriteColor}; +use crate::{Diagnostics, Options, Source, Sources}; #[derive(Parser, Debug)] pub(super) struct Flags { @@ -35,7 +35,18 @@ impl CommandBase for Flags { } } -pub(super) fn run<'m, I>(io: &mut Io<'_>, entry: &mut Entry<'_>, c: &Config, entrys: I, flags: &Flags, shared: &SharedFlags, options: &Options) -> Result where I: IntoIterator> { +pub(super) fn run<'m, I>( + io: &mut Io<'_>, + entry: &mut Entry<'_>, + c: &Config, + entrys: I, + flags: &Flags, + shared: &SharedFlags, + options: &Options, +) -> Result +where + I: IntoIterator>, +{ let col = Colors::new(); let mut changed = 0; @@ -192,18 +203,18 @@ fn diff(io: &mut Io, source: &Source, val: &[u8], col: &Colors) -> Result<(), an ChangeTag::Insert => ("+", &col.green), ChangeTag::Equal => (" ", &col.dim), }; - + io.stdout.set_color(color)?; - - write!(io.stdout,"{}", Line(change.old_index()))?; - write!(io.stdout,"{sign}")?; - + + write!(io.stdout, "{}", Line(change.old_index()))?; + write!(io.stdout, "{sign}")?; + for (_, value) in change.iter_strings_lossy() { write!(io.stdout, "{value}")?; } - + io.stdout.reset()?; - + if change.missing_newline() { writeln!(io.stdout)?; } diff --git a/crates/rune/src/cli/loader.rs b/crates/rune/src/cli/loader.rs index d475e165f..004613f80 100644 --- a/crates/rune/src/cli/loader.rs +++ b/crates/rune/src/cli/loader.rs @@ -6,7 +6,7 @@ use std::{path::Path, sync::Arc}; use anyhow::{anyhow, Context as _, Result}; -use crate::alloc::{VecDeque, Vec}; +use crate::alloc::{Vec, VecDeque}; use crate::cli::{visitor, Io, SharedFlags}; use crate::compile::{FileSourceLoader, ItemBuf}; use crate::Diagnostics; diff --git a/crates/rune/src/cli/naming.rs b/crates/rune/src/cli/naming.rs index 09999f7d5..94c9327bf 100644 --- a/crates/rune/src/cli/naming.rs +++ b/crates/rune/src/cli/naming.rs @@ -2,8 +2,8 @@ use core::mem::replace; use std::ffi::OsStr; -use crate::alloc::{self, try_format, String, HashSet}; use crate::alloc::prelude::*; +use crate::alloc::{self, try_format, HashSet, String}; use crate::cli::EntryPoint; use crate::workspace; @@ -18,12 +18,10 @@ impl Naming { /// Construct a unique crate name for the given entrypoint. pub(crate) fn name(&mut self, e: &EntryPoint<'_>) -> alloc::Result { let name = match &e { - EntryPoint::Path(path) => { - match path.file_stem().and_then(OsStr::to_str) { - Some(name) => String::try_from(name)?, - None => String::try_from("entry")?, - } - } + EntryPoint::Path(path) => match path.file_stem().and_then(OsStr::to_str) { + Some(name) => String::try_from(name)?, + None => String::try_from("entry")?, + }, EntryPoint::Package(p) => { let name = p.found.name.as_str(); @@ -35,7 +33,7 @@ impl Naming { }; try_format!("{}-{name}-{ext}", p.package.name) - }, + } }; // TODO: make it so that we can communicate different entrypoints in the diff --git a/crates/rune/src/cli/run.rs b/crates/rune/src/cli/run.rs index e7704fbbe..454ac3e13 100644 --- a/crates/rune/src/cli/run.rs +++ b/crates/rune/src/cli/run.rs @@ -5,8 +5,8 @@ use std::time::Instant; use anyhow::{anyhow, Result}; use clap::Parser; -use crate::cli::{Config, ExitCode, Io, CommandBase, AssetKind, SharedFlags}; -use crate::runtime::{VmError, VmExecution, VmResult, UnitStorage}; +use crate::cli::{AssetKind, CommandBase, Config, ExitCode, Io, SharedFlags}; +use crate::runtime::{UnitStorage, VmError, VmExecution, VmResult}; use crate::{Context, Sources, Unit, Value, Vm}; #[derive(Parser, Debug)] @@ -145,7 +145,11 @@ pub(super) async fn run( } if args.dump_unit() { - writeln!(io.stdout, "Unit size: {} bytes", unit.instructions().bytes())?; + writeln!( + io.stdout, + "Unit size: {} bytes", + unit.instructions().bytes() + )?; if args.emit_instructions() { let mut o = io.stdout.lock(); @@ -328,8 +332,10 @@ where let vm = execution.vm(); let mut o = io.stdout.lock(); - if let Some((hash, signature)) = - vm.unit().debug_info().and_then(|d| d.function_at(vm.last_ip())) + if let Some((hash, signature)) = vm + .unit() + .debug_info() + .and_then(|d| d.function_at(vm.last_ip())) { writeln!(o, "fn {} ({}):", signature, hash)?; } @@ -350,7 +356,11 @@ where writeln!(o, "{}:", label)?; } - if let Some((inst, _)) = vm.unit().instruction_at(vm.last_ip()).map_err(VmError::from)? { + if let Some((inst, _)) = vm + .unit() + .instruction_at(vm.last_ip()) + .map_err(VmError::from)? + { write!(o, " {:04} = {}", vm.last_ip(), inst)?; } else { write!(o, " {:04} = *out of bounds*", vm.last_ip())?; diff --git a/crates/rune/src/cli/tests.rs b/crates/rune/src/cli/tests.rs index 626613611..484a264fa 100644 --- a/crates/rune/src/cli/tests.rs +++ b/crates/rune/src/cli/tests.rs @@ -2,24 +2,26 @@ use std::io::Write; use std::sync::Arc; use std::time::Instant; -use anyhow::{bail, Result, Context}; +use anyhow::{bail, Context, Result}; use crate::alloc::prelude::*; use crate::alloc::Vec; -use crate::cli::{ExitCode, Io, CommandBase, AssetKind, Config, SharedFlags, EntryPoint, Entry, Options}; -use crate::cli::visitor; use crate::cli::naming::Naming; -use crate::compile::{ItemBuf, FileSourceLoader}; -use crate::modules::capture_io::CaptureIo; -use crate::runtime::{Value, Vm, VmError, VmResult, UnitFn}; +use crate::cli::visitor; +use crate::cli::{ + AssetKind, CommandBase, Config, Entry, EntryPoint, ExitCode, Io, Options, SharedFlags, +}; +use crate::compile::{FileSourceLoader, ItemBuf}; use crate::doc::TestParams; -use crate::{Hash, Sources, Unit, Diagnostics, Source}; -use crate::termcolor::{WriteColor, ColorSpec, Color}; +use crate::modules::capture_io::CaptureIo; +use crate::runtime::{UnitFn, Value, Vm, VmError, VmResult}; +use crate::termcolor::{Color, ColorSpec, WriteColor}; +use crate::{Diagnostics, Hash, Source, Sources, Unit}; mod cli { - use clap::Parser; - use ::rust_alloc::vec::Vec; use ::rust_alloc::string::String; + use ::rust_alloc::vec::Vec; + use clap::Parser; #[derive(Parser, Debug, Clone)] pub struct Flags { @@ -147,7 +149,13 @@ where doc_visitors.try_push(doc_visitor)?; for (hash, item) in functions.into_functions() { - cases.try_push(TestCase::new(hash, item, unit.clone(), sources.clone(), TestParams::default()))?; + cases.try_push(TestCase::new( + hash, + item, + unit.clone(), + sources.clone(), + TestParams::default(), + ))?; } } @@ -193,11 +201,26 @@ where let unit = Arc::new(unit?); let sources = Arc::new(sources); - let Some((hash, _)) = unit.iter_functions().find(|(_, f)| matches!(f, UnitFn::Offset { args: 0, offset: 0, .. })) else { + let Some((hash, _)) = unit.iter_functions().find(|(_, f)| { + matches!( + f, + UnitFn::Offset { + args: 0, + offset: 0, + .. + } + ) + }) else { bail!("Compiling source did not result in a function at offset 0"); }; - cases.try_push(TestCase::new(hash, test.item.try_clone()?, unit.clone(), sources.clone(), test.params))?; + cases.try_push(TestCase::new( + hash, + test.item.try_clone()?, + unit.clone(), + sources.clone(), + test.params, + ))?; } } @@ -288,7 +311,13 @@ struct TestCase { } impl TestCase { - fn new(hash: Hash, item: ItemBuf, unit: Arc, sources: Arc, params: TestParams) -> Self { + fn new( + hash: Hash, + item: ItemBuf, + unit: Arc, + sources: Arc, + params: TestParams, + ) -> Self { Self { hash, item, @@ -300,11 +329,7 @@ impl TestCase { } } - async fn execute( - &mut self, - vm: &mut Vm, - capture_io: &CaptureIo, - ) -> Result<()> { + async fn execute(&mut self, vm: &mut Vm, capture_io: &CaptureIo) -> Result<()> { let result = match vm.execute(self.hash, ()) { Ok(mut execution) => execution.async_complete().await, Err(err) => VmResult::Err(err), @@ -324,9 +349,7 @@ impl TestCase { }, _ => Outcome::Ok, }, - VmResult::Err(e) => { - Outcome::Panic(e) - } + VmResult::Err(e) => Outcome::Panic(e), }; if self.params.should_panic { @@ -353,7 +376,10 @@ impl TestCase { } Outcome::ExpectedPanic => { io.stdout.set_color(&colors.error)?; - writeln!(io.stdout, "expected panic because of `should_panic`, but ran without issue")?; + writeln!( + io.stdout, + "expected panic because of `should_panic`, but ran without issue" + )?; io.stdout.reset()?; } Outcome::Err(error) => { diff --git a/crates/rune/src/cli/visitor.rs b/crates/rune/src/cli/visitor.rs index 58ed6ee38..238ea15ec 100644 --- a/crates/rune/src/cli/visitor.rs +++ b/crates/rune/src/cli/visitor.rs @@ -1,7 +1,7 @@ use crate::alloc::prelude::*; use crate::alloc::Vec; use crate::compile::meta; -use crate::compile::{MetaError, CompileVisitor, ItemBuf, MetaRef}; +use crate::compile::{CompileVisitor, ItemBuf, MetaError, MetaRef}; use crate::Hash; /// Attribute to collect. @@ -43,7 +43,8 @@ impl CompileVisitor for FunctionVisitor { _ => return Ok(()), }; - self.functions.try_push((type_hash, meta.item.try_to_owned()?))?; + self.functions + .try_push((type_hash, meta.item.try_to_owned()?))?; Ok(()) } } diff --git a/crates/rune/src/diagnostics/emit.rs b/crates/rune/src/diagnostics/emit.rs index f7d2504e9..75a6fcd6d 100644 --- a/crates/rune/src/diagnostics/emit.rs +++ b/crates/rune/src/diagnostics/emit.rs @@ -9,17 +9,17 @@ use codespan_reporting::term; pub use codespan_reporting::term::termcolor; use codespan_reporting::term::termcolor::WriteColor; -use crate::alloc::{self, String}; use crate::alloc::fmt::TryWrite; use crate::alloc::prelude::*; -use crate::compile::{ErrorKind, Location, LinkerError}; +use crate::alloc::{self, String}; +use crate::ast::{Span, Spanned}; +use crate::compile::{ErrorKind, LinkerError, Location}; use crate::diagnostics::{ Diagnostic, FatalDiagnostic, FatalDiagnosticKind, WarningDiagnostic, WarningDiagnosticKind, }; -use crate::runtime::{Unit, VmErrorKind, VmError, DebugInst, VmErrorAt, Protocol}; -use crate::{Source, Diagnostics, SourceId, Sources}; -use crate::ast::{Span, Spanned}; use crate::hash::Hash; +use crate::runtime::{DebugInst, Protocol, Unit, VmError, VmErrorAt, VmErrorKind}; +use crate::{Diagnostics, Source, SourceId, Sources}; struct StackFrame { source_id: SourceId, @@ -84,11 +84,7 @@ impl Diagnostics { /// hints. /// /// See [prepare][crate::prepare] for how to use. - pub fn emit( - &self, - out: &mut O, - sources: &Sources, - ) -> Result<(), EmitError> + pub fn emit(&self, out: &mut O, sources: &Sources) -> Result<(), EmitError> where O: WriteColor, { @@ -118,11 +114,7 @@ impl VmError { /// hints. /// /// See [prepare][crate::prepare] for how to use. - pub fn emit( - &self, - out: &mut O, - sources: &Sources, - ) -> Result<(), EmitError> + pub fn emit(&self, out: &mut O, sources: &Sources) -> Result<(), EmitError> where O: WriteColor, { @@ -138,7 +130,10 @@ impl VmError { None => continue, }; - for ip in [l.ip].into_iter().chain(l.frames.iter().rev().map(|v| v.ip)) { + for ip in [l.ip] + .into_iter() + .chain(l.frames.iter().rev().map(|v| v.ip)) + { let debug_inst = match debug_info.instruction_at(ip) { Some(debug_inst) => debug_inst, None => continue, @@ -185,15 +180,20 @@ impl VmError { _ => {} }; - if let Some(&DebugInst { source_id, span, .. }) = get(at) { + if let Some(&DebugInst { + source_id, span, .. + }) = get(at) + { labels.push( - d::Label::primary(source_id, span.range()) - .with_message(at.try_to_string()?), + d::Label::primary(source_id, span.range()).with_message(at.try_to_string()?), ); } } - if let Some(&DebugInst { source_id, span, .. }) = get(&self.inner.error) { + if let Some(&DebugInst { + source_id, span, .. + }) = get(&self.inner.error) + { labels.push( d::Label::primary(source_id, span.range()) .with_message(self.inner.error.try_to_string()?), @@ -209,14 +209,18 @@ impl VmError { // the values together with an associated function seed. But // this is not guaranteed to work everywhere. - if let Some(&DebugInst { source_id, span, .. }) = get(at) { + if let Some(&DebugInst { + source_id, span, .. + }) = get(at) + { let instance_hash = Hash::associated_function(instance.type_hash(), *hash); if let Some(ident) = get_ident(at, instance_hash) { - labels.push( - d::Label::secondary(source_id, span.range()) - .with_message(format!("This corresponds to the `{instance}::{ident}` instance function")), - ); + labels.push(d::Label::secondary(source_id, span.range()).with_message( + format!( + "This corresponds to the `{instance}::{ident}` instance function" + ), + )); } if let Some(protocol) = Protocol::from_hash(instance_hash) { @@ -229,7 +233,8 @@ impl VmError { }; } - let diagnostic = d::Diagnostic::error().with_message(self.inner.error.try_to_string()?) + let diagnostic = d::Diagnostic::error() + .with_message(self.inner.error.try_to_string()?) .with_labels(labels) .with_notes(notes); @@ -244,11 +249,9 @@ impl VmError { }; let (line, line_count, [prefix, mid, suffix]) = match source.line(frame.span) { - Some((line, line_count, text)) => ( - line.saturating_add(1), - line_count.saturating_add(1), - text, - ), + Some((line, line_count, text)) => { + (line.saturating_add(1), line_count.saturating_add(1), text) + } None => continue, }; @@ -257,7 +260,11 @@ impl VmError { out.set_color(&red)?; write!(out, "{mid}")?; out.reset()?; - writeln!(out, "{}", suffix.trim_end_matches(|c| matches!(c, '\n' | '\r')))?; + writeln!( + out, + "{}", + suffix.trim_end_matches(|c| matches!(c, '\n' | '\r')) + )?; } } @@ -270,11 +277,7 @@ impl FatalDiagnostic { /// hints. /// /// See [prepare][crate::prepare] for how to use. - pub fn emit( - &self, - out: &mut O, - sources: &Sources, - ) -> Result<(), EmitError> + pub fn emit(&self, out: &mut O, sources: &Sources) -> Result<(), EmitError> where O: WriteColor, { @@ -412,7 +415,10 @@ where let mut notes = ::rust_alloc::vec::Vec::new(); let mut labels = ::rust_alloc::vec::Vec::new(); - labels.push(d::Label::primary(this.source_id(), this.span().range()).with_message(this.try_to_string()?)); + labels.push( + d::Label::primary(this.source_id(), this.span().range()) + .with_message(this.try_to_string()?), + ); match this.kind() { WarningDiagnosticKind::LetPatternMightPanic { span, .. } => { @@ -425,10 +431,7 @@ where notes.push(note.into_std()); } } - WarningDiagnosticKind::RemoveTupleCallParams { - variant, - .. - } => { + WarningDiagnosticKind::RemoveTupleCallParams { variant, .. } => { if let Some(variant) = sources.source(this.source_id(), *variant) { let mut note = String::new(); writeln!(note, "Hint: Rewrite to `{}`", variant)?; @@ -467,7 +470,10 @@ where let mut notes = ::rust_alloc::vec::Vec::new(); if let Some(span) = this.span() { - labels.push(d::Label::primary(this.source_id(), span.range()).with_message(this.kind().try_to_string()?)); + labels.push( + d::Label::primary(this.source_id(), span.range()) + .with_message(this.kind().try_to_string()?), + ); } match this.kind() { @@ -648,11 +654,7 @@ where ); } ErrorKind::PatternMissingFields { fields, .. } => { - let pl = if fields.len() == 1 { - "field" - } else { - "fields" - }; + let pl = if fields.len() == 1 { "field" } else { "fields" }; let fields = fields.join(", "); @@ -661,7 +663,11 @@ where .with_message(format!("Missing {}: {}", pl, fields)), ); - notes.push("You can also make the pattern non-exhaustive by adding `..`".try_to_string()?.into_std()); + notes.push( + "You can also make the pattern non-exhaustive by adding `..`" + .try_to_string()? + .into_std(), + ); } _ => (), } diff --git a/crates/rune/src/doc.rs b/crates/rune/src/doc.rs index b80a62738..6a0463c6b 100644 --- a/crates/rune/src/doc.rs +++ b/crates/rune/src/doc.rs @@ -4,7 +4,7 @@ mod context; use self::context::Context; mod artifacts; -pub(crate) use self::artifacts::{TestParams, Artifacts}; +pub(crate) use self::artifacts::{Artifacts, TestParams}; mod templating; diff --git a/crates/rune/src/doc/artifacts.rs b/crates/rune/src/doc/artifacts.rs index 5914d17fd..82ee451cc 100644 --- a/crates/rune/src/doc/artifacts.rs +++ b/crates/rune/src/doc/artifacts.rs @@ -1,20 +1,20 @@ use rust_alloc::string::ToString; -use std::io; use std::fs; +use std::io; use rust_alloc::borrow::ToOwned; use std::path::Path; use crate::alloc::borrow::Cow; -use crate::compile::ItemBuf; use crate::alloc::{String, Vec}; +use crate::compile::ItemBuf; +use anyhow::{Context as _, Error, Result}; use base64::display::Base64Display; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use relative_path::{RelativePath, RelativePathBuf}; -use sha2::{Sha256, Digest}; -use anyhow::{Context as _, Error, Result}; +use sha2::{Digest, Sha256}; /// Test parameters. #[derive(Debug, Default, Clone, Copy)] @@ -90,9 +90,13 @@ impl Artifacts { hash: bool, path: &P, content: F, - ) -> Result where P: ?Sized + AsRef, F: FnOnce() -> Result> { + ) -> Result + where + P: ?Sized + AsRef, + F: FnOnce() -> Result>, + { if !self.enabled { - return Ok(path.as_ref().to_owned()) + return Ok(path.as_ref().to_owned()); } let content = content().context("Building asset content")?; diff --git a/crates/rune/src/doc/build.rs b/crates/rune/src/doc/build.rs index 00f72447c..f3e00d69b 100644 --- a/crates/rune/src/doc/build.rs +++ b/crates/rune/src/doc/build.rs @@ -1,7 +1,7 @@ mod enum_; -mod type_; -mod markdown; mod js; +mod markdown; +mod type_; use core::fmt; use core::str; @@ -16,18 +16,18 @@ use syntect::html::{self, ClassStyle, ClassedHTMLGenerator}; use syntect::parsing::{SyntaxReference, SyntaxSet}; use crate as rune; -use crate::std; -use crate::std::borrow::ToOwned; -use crate::alloc::{self, String, VecDeque, Vec}; -use crate::alloc::prelude::*; -use crate::alloc::fmt::TryWrite; use crate::alloc::borrow::Cow; +use crate::alloc::fmt::TryWrite; +use crate::alloc::prelude::*; use crate::alloc::try_format; +use crate::alloc::{self, String, Vec, VecDeque}; use crate::compile::{ComponentRef, Item, ItemBuf}; -use crate::doc::context::{Function, Kind, Signature, Meta}; -use crate::doc::templating; use crate::doc::artifacts::Test; -use crate::doc::{Context, Visitor, Artifacts}; +use crate::doc::context::{Function, Kind, Meta, Signature}; +use crate::doc::templating; +use crate::doc::{Artifacts, Context, Visitor}; +use crate::std; +use crate::std::borrow::ToOwned; use crate::Hash; // InspiredGitHub @@ -46,7 +46,10 @@ pub(crate) struct Builder<'m> { } impl<'m> Builder<'m> { - fn new(cx: &Ctxt<'_, '_>, builder: B) -> alloc::Result where B: FnOnce(&Ctxt<'_, '_>) -> Result + 'm { + fn new(cx: &Ctxt<'_, '_>, builder: B) -> alloc::Result + where + B: FnOnce(&Ctxt<'_, '_>) -> Result + 'm, + { Ok(Self { state: cx.state.try_clone()?, builder: rust_alloc::boxed::Box::new(builder), @@ -55,8 +58,8 @@ impl<'m> Builder<'m> { } mod embed { - use rust_alloc::string::String; use rust_alloc::boxed::Box; + use rust_alloc::string::String; use rust_embed::RustEmbed; @@ -76,9 +79,7 @@ pub(crate) fn build( let paths = templating::Paths::default(); - let partials = [ - ("layout", asset_str("layout.html.hbs")?), - ]; + let partials = [("layout", asset_str("layout.html.hbs")?)]; let templating = templating::Templating::new(partials, paths.clone())?; @@ -109,7 +110,10 @@ pub(crate) fn build( let theme = theme_set.themes.get(THEME).context("missing theme")?; let syntax_css = artifacts.asset(true, "syntax.css", || { - let content = String::try_from(html::css_for_theme_with_class_style(theme, html::ClassStyle::Spaced)?)?; + let content = String::try_from(html::css_for_theme_with_class_style( + theme, + html::ClassStyle::Spaced, + )?)?; Ok(content.into_bytes().into()) })?; @@ -130,7 +134,11 @@ pub(crate) fn build( for item in context.iter_modules() { let item = item?; - let meta = context.meta(&item)?.into_iter().find(|m| matches!(&m.kind, Kind::Module)).with_context(|| anyhow!("Missing meta for {item}"))?; + let meta = context + .meta(&item)? + .into_iter() + .find(|m| matches!(&m.kind, Kind::Module)) + .with_context(|| anyhow!("Missing meta for {item}"))?; initial.try_push_back(Build::Module(meta))?; } @@ -209,7 +217,9 @@ pub(crate) fn build( for builder in builders { cx.state = builder.state; - artifacts.asset(false, &cx.state.path, || Ok((builder.builder)(&cx)?.into_bytes().try_into()?))?; + artifacts.asset(false, &cx.state.path, || { + Ok((builder.builder)(&cx)?.into_bytes().try_into()?) + })?; } artifacts.set_tests(cx.tests); @@ -221,7 +231,13 @@ fn build_search_index(cx: &Ctxt) -> Result { write!(s, "window.INDEX = [")?; let mut it = cx.index.iter(); - while let Some(IndexEntry { path, item, kind, doc }) = it.next() { + while let Some(IndexEntry { + path, + item, + kind, + doc, + }) = it.next() + { write!(s, "[\"{path}\",\"{item}\",\"{kind}\",\"")?; if let Some(doc) = doc { @@ -376,7 +392,10 @@ impl<'m> Ctxt<'_, 'm> { I: IntoIterator, I::Item: AsRef, { - let syntax = match self.syntax_set.find_syntax_by_token(self::markdown::RUST_TOKEN) { + let syntax = match self + .syntax_set + .find_syntax_by_token(self::markdown::RUST_TOKEN) + { Some(syntax) => syntax, None => self.syntax_set.find_syntax_plain_text(), }; @@ -396,11 +415,16 @@ impl<'m> Ctxt<'_, 'm> { } /// Render documentation. - fn render_docs(&mut self, meta: Meta<'_>, docs: &[S], capture_tests: bool) -> Result> + fn render_docs( + &mut self, + meta: Meta<'_>, + docs: &[S], + capture_tests: bool, + ) -> Result> where S: AsRef, { - use pulldown_cmark::{Options, Parser, BrokenLink}; + use pulldown_cmark::{BrokenLink, Options, Parser}; if docs.is_empty() { return Ok(None); @@ -438,7 +462,12 @@ impl<'m> Ctxt<'_, 'm> { let mut tests = Vec::new(); - markdown::push_html(&self.syntax_set, &mut o, iter, capture_tests.then_some(&mut tests))?; + markdown::push_html( + &self.syntax_set, + &mut o, + iter, + capture_tests.then_some(&mut tests), + )?; if let Some(error) = link_error { return Err(error); @@ -517,7 +546,11 @@ impl<'m> Ctxt<'_, 'm> { } } - let mut it = self.context.meta_by_hash(hash)?.into_iter().flat_map(|m| Some((m, into_item_kind(m)?))); + let mut it = self + .context + .meta_by_hash(hash)? + .into_iter() + .flat_map(|m| Some((m, into_item_kind(m)?))); let Some((meta, kind)) = it.next() else { tracing::warn!(?hash, "No link for hash"); @@ -526,7 +559,7 @@ impl<'m> Ctxt<'_, 'm> { tracing::warn!("Candidate: {:?}", meta.kind); } - return Ok(Some(try_format!("{hash}"))) + return Ok(Some(try_format!("{hash}"))); }; let item = meta.item.context("Missing item link meta")?; @@ -540,7 +573,9 @@ impl<'m> Ctxt<'_, 'm> { }; let path = self.item_path(item, kind)?; - Ok(Some(try_format!("{name}"))) + Ok(Some(try_format!( + "{name}" + ))) } /// Coerce args into string. @@ -642,7 +677,11 @@ impl<'m> Ctxt<'_, 'm> { Ok(string) } - fn link_callback(&self, meta: Meta<'_>, link: &str) -> Result> { + fn link_callback( + &self, + meta: Meta<'_>, + link: &str, + ) -> Result> { enum Flavor { Any, Macro, @@ -707,7 +746,7 @@ impl<'m> Ctxt<'_, 'm> { Kind::Function(_) if flavor.is_function() => ItemKind::Function, _ => { continue; - }, + } })?; } @@ -744,8 +783,12 @@ fn asset_str(path: &str) -> Result> { let asset = embed::Assets::get(path).with_context(|| anyhow!("{path}: missing asset"))?; let data = match asset.data { - rust_alloc::borrow::Cow::Borrowed(data) => Cow::Borrowed(str::from_utf8(data).with_context(|| anyhow!("{path}: not utf-8"))?), - rust_alloc::borrow::Cow::Owned(data) => Cow::Owned(String::from_utf8(data.try_into()?).with_context(|| anyhow!("{path}: not utf-8"))?), + rust_alloc::borrow::Cow::Borrowed(data) => { + Cow::Borrowed(str::from_utf8(data).with_context(|| anyhow!("{path}: not utf-8"))?) + } + rust_alloc::borrow::Cow::Owned(data) => Cow::Owned( + String::from_utf8(data.try_into()?).with_context(|| anyhow!("{path}: not utf-8"))?, + ), }; Ok(data) @@ -758,7 +801,10 @@ fn compile(templating: &templating::Templating, path: &str) -> Result(cx: &Ctxt<'_, 'm>, mods: Vec<(&'m Item, RelativePathBuf)>) -> Result> { +fn build_index<'m>( + cx: &Ctxt<'_, 'm>, + mods: Vec<(&'m Item, RelativePathBuf)>, +) -> Result> { #[derive(Serialize)] struct Params<'a> { #[serde(flatten)] @@ -779,7 +825,7 @@ fn build_index<'m>(cx: &Ctxt<'_, 'm>, mods: Vec<(&'m Item, RelativePathBuf)>) -> let mut c = item.iter(); match c.next() { - None => {}, + None => {} Some(ComponentRef::Crate(..)) => {} _ => continue, } @@ -801,7 +847,11 @@ fn build_index<'m>(cx: &Ctxt<'_, 'm>, mods: Vec<(&'m Item, RelativePathBuf)>) -> /// Build a single module. #[tracing::instrument(skip_all)] -fn module<'m>(cx: &mut Ctxt<'_, 'm>, meta: Meta<'m>, queue: &mut VecDeque>) -> Result> { +fn module<'m>( + cx: &mut Ctxt<'_, 'm>, + meta: Meta<'m>, + queue: &mut VecDeque>, +) -> Result> { #[derive(Serialize)] struct Params<'a> { #[serde(flatten)] @@ -950,7 +1000,12 @@ fn module<'m>(cx: &mut Ctxt<'_, 'm>, meta: Meta<'m>, queue: &mut VecDeque(cx: &mut Ctxt<'_, 'm>, meta: Meta<'m>, queue: &mut VecDeque(cx: &mut Ctxt<'_, 'm>, meta: Meta<'m>) -> Result f, + Kind::Function( + f @ Function { + signature: Signature::Function { .. }, + .. + }, + ) => f, _ => bail!("found meta, but not a function"), }; @@ -1095,7 +1154,12 @@ where } /// Helper for building an item path. -fn build_item_path(name: &str, item: &Item, kind: ItemKind, path: &mut RelativePathBuf) -> Result<()> { +fn build_item_path( + name: &str, + item: &Item, + kind: ItemKind, + path: &mut RelativePathBuf, +) -> Result<()> { if item.is_empty() { path.push(name); } else { @@ -1123,18 +1187,20 @@ fn build_item_path(name: &str, item: &Item, kind: ItemKind, path: &mut RelativeP } /// Render documentation. -fn render_code_by_syntax(syntax_set: &SyntaxSet, lines: I, syntax: &SyntaxReference, mut out: Option<&mut String>) -> Result +fn render_code_by_syntax( + syntax_set: &SyntaxSet, + lines: I, + syntax: &SyntaxReference, + mut out: Option<&mut String>, +) -> Result where I: IntoIterator, I::Item: AsRef, { let mut buf = String::new(); - let mut gen = ClassedHTMLGenerator::new_with_class_style( - syntax, - syntax_set, - ClassStyle::Spaced, - ); + let mut gen = + ClassedHTMLGenerator::new_with_class_style(syntax, syntax_set, ClassStyle::Spaced); for line in lines { let line = line.as_ref(); diff --git a/crates/rune/src/doc/build/enum_.rs b/crates/rune/src/doc/build/enum_.rs index e1c720a61..9bf2462cd 100644 --- a/crates/rune/src/doc/build/enum_.rs +++ b/crates/rune/src/doc/build/enum_.rs @@ -3,8 +3,8 @@ use serde::Serialize; use crate::alloc::{String, Vec}; use crate::compile::{ComponentRef, Item}; -use crate::doc::context::Meta; use crate::doc::build::{self, Builder, Ctxt, IndexEntry}; +use crate::doc::context::Meta; #[derive(Serialize)] struct Params<'a> { @@ -23,7 +23,10 @@ struct Params<'a> { /// Build an enumeration. #[tracing::instrument(skip_all)] -pub(crate) fn build<'m>(cx: &mut Ctxt<'_, 'm>, meta: Meta<'m>) -> Result<(Builder<'m>, Vec>)> { +pub(crate) fn build<'m>( + cx: &mut Ctxt<'_, 'm>, + meta: Meta<'m>, +) -> Result<(Builder<'m>, Vec>)> { let module = cx.module_path_html(meta, false)?; let (protocols, methods, variants, index) = build::type_::build_assoc_fns(cx, meta)?; diff --git a/crates/rune/src/doc/build/markdown.rs b/crates/rune/src/doc/build/markdown.rs index f656c9123..69c079326 100644 --- a/crates/rune/src/doc/build/markdown.rs +++ b/crates/rune/src/doc/build/markdown.rs @@ -1,14 +1,14 @@ use core::fmt; use std::io; -use crate::doc::artifacts::TestParams; -use crate::alloc::{try_vec, String, Vec, HashMap}; use crate::alloc::fmt::TryWrite; +use crate::alloc::{try_vec, HashMap, String, Vec}; +use crate::doc::artifacts::TestParams; -use syntect::parsing::{SyntaxReference, SyntaxSet}; -use pulldown_cmark::escape::{escape_href, escape_html, StrWrite}; -use pulldown_cmark::{CowStr, Alignment, CodeBlockKind, LinkType, Tag, Event}; use anyhow::Result; +use pulldown_cmark::escape::{escape_href, escape_html, StrWrite}; +use pulldown_cmark::{Alignment, CodeBlockKind, CowStr, Event, LinkType, Tag}; +use syntect::parsing::{SyntaxReference, SyntaxSet}; pub(crate) const RUST_TOKEN: &str = "rust"; pub(crate) const RUNE_TOKEN: &str = "rune"; @@ -26,11 +26,14 @@ struct StringWriter<'a> { impl StrWrite for StringWriter<'_> { fn write_str(&mut self, s: &str) -> io::Result<()> { - self.string.try_push_str(s).map_err(|error| io::Error::new(io::ErrorKind::Other, error)) + self.string + .try_push_str(s) + .map_err(|error| io::Error::new(io::ErrorKind::Other, error)) } fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> { - TryWrite::write_fmt(self.string, args).map_err(|error| io::Error::new(io::ErrorKind::Other, error)) + TryWrite::write_fmt(self.string, args) + .map_err(|error| io::Error::new(io::ErrorKind::Other, error)) } } @@ -70,7 +73,8 @@ where let mut string = String::new(); let s = (self.tests.is_some() && params.is_some()).then_some(&mut string); - let html = super::render_code_by_syntax(self.syntax_set, text.lines(), syntax, s)?; + let html = + super::render_code_by_syntax(self.syntax_set, text.lines(), syntax, s)?; if let Some(params) = params { if let Some(tests) = self.tests.as_mut() { @@ -215,13 +219,13 @@ where } Tag::Emphasis => { self.write("")?; - }, + } Tag::Strong => { self.write("")?; - }, + } Tag::Strikethrough => { self.write("")?; - }, + } Tag::Link(LinkType::Email, dest, title) => { self.write("(&mut self, kind: &'input CodeBlockKind<'input>) -> (&'input str, &'a SyntaxReference, Option) { + fn find_syntax<'input>( + &mut self, + kind: &'input CodeBlockKind<'input>, + ) -> (&'input str, &'a SyntaxReference, Option) { let mut syntax = None; let mut params = TestParams::default(); @@ -286,15 +293,12 @@ where params.ignore = true; continue; } - RUNE_TOKEN => { - (RUNE_TOKEN, RUST_TOKEN, true) - } + RUNE_TOKEN => (RUNE_TOKEN, RUST_TOKEN, true), token => (token, token, false), }; if syntax.is_none() { - if let Some(s) = self.syntax_set.find_syntax_by_token(lookup) - { + if let Some(s) = self.syntax_set.find_syntax_by_token(lookup) { syntax = Some((token, s, is_rune)); } } @@ -306,7 +310,11 @@ where } let Some(syntax) = self.syntax_set.find_syntax_by_token(RUST_TOKEN) else { - return ("text", self.syntax_set.find_syntax_plain_text(), Some(params)); + return ( + "text", + self.syntax_set.find_syntax_plain_text(), + Some(params), + ); }; (RUNE_TOKEN, syntax, Some(params)) @@ -412,7 +420,12 @@ where } /// Process markdown html and captures tests. -pub(super) fn push_html<'a, I>(syntax_set: &'a SyntaxSet, string: &'a mut String, iter: I, tests: Option<&'a mut Vec<(String, TestParams)>>) -> Result<()> +pub(super) fn push_html<'a, I>( + syntax_set: &'a SyntaxSet, + string: &'a mut String, + iter: I, + tests: Option<&'a mut Vec<(String, TestParams)>>, +) -> Result<()> where I: Iterator>, { diff --git a/crates/rune/src/doc/build/type_.rs b/crates/rune/src/doc/build/type_.rs index 6c0700e24..fc9dcc3b1 100644 --- a/crates/rune/src/doc/build/type_.rs +++ b/crates/rune/src/doc/build/type_.rs @@ -1,12 +1,12 @@ use anyhow::{Context, Result}; use serde::Serialize; -use crate::alloc::{Vec, String}; use crate::alloc::borrow::Cow; use crate::alloc::prelude::*; +use crate::alloc::{String, Vec}; use crate::compile::{ComponentRef, Item}; +use crate::doc::build::{Builder, Ctxt, IndexEntry, IndexKind}; use crate::doc::context::{Assoc, AssocFnKind, Meta}; -use crate::doc::build::{Ctxt, IndexEntry, IndexKind, Builder}; #[derive(Serialize)] pub(super) struct Protocol<'a> { @@ -38,7 +38,12 @@ pub(super) struct Variant<'a> { pub(super) fn build_assoc_fns<'m>( cx: &mut Ctxt<'_, 'm>, meta: Meta<'m>, -) -> Result<(Vec>, Vec>, Vec>, Vec>)> { +) -> Result<( + Vec>, + Vec>, + Vec>, + Vec>, +)> { let mut protocols = Vec::new(); let mut methods = Vec::new(); let mut variants = Vec::new(); @@ -48,7 +53,8 @@ pub(super) fn build_assoc_fns<'m>( for assoc in cx.context.associated(meta.hash) { match assoc { Assoc::Variant(variant) => { - let line_doc = cx.render_line_docs(meta, variant.docs.get(..1).unwrap_or_default())?; + let line_doc = + cx.render_line_docs(meta, variant.docs.get(..1).unwrap_or_default())?; let doc = cx.render_docs(meta, variant.docs, true)?; variants.try_push(Variant { @@ -71,14 +77,15 @@ pub(super) fn build_assoc_fns<'m>( (protocol, value.as_str()) } AssocFnKind::Method(name, args, sig) => { - let line_doc = cx.render_line_docs(meta, assoc.docs.get(..1).unwrap_or_default())?; + let line_doc = + cx.render_line_docs(meta, assoc.docs.get(..1).unwrap_or_default())?; cx.state.item.push(name)?; let doc = cx.render_docs(meta, assoc.docs, true)?; cx.state.item.pop()?; let mut list = Vec::new(); - + for &hash in assoc.parameter_types { if let Some(link) = cx.link(hash, None)? { list.try_push(link)?; @@ -87,7 +94,9 @@ pub(super) fn build_assoc_fns<'m>( } } - let parameters = (!list.is_empty()).then(|| list.iter().try_join(", ")).transpose()?; + let parameters = (!list.is_empty()) + .then(|| list.iter().try_join(", ")) + .transpose()?; methods.try_push(Method { is_async: assoc.is_async, @@ -107,7 +116,7 @@ pub(super) fn build_assoc_fns<'m>( line_doc, doc, })?; - + continue; } }; @@ -144,7 +153,10 @@ pub(super) fn build_assoc_fns<'m>( for m in &methods { index.try_push(IndexEntry { - path: cx.state.path.with_file_name(format!("{name}#method.{}", m.name)), + path: cx + .state + .path + .with_file_name(format!("{name}#method.{}", m.name)), item: Cow::Owned(meta_item.join([m.name])?), kind: IndexKind::Method, doc: m.line_doc.try_clone()?, @@ -153,7 +165,10 @@ pub(super) fn build_assoc_fns<'m>( for m in &variants { index.try_push(IndexEntry { - path: cx.state.path.with_file_name(format!("{name}#variant.{}", m.name)), + path: cx + .state + .path + .with_file_name(format!("{name}#variant.{}", m.name)), item: Cow::Owned(meta_item.join([m.name])?), kind: IndexKind::Variant, doc: m.line_doc.try_clone()?, @@ -182,7 +197,12 @@ struct Params<'a> { /// Build an unknown type. #[tracing::instrument(skip_all)] -pub(crate) fn build<'m>(cx: &mut Ctxt<'_, 'm>, what: &'static str, what_class: &'static str, meta: Meta<'m>) -> Result<(Builder<'m>, Vec>)> { +pub(crate) fn build<'m>( + cx: &mut Ctxt<'_, 'm>, + what: &'static str, + what_class: &'static str, + meta: Meta<'m>, +) -> Result<(Builder<'m>, Vec>)> { let module = cx.module_path_html(meta, false)?; let (protocols, methods, _, index) = build_assoc_fns(cx, meta)?; diff --git a/crates/rune/src/doc/context.rs b/crates/rune/src/doc/context.rs index 464584017..cf3ccfffa 100644 --- a/crates/rune/src/doc/context.rs +++ b/crates/rune/src/doc/context.rs @@ -1,5 +1,5 @@ -use crate::alloc::{self, String, Vec}; use crate::alloc::prelude::*; +use crate::alloc::{self, String, Vec}; use crate::compile::context::ContextMeta; use crate::compile::{meta, ComponentRef, IntoComponent, Item, ItemBuf}; use crate::doc::{Visitor, VisitorData}; @@ -135,7 +135,11 @@ impl<'a> Context<'a> { .. }) => ( f.is_async, - AssocFnKind::Method(data.item.last()?.as_str()?, f.args, Signature::Function), + AssocFnKind::Method( + data.item.last()?.as_str()?, + f.args, + Signature::Function, + ), ), Some(meta::Kind::Function { associated: Some(meta::AssociatedKind::Instance(name)), @@ -173,9 +177,17 @@ impl<'a> Context<'a> { match &meta.kind { meta::Kind::Variant { .. } => { let name = meta.item.as_deref()?.last()?.as_str()?; - Some(Assoc::Variant(AssocVariant { name, docs: meta.docs.lines() })) + Some(Assoc::Variant(AssocVariant { + name, + docs: meta.docs.lines(), + })) } - meta::Kind::Function { associated: Some(associated), parameter_types, signature, .. } => { + meta::Kind::Function { + associated: Some(associated), + parameter_types, + signature, + .. + } => { let kind = match *associated { meta::AssociatedKind::Protocol(protocol) => AssocFnKind::Protocol(protocol), meta::AssociatedKind::FieldFn(protocol, ref field) => { @@ -184,22 +196,27 @@ impl<'a> Context<'a> { meta::AssociatedKind::IndexFn(protocol, index) => { AssocFnKind::IndexFn(protocol, index) } - meta::AssociatedKind::Instance(ref name) => AssocFnKind::Method(name, signature.args, Signature::Instance), + meta::AssociatedKind::Instance(ref name) => { + AssocFnKind::Method(name, signature.args, Signature::Instance) + } }; Some(Assoc::Fn(AssocFn { kind, is_async: signature.is_async, return_type: signature.return_type, - argument_types: &signature - .argument_types, + argument_types: &signature.argument_types, arg_names: meta.docs.args(), parameter_types: ¶meter_types[..], deprecated: meta.deprecated.as_deref(), docs: meta.docs.lines(), })) } - meta::Kind::Function { associated: None, signature, .. } => { + meta::Kind::Function { + associated: None, + signature, + .. + } => { let name = meta.item.as_deref()?.last()?.as_str()?; let kind = AssocFnKind::Method(name, signature.args, Signature::Function); @@ -207,8 +224,7 @@ impl<'a> Context<'a> { kind, is_async: signature.is_async, return_type: signature.return_type, - argument_types: &signature - .argument_types, + argument_types: &signature.argument_types, arg_names: meta.docs.args(), parameter_types: &[], deprecated: meta.deprecated.as_deref(), @@ -303,31 +319,27 @@ impl<'a> Context<'a> { associated: None, signature: f, .. - } => { - Kind::Function(Function { - is_async: f.is_async, - signature: Signature::Function, - arg_names: meta.docs.args(), - args: f.args, - return_type: f.return_type, - argument_types: &f.argument_types, - }) - } + } => Kind::Function(Function { + is_async: f.is_async, + signature: Signature::Function, + arg_names: meta.docs.args(), + args: f.args, + return_type: f.return_type, + argument_types: &f.argument_types, + }), meta::Kind::Function { associated: Some(..), signature: f, .. - } => { - Kind::Function(Function { - is_async: f.is_async, - signature: Signature::Instance, - arg_names: meta.docs.args(), - args: f.args, - return_type: f.return_type, - argument_types: &f.argument_types, - }) - } - meta::Kind::Const {.. } => { + } => Kind::Function(Function { + is_async: f.is_async, + signature: Signature::Instance, + arg_names: meta.docs.args(), + args: f.args, + return_type: f.return_type, + argument_types: &f.argument_types, + }), + meta::Kind::Const { .. } => { let const_value = self.context.get_const_value(meta.hash)?; Kind::Const(const_value) } @@ -361,7 +373,11 @@ fn visitor_meta_to_meta<'a>(base: &'a Item, data: &'a VisitorData) -> Meta<'a> { Some(meta::Kind::Struct { .. }) => Kind::Struct, Some(meta::Kind::Variant { .. }) => Kind::Variant, Some(meta::Kind::Enum { .. }) => Kind::Enum, - Some(meta::Kind::Function { associated, signature: f, .. }) => Kind::Function(Function { + Some(meta::Kind::Function { + associated, + signature: f, + .. + }) => Kind::Function(Function { is_async: f.is_async, arg_names: None, args: f.args, diff --git a/crates/rune/src/doc/templating.rs b/crates/rune/src/doc/templating.rs index ce85010db..80e59699a 100644 --- a/crates/rune/src/doc/templating.rs +++ b/crates/rune/src/doc/templating.rs @@ -1,11 +1,12 @@ -use crate::std::sync::Mutex; -use ::rust_alloc::sync::Arc; -use crate::alloc::{self, String, HashMap}; use crate::alloc::borrow::Cow; use crate::alloc::prelude::*; +use crate::alloc::{self, HashMap, String}; +use crate::std::sync::Mutex; +use ::rust_alloc::sync::Arc; use handlebars::{ - Context, Handlebars, Helper, HelperResult, Output, RenderContext, Renderable, StringOutput, HelperDef, + Context, Handlebars, Helper, HelperDef, HelperResult, Output, RenderContext, Renderable, + StringOutput, }; use serde::Serialize; @@ -40,7 +41,10 @@ pub(crate) struct Paths { impl Paths { /// Insert a path redirect. pub(crate) fn insert(&self, from: &str, to: &str) -> alloc::Result<()> { - self.inner.lock().unwrap().try_insert(from.try_to_owned()?, to.try_to_owned()?)?; + self.inner + .lock() + .unwrap() + .try_insert(from.try_to_owned()?, to.try_to_owned()?)?; Ok(()) } } @@ -52,7 +56,10 @@ pub(crate) struct Templating { impl Templating { /// Set up a new templating engine. - pub(crate) fn new<'a, I>(partials: I, paths: Paths) -> Result where I: IntoIterator)> { + pub(crate) fn new<'a, I>(partials: I, paths: Paths) -> Result + where + I: IntoIterator)>, + { let mut handlebars = Handlebars::new(); handlebars.register_helper("literal", ::rust_alloc::boxed::Box::new(literal)); handlebars.register_helper("path", ::rust_alloc::boxed::Box::new(path(paths))); @@ -90,7 +97,12 @@ fn literal( } fn path(paths: Paths) -> impl HelperDef + Send + Sync + 'static { - move |h: &Helper<'_, '_>, _: &Handlebars<'_>, _: &Context, _: &mut RenderContext<'_, '_>, out: &mut dyn Output| -> HelperResult { + move |h: &Helper<'_, '_>, + _: &Handlebars<'_>, + _: &Context, + _: &mut RenderContext<'_, '_>, + out: &mut dyn Output| + -> HelperResult { let param = h.param(0).and_then(|v| v.value().as_str()).unwrap_or(""); let inner = paths.inner.lock().unwrap(); let path = inner.get(param).map(String::as_str).unwrap_or(param); diff --git a/crates/rune/src/doc/visitor.rs b/crates/rune/src/doc/visitor.rs index bb59a24dd..301d8b41e 100644 --- a/crates/rune/src/doc/visitor.rs +++ b/crates/rune/src/doc/visitor.rs @@ -1,12 +1,12 @@ -use crate::alloc::prelude::*; -use crate::alloc::{Box, Vec, String}; +use crate::alloc; use crate::alloc::hash_map::{self, HashMap}; +use crate::alloc::prelude::*; +use crate::alloc::{Box, String, Vec}; +use crate::compile::meta; use crate::compile::{ - MetaError, CompileVisitor, IntoComponent, Item, ItemBuf, MetaRef, Names, Located, + CompileVisitor, IntoComponent, Item, ItemBuf, Located, MetaError, MetaRef, Names, }; -use crate::compile::meta; use crate::hash::Hash; -use crate::alloc; pub(crate) struct VisitorData { pub(crate) item: ItemBuf, @@ -57,7 +57,10 @@ impl Visitor { let hash = Hash::type_hash(&this.base); this.names.insert(&this.base)?; - this.data.try_insert(hash, VisitorData::new(this.base.try_clone()?, hash, Some(meta::Kind::Module)))?; + this.data.try_insert( + hash, + VisitorData::new(this.base.try_clone()?, hash, Some(meta::Kind::Module)), + )?; this.item_to_hash.try_insert(this.base.try_clone()?, hash)?; Ok(this) } @@ -85,14 +88,19 @@ impl CompileVisitor for Visitor { tracing::trace!(base = ?self.base, meta = ?meta.item, ?item, "register meta"); self.names.insert(&item)?; - self.item_to_hash.try_insert(item.try_to_owned()?, meta.hash)?; + self.item_to_hash + .try_insert(item.try_to_owned()?, meta.hash)?; match self.data.entry(meta.hash) { hash_map::Entry::Occupied(e) => { e.into_mut().kind = Some(meta.kind.try_clone()?); } hash_map::Entry::Vacant(e) => { - e.try_insert(VisitorData::new(item, meta.hash, Some(meta.kind.try_clone()?)))?; + e.try_insert(VisitorData::new( + item, + meta.hash, + Some(meta.kind.try_clone()?), + ))?; } } @@ -106,7 +114,13 @@ impl CompileVisitor for Visitor { Ok(()) } - fn visit_doc_comment(&mut self, _location: &dyn Located, item: &Item, hash: Hash, string: &str) -> Result<(), MetaError> { + fn visit_doc_comment( + &mut self, + _location: &dyn Located, + item: &Item, + hash: Hash, + string: &str, + ) -> Result<(), MetaError> { // Documentation comments are literal source lines, so they're newline // terminated. Since we perform our own internal newlines conversion // these need to be trimmed - at least between each doc item. @@ -119,10 +133,13 @@ impl CompileVisitor for Visitor { let data = match self.data.entry(hash) { hash_map::Entry::Occupied(e) => e.into_mut(), - hash_map::Entry::Vacant(e) => e.try_insert(VisitorData::new(item.try_to_owned()?, hash, None))?, + hash_map::Entry::Vacant(e) => { + e.try_insert(VisitorData::new(item.try_to_owned()?, hash, None))? + } }; - data.docs.try_push(string.trim_end_matches(newlines).try_to_owned()?)?; + data.docs + .try_push(string.trim_end_matches(newlines).try_to_owned()?)?; Ok(()) } @@ -139,7 +156,9 @@ impl CompileVisitor for Visitor { let data = match self.data.entry(hash) { hash_map::Entry::Occupied(e) => e.into_mut(), - hash_map::Entry::Vacant(e) => e.try_insert(VisitorData::new(item.try_to_owned()?, hash, None))?, + hash_map::Entry::Vacant(e) => { + e.try_insert(VisitorData::new(item.try_to_owned()?, hash, None))? + } }; data.field_docs diff --git a/crates/rune/src/workspace.rs b/crates/rune/src/workspace.rs index e07bcb659..9b6e86ac2 100644 --- a/crates/rune/src/workspace.rs +++ b/crates/rune/src/workspace.rs @@ -17,14 +17,14 @@ cfg_emit! { } mod error; -pub use self::error::{WorkspaceError}; +pub use self::error::WorkspaceError; pub(crate) use self::error::WorkspaceErrorKind; mod manifest; -pub use self::manifest::{Manifest, WorkspaceFilter, Package, FoundKind, Found, FoundPackage}; +pub use self::manifest::{Found, FoundKind, FoundPackage, Manifest, Package, WorkspaceFilter}; mod diagnostics; -pub use self::diagnostics::{Diagnostics, Diagnostic, FatalDiagnostic}; +pub use self::diagnostics::{Diagnostic, Diagnostics, FatalDiagnostic}; mod source_loader; pub use self::source_loader::{FileSourceLoader, SourceLoader}; diff --git a/crates/rune/src/workspace/build.rs b/crates/rune/src/workspace/build.rs index ddee32bc5..257eb4dcd 100644 --- a/crates/rune/src/workspace/build.rs +++ b/crates/rune/src/workspace/build.rs @@ -1,10 +1,10 @@ use core::fmt; -use crate::Sources; -use crate::ast::Span; use crate::alloc; -use crate::workspace::{SourceLoader, Diagnostics, FileSourceLoader, WorkspaceError}; +use crate::ast::Span; use crate::workspace::manifest::{Loader, Manifest}; +use crate::workspace::{Diagnostics, FileSourceLoader, SourceLoader, WorkspaceError}; +use crate::Sources; /// Failed to build workspace. #[derive(Debug)] @@ -38,7 +38,7 @@ impl fmt::Display for BuildError { match &self.kind { BuildErrorKind::Default => { write!(f, "Failed to load workspace (see diagnostics for details)") - }, + } BuildErrorKind::Alloc(error) => error.fmt(f), } } @@ -108,7 +108,8 @@ impl<'a> Build<'a> { let mut manifest = Manifest::default(); for id in self.sources.source_ids() { - let mut loader = Loader::new(id, self.sources, diagnostics, source_loader, &mut manifest); + let mut loader = + Loader::new(id, self.sources, diagnostics, source_loader, &mut manifest); if let Err(error) = loader.load_manifest() { diagnostics.fatal(id, WorkspaceError::new(Span::empty(), error))?; @@ -118,7 +119,7 @@ impl<'a> Build<'a> { if diagnostics.has_errors() { return Err(BuildError::DEFAULT); } - + Ok(manifest) } } diff --git a/crates/rune/src/workspace/diagnostics.rs b/crates/rune/src/workspace/diagnostics.rs index 3211036c9..921111b55 100644 --- a/crates/rune/src/workspace/diagnostics.rs +++ b/crates/rune/src/workspace/diagnostics.rs @@ -1,6 +1,6 @@ use crate::alloc::{self, Vec}; -use crate::SourceId; use crate::workspace::WorkspaceError; +use crate::SourceId; /// A fatal diagnostic in a workspace. #[derive(Debug)] @@ -43,7 +43,9 @@ impl Diagnostics { /// Test if diagnostics has errors. pub fn has_errors(&self) -> bool { - self.diagnostics.iter().any(|e| matches!(e, Diagnostic::Fatal(..))) + self.diagnostics + .iter() + .any(|e| matches!(e, Diagnostic::Fatal(..))) } /// Test if diagnostics is empty. @@ -52,11 +54,13 @@ impl Diagnostics { } /// Report a single workspace error. - pub(crate) fn fatal(&mut self, source_id: SourceId, error: WorkspaceError) -> alloc::Result<()> { - self.diagnostics.try_push(Diagnostic::Fatal(FatalDiagnostic { - source_id, - error, - })) + pub(crate) fn fatal( + &mut self, + source_id: SourceId, + error: WorkspaceError, + ) -> alloc::Result<()> { + self.diagnostics + .try_push(Diagnostic::Fatal(FatalDiagnostic { source_id, error })) } } diff --git a/crates/rune/src/workspace/emit.rs b/crates/rune/src/workspace/emit.rs index 405aa663e..a380259cf 100644 --- a/crates/rune/src/workspace/emit.rs +++ b/crates/rune/src/workspace/emit.rs @@ -7,11 +7,11 @@ use codespan_reporting::diagnostic as d; use codespan_reporting::term; use codespan_reporting::term::termcolor::WriteColor; -use crate::alloc::prelude::*; use crate::alloc; -use crate::Sources; +use crate::alloc::prelude::*; use crate::ast::Spanned; -use crate::workspace::{Diagnostics, Diagnostic, FatalDiagnostic}; +use crate::workspace::{Diagnostic, Diagnostics, FatalDiagnostic}; +use crate::Sources; /// Errors that can be raised when formatting diagnostics. #[derive(Debug)] @@ -70,11 +70,7 @@ impl Diagnostics { /// hints. /// /// See [prepare][crate::prepare] for how to use. - pub fn emit( - &self, - out: &mut O, - sources: &Sources, - ) -> Result<(), EmitError> + pub fn emit(&self, out: &mut O, sources: &Sources) -> Result<(), EmitError> where O: WriteColor, { @@ -109,7 +105,10 @@ where let mut labels = rust_alloc::vec::Vec::new(); let span = this.error().span(); - labels.push(d::Label::primary(this.source_id(), span.range()).with_message(this.error().try_to_string()?.into_std())); + labels.push( + d::Label::primary(this.source_id(), span.range()) + .with_message(this.error().try_to_string()?.into_std()), + ); let diagnostic = d::Diagnostic::error() .with_message(this.error().try_to_string()?.into_std()) diff --git a/crates/rune/src/workspace/error.rs b/crates/rune/src/workspace/error.rs index 78fde8a1d..b388edd93 100644 --- a/crates/rune/src/workspace/error.rs +++ b/crates/rune/src/workspace/error.rs @@ -3,11 +3,11 @@ use core::fmt; use std::path::Path; use crate::alloc::{self, Box, String}; -use crate::SourceId; -use crate::compile::HasSpan; use crate::ast::{Span, Spanned}; -use crate::workspace::glob; +use crate::compile::HasSpan; use crate::source; +use crate::workspace::glob; +use crate::SourceId; /// An error raised when interacting with workspaces. #[derive(Debug)] @@ -36,7 +36,12 @@ impl WorkspaceError { S: Spanned, M: fmt::Display + fmt::Debug + Send + Sync + 'static, { - Self::new(spanned, WorkspaceErrorKind::Custom { error: anyhow::Error::msg(message) }) + Self::new( + spanned, + WorkspaceErrorKind::Custom { + error: anyhow::Error::msg(message), + }, + ) } } @@ -87,7 +92,9 @@ where #[allow(missing_docs)] #[non_exhaustive] pub(crate) enum WorkspaceErrorKind { - Custom { error: anyhow::Error }, + Custom { + error: anyhow::Error, + }, GlobError { path: Box, error: glob::GlobError, @@ -96,15 +103,27 @@ pub(crate) enum WorkspaceErrorKind { path: Box, error: source::FromPathError, }, - Toml { error: toml::de::Error }, - Key { error: serde_hashkey::Error }, - MissingSourceId { source_id: SourceId }, - MissingField { field: &'static str }, + Toml { + error: toml::de::Error, + }, + Key { + error: serde_hashkey::Error, + }, + MissingSourceId { + source_id: SourceId, + }, + MissingField { + field: &'static str, + }, ExpectedArray, MissingManifestPath, ExpectedTable, - UnsupportedKey { key: String }, - AllocError { error: alloc::Error }, + UnsupportedKey { + key: String, + }, + AllocError { + error: alloc::Error, + }, } cfg_std! { @@ -132,44 +151,36 @@ cfg_std! { impl fmt::Display for WorkspaceErrorKind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - WorkspaceErrorKind::Custom { error } => { - error.fmt(f) - } + WorkspaceErrorKind::Custom { error } => error.fmt(f), WorkspaceErrorKind::GlobError { path, error } => write!( f, - "Failed to glob at `{path}`: {error}", path = path.display() + "Failed to glob at `{path}`: {error}", + path = path.display() ), WorkspaceErrorKind::Source { path, error } => write!( f, - "Failed to load source at `{path}`: {error}", path = path.display() - ), - WorkspaceErrorKind::Toml { error } => write!( - f, - "Failed to deserialize manifest: {error}", - ), - WorkspaceErrorKind::Key { error } => write!( - f, - "Failed to deserialize: {error}", - error = error - ), - WorkspaceErrorKind::MissingSourceId { source_id } => write!( - f, - "Missing source id `{source_id}`", - ), - WorkspaceErrorKind::MissingField { field } => write!( - f, - "Missing required field `{field}`", + "Failed to load source at `{path}`: {error}", + path = path.display() ), + WorkspaceErrorKind::Toml { error } => { + write!(f, "Failed to deserialize manifest: {error}",) + } + WorkspaceErrorKind::Key { error } => { + write!(f, "Failed to deserialize: {error}", error = error) + } + WorkspaceErrorKind::MissingSourceId { source_id } => { + write!(f, "Missing source id `{source_id}`",) + } + WorkspaceErrorKind::MissingField { field } => { + write!(f, "Missing required field `{field}`",) + } WorkspaceErrorKind::ExpectedArray {} => write!(f, "Expected array"), WorkspaceErrorKind::MissingManifestPath {} => write!( f, "Element `[workspace]` can only be used in manifests with a valid path" ), WorkspaceErrorKind::ExpectedTable {} => write!(f, "Expected table"), - WorkspaceErrorKind::UnsupportedKey { key } => write!( - f, - "Key `{key}` not supported", - ), + WorkspaceErrorKind::UnsupportedKey { key } => write!(f, "Key `{key}` not supported",), WorkspaceErrorKind::AllocError { error } => error.fmt(f), } } diff --git a/crates/rune/src/workspace/glob.rs b/crates/rune/src/workspace/glob.rs index 56aac5c56..59beb8b2c 100644 --- a/crates/rune/src/workspace/glob.rs +++ b/crates/rune/src/workspace/glob.rs @@ -9,7 +9,7 @@ use std::path::{Path, PathBuf}; use crate as rune; use crate::alloc::prelude::*; -use crate::alloc::{self, VecDeque, Vec, Box}; +use crate::alloc::{self, Box, Vec, VecDeque}; use relative_path::RelativePath; diff --git a/crates/rune/src/workspace/manifest.rs b/crates/rune/src/workspace/manifest.rs index e3c09380c..af1c9a349 100644 --- a/crates/rune/src/workspace/manifest.rs +++ b/crates/rune/src/workspace/manifest.rs @@ -1,23 +1,25 @@ +use std::ffi::OsStr; use std::fmt; -use std::path::{PathBuf, Path}; -use std::iter; -use std::io; use std::fs; -use std::ffi::OsStr; +use std::io; +use std::iter; +use std::path::{Path, PathBuf}; use anyhow::Result; -use relative_path::{RelativePathBuf, RelativePath}; +use relative_path::{RelativePath, RelativePathBuf}; use semver::Version; use serde::de::IntoDeserializer; use serde::Deserialize; use serde_hashkey as key; -use crate::alloc::{self, Vec, String}; use crate::alloc::prelude::*; -use crate::{Sources, SourceId}; +use crate::alloc::{self, String, Vec}; use crate::ast::{Span, Spanned}; -use crate::workspace::{MANIFEST_FILE, WorkspaceErrorKind, Diagnostics, WorkspaceError, SourceLoader, glob}; -use crate::workspace::spanned_value::{Array, SpannedValue, Value, Table}; +use crate::workspace::spanned_value::{Array, SpannedValue, Table, Value}; +use crate::workspace::{ + glob, Diagnostics, SourceLoader, WorkspaceError, WorkspaceErrorKind, MANIFEST_FILE, +}; +use crate::{SourceId, Sources}; const BIN: &str = "bin"; const TESTS: &str = "tests"; @@ -110,7 +112,13 @@ pub struct Manifest { } impl Manifest { - fn find_paths<'m>(&'m self, m: WorkspaceFilter<'_>, kind: FoundKind, auto_path: &Path, auto_find: fn(&Package) -> bool) -> Result>> { + fn find_paths<'m>( + &'m self, + m: WorkspaceFilter<'_>, + kind: FoundKind, + auto_path: &Path, + auto_find: fn(&Package) -> bool, + ) -> Result>> { let mut output = Vec::new(); for package in self.packages.iter() { @@ -144,7 +152,9 @@ impl Manifest { /// Find all examples matching the given name in the workspace. pub fn find_examples(&self, m: WorkspaceFilter<'_>) -> Result>> { - self.find_paths(m, FoundKind::Example, Path::new(EXAMPLES), |p| p.auto_examples) + self.find_paths(m, FoundKind::Example, Path::new(EXAMPLES), |p| { + p.auto_examples + }) } /// Find all benches matching the given name in the workspace. @@ -174,7 +184,13 @@ pub struct Package { } impl Package { - fn find_paths(&self, m: WorkspaceFilter<'_>, kind: FoundKind, auto_path: &Path, auto_find: fn(&Package) -> bool) -> Result> { + fn find_paths( + &self, + m: WorkspaceFilter<'_>, + kind: FoundKind, + auto_path: &Path, + auto_find: fn(&Package) -> bool, + ) -> Result> { let mut output = Vec::new(); if let (Some(path), true) = (&self.root, auto_find(self)) { @@ -215,7 +231,9 @@ impl Package { /// Find all examples matching the given name in the workspace. pub fn find_examples(&self, m: WorkspaceFilter<'_>) -> Result> { - self.find_paths(m, FoundKind::Example, Path::new(EXAMPLES), |p| p.auto_examples) + self.find_paths(m, FoundKind::Example, Path::new(EXAMPLES), |p| { + p.auto_examples + }) } /// Find all benches matching the given name in the workspace. @@ -233,9 +251,13 @@ pub(crate) struct Loader<'a> { } impl<'a> Loader<'a> { - pub(crate) fn new(id: SourceId, sources: &'a mut Sources, diagnostics: &'a mut Diagnostics, - source_loader: &'a mut dyn SourceLoader, - manifest: &'a mut Manifest) -> Self { + pub(crate) fn new( + id: SourceId, + sources: &'a mut Sources, + diagnostics: &'a mut Diagnostics, + source_loader: &'a mut dyn SourceLoader, + manifest: &'a mut Manifest, + ) -> Self { Self { id, sources, @@ -248,7 +270,10 @@ impl<'a> Loader<'a> { /// Load a manifest. pub(crate) fn load_manifest(&mut self) -> Result<()> { let Some(source) = self.sources.get(self.id) else { - self.fatal(WorkspaceError::new(Span::empty(), WorkspaceErrorKind::MissingSourceId { source_id: self.id }))?; + self.fatal(WorkspaceError::new( + Span::empty(), + WorkspaceErrorKind::MissingSourceId { source_id: self.id }, + ))?; return Ok(()); }; @@ -265,7 +290,10 @@ impl<'a> Loader<'a> { } }; - let root = source.path().and_then(|p| p.parent().map(TryToOwned::try_to_owned)).transpose()?; + let root = source + .path() + .and_then(|p| p.parent().map(TryToOwned::try_to_owned)) + .transpose()?; let root = root.as_deref(); let Some((mut table, _)) = self.ensure_table(value)? else { @@ -273,14 +301,24 @@ impl<'a> Loader<'a> { }; // If manifest is a package, add it here. - if let Some((package, span)) = table.remove("package").map(|value| self.ensure_table(value)).transpose()?.flatten() { + if let Some((package, span)) = table + .remove("package") + .map(|value| self.ensure_table(value)) + .transpose()? + .flatten() + { if let Some(package) = self.load_package(package, span, root)? { self.manifest.packages.try_push(package)?; } } // Load the [workspace] section. - if let Some((mut table, span)) = table.remove("workspace").map(|value| self.ensure_table(value)).transpose()?.flatten() { + if let Some((mut table, span)) = table + .remove("workspace") + .map(|value| self.ensure_table(value)) + .transpose()? + .flatten() + { match &root { Some(root) => { if let Some(members) = self.load_members(&mut table, root)? { @@ -288,9 +326,12 @@ impl<'a> Loader<'a> { self.load_member(span, &path)?; } } - }, + } None => { - self.fatal(WorkspaceError::new(span, WorkspaceErrorKind::MissingManifestPath))?; + self.fatal(WorkspaceError::new( + span, + WorkspaceErrorKind::MissingManifestPath, + ))?; } } @@ -302,7 +343,11 @@ impl<'a> Loader<'a> { } /// Load members from the given workspace configuration. - fn load_members(&mut self, table: &mut Table, root: &Path) -> Result>> { + fn load_members( + &mut self, + table: &mut Table, + root: &Path, + ) -> Result>> { let Some(members) = table.remove("members") else { return Ok(None); }; @@ -333,7 +378,13 @@ impl<'a> Loader<'a> { /// /// Currently only supports expanding `*` and required interacting with the /// filesystem. - fn glob_relative_path(&mut self, output: &mut Vec<(Span, PathBuf)>, span: Span, member: &RelativePath, root: &Path) -> Result<()> { + fn glob_relative_path( + &mut self, + output: &mut Vec<(Span, PathBuf)>, + span: Span, + member: &RelativePath, + root: &Path, + ) -> Result<()> { let glob = glob::Glob::new(root, member)?; for m in glob.matcher()? { @@ -354,14 +405,22 @@ impl<'a> Loader<'a> { } /// Helper to convert an [io::Error] into a [WorkspaceErrorKind::SourceError]. - fn glob_error(&mut self, span: Span, path: &Path, result: Result) -> alloc::Result> { + fn glob_error( + &mut self, + span: Span, + path: &Path, + result: Result, + ) -> alloc::Result> { Ok(match result { Ok(result) => Some(result), Err(error) => { - self.fatal(WorkspaceError::new(span, WorkspaceErrorKind::GlobError { - path: path.try_into()?, - error, - }))?; + self.fatal(WorkspaceError::new( + span, + WorkspaceErrorKind::GlobError { + path: path.try_into()?, + error, + }, + ))?; None } @@ -386,7 +445,12 @@ impl<'a> Loader<'a> { } /// Load a package from a value. - fn load_package(&mut self, mut table: Table, span: Span, root: Option<&Path>) -> alloc::Result> { + fn load_package( + &mut self, + mut table: Table, + span: Span, + root: Option<&Path>, + ) -> alloc::Result> { let name = self.field(&mut table, span, "name")?; let version = self.field(&mut table, span, "version")?; self.ensure_empty(table)?; @@ -410,7 +474,12 @@ impl<'a> Loader<'a> { fn ensure_empty(&mut self, table: Table) -> alloc::Result<()> { for (key, _) in table { let span = Spanned::span(&key); - self.fatal(WorkspaceError::new(span, WorkspaceErrorKind::UnsupportedKey { key: key.get_ref().as_str().try_into()? }))?; + self.fatal(WorkspaceError::new( + span, + WorkspaceErrorKind::UnsupportedKey { + key: key.get_ref().as_str().try_into()?, + }, + ))?; } Ok(()) @@ -445,15 +514,21 @@ impl<'a> Loader<'a> { } /// Helper to load a single field. - fn field(&mut self, table: &mut Table, span: Span, field: &'static str) -> alloc::Result> where T: for<'de> Deserialize<'de> { + fn field( + &mut self, + table: &mut Table, + span: Span, + field: &'static str, + ) -> alloc::Result> + where + T: for<'de> Deserialize<'de>, + { Ok(match table.remove(field) { - Some(value) => { - match deserialize(value) { - Ok(value) => Some(value), - Err(error) => { - self.fatal(error)?; - None - } + Some(value) => match deserialize(value) { + Ok(value) => Some(value), + Err(error) => { + self.fatal(error)?; + None } }, None => { @@ -471,7 +546,10 @@ impl<'a> Loader<'a> { } /// Helper to load a single field. -fn deserialize(value: SpannedValue) -> Result where T: for<'de> Deserialize<'de> { +fn deserialize(value: SpannedValue) -> Result +where + T: for<'de> Deserialize<'de>, +{ let span = Spanned::span(&value); let f = key::to_key(value.get_ref()).map_err(|e| WorkspaceError::new(span, e))?; let deserializer = f.into_deserializer(); @@ -487,40 +565,39 @@ fn find_rune_files(path: &Path) -> Result return Err(e.into()), }; - Ok(iter::from_fn(move || { - loop { - let e = dir.as_mut()?.next()?; + Ok(iter::from_fn(move || loop { + let e = dir.as_mut()?.next()?; - let e = match e { - Ok(e) => e, - Err(err) => return Some(Err(err.into())), - }; + let e = match e { + Ok(e) => e, + Err(err) => return Some(Err(err.into())), + }; - let m = match e.metadata() { - Ok(m) => m, - Err(err) => return Some(Err(err.into())), - }; + let m = match e.metadata() { + Ok(m) => m, + Err(err) => return Some(Err(err.into())), + }; - if !m.is_file() { - continue; - } + if !m.is_file() { + continue; + } - let path = e.path(); + let path = e.path(); - let (Some(name), Some(ext)) = (path.file_stem().and_then(OsStr::to_str), path.extension()) else { - continue; - }; + let (Some(name), Some(ext)) = (path.file_stem().and_then(OsStr::to_str), path.extension()) + else { + continue; + }; - if ext != OsStr::new("rn") { - continue; - } + if ext != OsStr::new("rn") { + continue; + } - let name = match String::try_from(name) { - Ok(name) => name, - Err(error) => return Some(Err(error.into())), - }; + let name = match String::try_from(name) { + Ok(name) => name, + Err(error) => return Some(Err(error.into())), + }; - return Some(Ok((path, name))); - } + return Some(Ok((path, name))); })) } diff --git a/crates/rune/src/workspace/source_loader.rs b/crates/rune/src/workspace/source_loader.rs index 95cde4ca8..fea2c97d0 100644 --- a/crates/rune/src/workspace/source_loader.rs +++ b/crates/rune/src/workspace/source_loader.rs @@ -1,9 +1,9 @@ use std::path::Path; use crate::ast::Span; -use crate::Source; -use crate::workspace::WorkspaceError; use crate::compile::WithSpan; +use crate::workspace::WorkspaceError; +use crate::Source; use super::WorkspaceErrorKind; diff --git a/crates/rune/src/workspace/spanned_value.rs b/crates/rune/src/workspace/spanned_value.rs index 18eaade39..fc44d40cb 100644 --- a/crates/rune/src/workspace/spanned_value.rs +++ b/crates/rune/src/workspace/spanned_value.rs @@ -254,7 +254,10 @@ impl From<&str> for Value { } } -impl From> for Value where V: Into { +impl From> for Value +where + V: Into, +{ fn from(val: Vec) -> Value { Value::Array(val.into_iter().map(|v| v.into()).collect()) } @@ -447,7 +450,10 @@ impl<'de> de::Deserialize<'de> for Value { Ok(Value::Integer(value)) } - fn visit_u64(self, value: u64) -> Result where E: de::Error { + fn visit_u64(self, value: u64) -> Result + where + E: de::Error, + { if value <= i64::max_value() as u64 { Ok(Value::Integer(value as i64)) } else { @@ -467,11 +473,17 @@ impl<'de> de::Deserialize<'de> for Value { Ok(Value::Float(value)) } - fn visit_str(self, value: &str) -> Result where E: de::Error { + fn visit_str(self, value: &str) -> Result + where + E: de::Error, + { Ok(Value::String(value.to_string())) } - fn visit_string(self, value: String) -> Result where E: de::Error { + fn visit_string(self, value: String) -> Result + where + E: de::Error, + { Ok(Value::String(value)) } @@ -577,24 +589,26 @@ impl de::Error for OptError { } } -struct LayerDeserializer<'de, D: de::Deserializer<'de>>(D, std::marker::PhantomData<&'de()>); +struct LayerDeserializer<'de, D: de::Deserializer<'de>>(D, std::marker::PhantomData<&'de ()>); impl<'de, D: de::Deserializer<'de>> de::Deserializer<'de> for LayerDeserializer<'de, D> { type Error = OptError; fn deserialize_any(self, visitor: V) -> Result where - V: de::Visitor<'de> + V: de::Visitor<'de>, { - self.0.deserialize_any(visitor).map_err(|e| OptError(Some(e))) + self.0 + .deserialize_any(visitor) + .map_err(|e| OptError(Some(e))) } fn deserialize_struct( self, name: &'static str, fields: &'static [&'static str], - visitor: V + visitor: V, ) -> Result where - V: de::Visitor<'de> + V: de::Visitor<'de>, { let wrapped_visitor = DatetimeOrTableWrapper(visitor); match self.0.deserialize_struct(name, fields, wrapped_visitor) { @@ -620,7 +634,7 @@ impl<'de> de::DeserializeSeed<'de> for DatetimeOrTable { D: de::Deserializer<'de>, { let deserializer = LayerDeserializer(deserializer, std::marker::PhantomData); - let res = as de::Deserialize<'_>>::deserialize(deserializer); + let res = as de::Deserialize<'_>>::deserialize(deserializer); match res { Ok(v) => Ok(Some(v)), Err(OptError(None)) => Ok(None), diff --git a/crates/rune/tests/ui/install_with_compat.rs b/crates/rune/tests/ui/install_with_compat.rs index f2dbd42a9..e087cb5c1 100644 --- a/crates/rune/tests/ui/install_with_compat.rs +++ b/crates/rune/tests/ui/install_with_compat.rs @@ -3,8 +3,6 @@ use rune::Any; // Generates a warning that the path should no longer be using a string literal. #[derive(Any)] #[rune(install_with = "foo::bar")] -struct Struct { -} +struct Struct {} -fn main() { -} +fn main() {}