Skip to main content

rune/workspace/
manifest.rs

1use std::ffi::OsStr;
2use std::fmt;
3use std::io;
4use std::path::{Path, PathBuf};
5
6use anyhow::{anyhow, Result};
7use relative_path::{RelativePath, RelativePathBuf};
8use semver::Version;
9use serde::de::IntoDeserializer;
10use serde::Deserialize;
11use serde_hashkey as key;
12
13use crate as rune;
14use crate::alloc::prelude::*;
15use crate::alloc::{self, HashMap, String, Vec};
16use crate::ast::{Span, Spanned};
17use crate::source::is_declaration_name;
18use crate::workspace::spanned_value::{Array, SpannedValue, Table, Value};
19use crate::workspace::{
20    glob, Diagnostics, SourceLoader, WorkspaceError, WorkspaceErrorKind, MANIFEST_FILE,
21};
22use crate::{SourceId, Sources};
23
24/// A workspace filter which in combination with [Manifest::find_by_kind]
25/// can be used to selectively find things in the workspace.
26#[derive(Debug, Clone, Copy)]
27#[non_exhaustive]
28pub enum WorkspaceFilter<'a> {
29    /// Look for one specific named thing.
30    Name(&'a str),
31    /// Look for all things.
32    All,
33}
34
35/// The kind of a found entry.
36#[derive(Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
37#[non_exhaustive]
38pub enum FoundKind {
39    /// The found entry is a binary.
40    Binary,
41    /// The found entry is a source file.
42    Library,
43    /// The found entry is a test.
44    Test,
45    /// The found entry is an example.
46    Example,
47    /// The found entry is a benchmark.
48    Bench,
49}
50
51impl FoundKind {
52    fn all() -> [Self; 5] {
53        [
54            Self::Binary,
55            Self::Library,
56            Self::Test,
57            Self::Example,
58            Self::Bench,
59        ]
60    }
61}
62
63impl fmt::Display for FoundKind {
64    #[inline]
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        match self {
67            FoundKind::Library => "lib".fmt(f),
68            FoundKind::Binary => "bin".fmt(f),
69            FoundKind::Test => "test".fmt(f),
70            FoundKind::Example => "example".fmt(f),
71            FoundKind::Bench => "bench".fmt(f),
72        }
73    }
74}
75
76/// A found item in the workspace.
77#[derive(Debug, TryClone)]
78#[non_exhaustive]
79pub struct Found {
80    /// The kind found.
81    #[try_clone(copy)]
82    pub kind: FoundKind,
83    /// A found path that can be built.
84    pub path: PathBuf,
85    /// Name of the found thing.
86    pub name: String,
87}
88
89/// A found item in the workspace associated with a package.
90#[derive(Debug, TryClone)]
91#[non_exhaustive]
92pub struct FoundPackage<'a> {
93    /// A found path that can be built.
94    pub found: Found,
95    /// Index of the package build belongs to.
96    pub package: &'a Package,
97}
98
99impl WorkspaceFilter<'_> {
100    fn matches(self, name: &str) -> bool {
101        match self {
102            WorkspaceFilter::Name(expected) => name == expected,
103            WorkspaceFilter::All => true,
104        }
105    }
106}
107
108impl<T> Spanned for toml::Spanned<T> {
109    #[inline]
110    fn span(&self) -> Span {
111        let range = toml::Spanned::span(self);
112        Span::new(range.start, range.end)
113    }
114}
115
116/// The manifest of a workspace.
117#[derive(Default, Debug)]
118#[non_exhaustive]
119pub struct Manifest {
120    /// List of packages found.
121    pub packages: Vec<Package>,
122}
123
124impl Manifest {
125    /// Find all entrypoints of a specific kind.
126    pub fn find_by_kind(
127        &self,
128        filter: WorkspaceFilter<'_>,
129        kind: FoundKind,
130    ) -> Result<Vec<FoundPackage<'_>>> {
131        let mut output = Vec::new();
132
133        for package in self.packages.iter() {
134            for found in package.find_by_kind(filter, kind)? {
135                output.try_push(FoundPackage { found, package })?;
136            }
137        }
138
139        Ok(output)
140    }
141
142    /// Find every single entrypoint available.
143    pub fn find_all(&self, filter: WorkspaceFilter<'_>) -> Result<Vec<FoundPackage<'_>>> {
144        let mut output = Vec::new();
145        for kind in FoundKind::all() {
146            output.try_extend(self.find_by_kind(filter, kind)?)?;
147        }
148        Ok(output)
149    }
150}
151
152/// A single package.
153#[derive(Debug)]
154#[non_exhaustive]
155pub struct Package {
156    /// The name of the package.
157    pub name: String,
158    /// The version of the package..
159    pub version: Version,
160    /// The root of the package.
161    pub root: Option<PathBuf>,
162    /// Automatically detect binaries.
163    pub auto_bins: bool,
164    /// Automatically detect libraries.
165    pub auto_libs: bool,
166    /// Automatically detect tests.
167    pub auto_tests: bool,
168    /// Automatically detect examples.
169    pub auto_examples: bool,
170    /// Automatically detect benches.
171    pub auto_benches: bool,
172    /// The packages named in `[dependencies]`.
173    pub dependencies: Vec<Dependency>,
174    /// The declaration sources (`*.d.rn`) of the package itself and of every
175    /// package it depends on, directly or not, each once. These are compiled
176    /// beside each of the package's entry points.
177    pub declarations: Vec<PathBuf>,
178}
179
180/// A dependency of a package, as named in its `[dependencies]`.
181#[derive(Debug, TryClone)]
182#[non_exhaustive]
183pub struct Dependency {
184    /// The name the dependency is given in the manifest.
185    pub name: String,
186    /// The directory of the dependency, holding its `Rune.toml`.
187    pub root: PathBuf,
188}
189
190impl Package {
191    fn auto_find(&self, kind: FoundKind) -> bool {
192        match kind {
193            FoundKind::Binary => self.auto_bins,
194            FoundKind::Library => self.auto_libs,
195            FoundKind::Test => self.auto_tests,
196            FoundKind::Example => self.auto_examples,
197            FoundKind::Bench => self.auto_benches,
198        }
199    }
200
201    fn find_by_kind(&self, filter: WorkspaceFilter<'_>, kind: FoundKind) -> Result<Vec<Found>> {
202        match kind {
203            FoundKind::Binary => self.find_bins(filter),
204            FoundKind::Library => self
205                .find_lib(filter)
206                .and_then(|lib| lib.into_iter().try_collect().map_err(anyhow::Error::from)),
207            FoundKind::Test => self.find_tests(filter),
208            FoundKind::Bench => self.find_benches(filter),
209            FoundKind::Example => self.find_examples(filter),
210        }
211    }
212
213    /// Find every single entrypoint available.
214    pub fn find_all(&self, filter: WorkspaceFilter<'_>) -> Result<Vec<Found>> {
215        let mut output = Vec::new();
216        for kind in FoundKind::all() {
217            output.try_extend(self.find_by_kind(filter, kind)?)?;
218        }
219        Ok(output)
220    }
221
222    /// Find all binaries matching the given name in the package.
223    pub fn find_bins(&self, filter: WorkspaceFilter<'_>) -> Result<Vec<Found>> {
224        if !self.auto_find(FoundKind::Binary) {
225            return Ok(Vec::new());
226        }
227
228        let Some(root) = &self.root else {
229            return Ok(Vec::new());
230        };
231
232        let src_path = root.join("src");
233
234        let mut found = Vec::new();
235
236        let bin_entry_point = src_path.join("main.rn");
237        if bin_entry_point.exists() && bin_entry_point.is_file() && filter.matches(&self.name) {
238            found.try_push(Found {
239                kind: FoundKind::Binary,
240                path: bin_entry_point,
241                name: self.name.try_clone()?,
242            })?;
243        }
244
245        let bin_directory = src_path.join("bin");
246        if bin_directory.exists() && bin_directory.is_dir() {
247            for (path, name) in find_binary_entry_points(&bin_directory)? {
248                if filter.matches(&name) {
249                    found.try_push(Found {
250                        kind: FoundKind::Binary,
251                        path,
252                        name,
253                    })?;
254                }
255            }
256        }
257
258        Ok(found)
259    }
260
261    /// Find a library entry point matching the given name in the package, if one exists.
262    pub fn find_lib(&self, filter: WorkspaceFilter<'_>) -> Result<Option<Found>> {
263        if !self.auto_find(FoundKind::Library) {
264            return Ok(None);
265        }
266
267        let Some(root) = &self.root else {
268            return Ok(None);
269        };
270
271        let src_path = root.join("src");
272
273        let mut lib = None;
274
275        let lib_entry_point = src_path.join("lib.rn");
276        if lib_entry_point.exists() && lib_entry_point.is_file() {
277            if !filter.matches(&self.name) {
278                return Ok(None);
279            }
280
281            lib = Some(Found {
282                kind: FoundKind::Library,
283                path: lib_entry_point,
284                name: self.name.try_clone()?,
285            });
286        }
287
288        Ok(lib)
289    }
290
291    fn find_in_directory(
292        &self,
293        filter: WorkspaceFilter<'_>,
294        kind: FoundKind,
295        directory: &str,
296    ) -> Result<Vec<Found>> {
297        if !self.auto_find(kind) {
298            return Ok(Vec::new());
299        }
300
301        let Some(root) = &self.root else {
302            return Ok(Vec::new());
303        };
304
305        let directory_path = root.join(directory);
306        if !directory_path.exists() || !directory_path.is_dir() {
307            return Ok(Vec::new());
308        }
309
310        let mut found = Vec::new();
311
312        for (path, name) in find_binary_entry_points(&directory_path)? {
313            if filter.matches(&name) {
314                found.try_push(Found { kind, path, name })?;
315            }
316        }
317
318        Ok(found)
319    }
320
321    /// Find all tests associated with the given base name.
322    pub fn find_tests(&self, filter: WorkspaceFilter<'_>) -> Result<Vec<Found>> {
323        self.find_in_directory(filter, FoundKind::Test, "tests")
324    }
325
326    /// Find all examples matching the given name in the package.
327    pub fn find_examples(&self, filter: WorkspaceFilter<'_>) -> Result<Vec<Found>> {
328        self.find_in_directory(filter, FoundKind::Example, "examples")
329    }
330
331    /// Find all benches matching the given name in the workspace.
332    pub fn find_benches(&self, filter: WorkspaceFilter<'_>) -> Result<Vec<Found>> {
333        self.find_in_directory(filter, FoundKind::Bench, "benches")
334    }
335}
336
337/// Loader for manifests
338pub struct Loader<'a> {
339    id: SourceId,
340    sources: &'a mut Sources,
341    diagnostics: &'a mut Diagnostics,
342    source_loader: &'a mut dyn SourceLoader,
343    manifest: &'a mut Manifest,
344    /// The roots of the packages whose dependencies are being loaded, from
345    /// the outermost in, which is what a cycle is noticed by.
346    loading: Vec<PathBuf>,
347    /// The declaration sources a dependency was found to bring, by its root,
348    /// so that a package several others depend on is loaded once.
349    resolved: HashMap<PathBuf, Vec<PathBuf>>,
350}
351
352impl<'a> Loader<'a> {
353    pub(crate) fn new(
354        id: SourceId,
355        sources: &'a mut Sources,
356        diagnostics: &'a mut Diagnostics,
357        source_loader: &'a mut dyn SourceLoader,
358        manifest: &'a mut Manifest,
359    ) -> Self {
360        Self {
361            id,
362            sources,
363            diagnostics,
364            source_loader,
365            manifest,
366            loading: Vec::new(),
367            resolved: HashMap::new(),
368        }
369    }
370
371    /// Parse the current source as a table, along with the directory it is
372    /// in if it has a path.
373    fn parse(&mut self) -> Result<Option<(Table, Option<PathBuf>)>> {
374        let Some(source) = self.sources.get(self.id) else {
375            self.fatal(WorkspaceError::new(
376                Span::empty(),
377                WorkspaceErrorKind::MissingSourceId { source_id: self.id },
378            ))?;
379            return Ok(None);
380        };
381
382        let value: SpannedValue = match toml::from_str(source.as_str()) {
383            Ok(value) => value,
384            Err(e) => {
385                let span = match e.span() {
386                    Some(span) => Span::new(span.start, span.end),
387                    None => Span::new(0, source.len()),
388                };
389
390                self.fatal(WorkspaceError::new(span, e))?;
391                return Ok(None);
392            }
393        };
394
395        let root = source
396            .path()
397            .and_then(|p| p.parent().map(TryToOwned::try_to_owned))
398            .transpose()?;
399
400        let Some((table, _)) = self.ensure_table(value)? else {
401            return Ok(None);
402        };
403
404        Ok(Some((table, root)))
405    }
406
407    /// Load a manifest.
408    pub(crate) fn load_manifest(&mut self) -> Result<()> {
409        let Some((mut table, root)) = self.parse()? else {
410            return Ok(());
411        };
412
413        let root = root.as_deref();
414        let has_package = table.contains_key("package");
415
416        // If manifest is a package, add it here.
417        let mut package = match table
418            .remove("package")
419            .map(|value| self.ensure_table(value))
420            .transpose()?
421            .flatten()
422        {
423            Some((package, span)) => self.load_package(package, span, root)?,
424            None => None,
425        };
426
427        // A package's own declaration sources come first, the common case
428        // being a project describing the host it is run in.
429        if let (Some(package), Some(root)) = (&mut package, root) {
430            package.declarations = self.find_declarations(root)?;
431        }
432
433        if let Some(value) = table.remove("dependencies") {
434            let span = Spanned::span(&value);
435
436            match (&mut package, root) {
437                (Some(package), Some(root)) => {
438                    let (dependencies, declarations) = self.load_dependencies(value, root)?;
439                    package.dependencies = dependencies;
440
441                    for path in declarations {
442                        if !package.declarations.contains(&path) {
443                            package.declarations.try_push(path)?;
444                        }
445                    }
446                }
447                // The package itself is broken, which has been reported.
448                (None, _) if has_package => {}
449                (None, _) => {
450                    self.fatal(WorkspaceError::new(
451                        span,
452                        WorkspaceErrorKind::DependenciesWithoutPackage,
453                    ))?;
454                }
455                (Some(..), None) => {
456                    self.fatal(WorkspaceError::new(
457                        span,
458                        WorkspaceErrorKind::MissingManifestPath,
459                    ))?;
460                }
461            }
462        }
463
464        if let Some(package) = package {
465            self.manifest.packages.try_push(package)?;
466        }
467
468        // Load the [workspace] section.
469        if let Some((mut table, span)) = table
470            .remove("workspace")
471            .map(|value| self.ensure_table(value))
472            .transpose()?
473            .flatten()
474        {
475            match &root {
476                Some(root) => {
477                    if let Some(members) = self.load_members(&mut table, root)? {
478                        for (span, path) in members {
479                            self.load_member(span, &path)?;
480                        }
481                    }
482                }
483                None => {
484                    self.fatal(WorkspaceError::new(
485                        span,
486                        WorkspaceErrorKind::MissingManifestPath,
487                    ))?;
488                }
489            }
490
491            self.ensure_empty(table)?;
492        }
493
494        self.ensure_empty(table)?;
495        Ok(())
496    }
497
498    /// Load members from the given workspace configuration.
499    fn load_members(
500        &mut self,
501        table: &mut Table,
502        root: &Path,
503    ) -> Result<Option<Vec<(Span, PathBuf)>>> {
504        let Some(members) = table.remove("members") else {
505            return Ok(None);
506        };
507
508        let Some((members, _)) = self.ensure_array(members)? else {
509            return Ok(None);
510        };
511
512        let mut output = Vec::new();
513
514        for value in members {
515            let span = Spanned::span(&value);
516
517            match deserialize::<RelativePathBuf>(value) {
518                Ok(member) => {
519                    self.glob_relative_path(&mut output, span, &member, root)?;
520                }
521                Err(error) => {
522                    self.fatal(error)?;
523                }
524            };
525        }
526
527        Ok(Some(output))
528    }
529
530    /// Glob a relative path.
531    ///
532    /// Currently only supports expanding `*` and required interacting with the
533    /// filesystem.
534    fn glob_relative_path(
535        &mut self,
536        output: &mut Vec<(Span, PathBuf)>,
537        span: Span,
538        member: &RelativePath,
539        root: &Path,
540    ) -> Result<()> {
541        let glob = glob::Glob::new(root, member)?;
542
543        for m in glob.matcher()? {
544            let Some(mut path) = self.glob_error(span, root, m)? else {
545                continue;
546            };
547
548            path.push(MANIFEST_FILE);
549
550            if !path.is_file() {
551                continue;
552            }
553
554            output.try_push((span, path))?;
555        }
556
557        Ok(())
558    }
559
560    /// Helper to convert an [io::Error] into a [WorkspaceErrorKind::SourceError].
561    fn glob_error<T>(
562        &mut self,
563        span: Span,
564        path: &Path,
565        result: Result<T, glob::GlobError>,
566    ) -> alloc::Result<Option<T>> {
567        Ok(match result {
568            Ok(result) => Some(result),
569            Err(error) => {
570                self.fatal(WorkspaceError::new(
571                    span,
572                    WorkspaceErrorKind::GlobError {
573                        path: path.try_into()?,
574                        error,
575                    },
576                ))?;
577
578                None
579            }
580        })
581    }
582
583    /// Try to load the given path as a member in the current manifest.
584    fn load_member(&mut self, span: Span, path: &Path) -> Result<()> {
585        let source = match self.source_loader.load(span, path) {
586            Ok(source) => source,
587            Err(error) => {
588                self.fatal(error)?;
589                return Ok(());
590            }
591        };
592
593        let id = self.sources.insert(source)?;
594        let old = std::mem::replace(&mut self.id, id);
595        self.load_manifest()?;
596        self.id = old;
597        Ok(())
598    }
599
600    /// Load the `[dependencies]` of the package rooted at `root`, returning
601    /// the dependencies and the declaration sources they bring between them.
602    fn load_dependencies(
603        &mut self,
604        value: SpannedValue,
605        root: &Path,
606    ) -> Result<(Vec<Dependency>, Vec<PathBuf>)> {
607        let mut dependencies = Vec::new();
608        let mut declarations = Vec::new();
609
610        let Some((table, _)) = self.ensure_table(value)? else {
611            return Ok((dependencies, declarations));
612        };
613
614        self.loading.try_push(canonical(root)?)?;
615
616        for (key, value) in table {
617            let name = String::try_from(key.get_ref().as_str())?;
618            let span = Spanned::span(&value);
619
620            let Some(path) = self.dependency_path(&name, value)? else {
621                continue;
622            };
623
624            let dir = path.to_path(root);
625            let manifest = dir.join(MANIFEST_FILE);
626
627            if !manifest.is_file() {
628                self.fatal(WorkspaceError::new(
629                    span,
630                    WorkspaceErrorKind::MissingDependency {
631                        name,
632                        path: manifest.as_path().try_into()?,
633                    },
634                ))?;
635                continue;
636            }
637
638            let dir = canonical(&dir)?;
639
640            if self.loading.contains(&dir) {
641                self.fatal(WorkspaceError::new(
642                    span,
643                    WorkspaceErrorKind::DependencyCycle { name },
644                ))?;
645                continue;
646            }
647
648            let found = match self.resolved.get(&dir) {
649                Some(found) => found.try_clone()?,
650                None => {
651                    let found = self.load_dependency(span, &manifest, &dir)?;
652                    self.resolved
653                        .try_insert(dir.try_clone()?, found.try_clone()?)?;
654                    found
655                }
656            };
657
658            for path in found {
659                if !declarations.contains(&path) {
660                    declarations.try_push(path)?;
661                }
662            }
663
664            dependencies.try_push(Dependency { name, root: dir })?;
665        }
666
667        self.loading.pop();
668        Ok((dependencies, declarations))
669    }
670
671    /// The path of a dependency, which is the only kind there is.
672    fn dependency_path(
673        &mut self,
674        name: &str,
675        value: SpannedValue,
676    ) -> alloc::Result<Option<RelativePathBuf>> {
677        let span = Spanned::span(&value);
678
679        let path = match value.into_inner() {
680            Value::Table(mut table) => match table.remove("path") {
681                Some(path) => {
682                    self.ensure_empty(table)?;
683                    Some(path)
684                }
685                None => None,
686            },
687            _ => None,
688        };
689
690        let Some(path) = path else {
691            self.fatal(WorkspaceError::new(
692                span,
693                WorkspaceErrorKind::UnsupportedDependency {
694                    name: name.try_to_owned()?,
695                },
696            ))?;
697            return Ok(None);
698        };
699
700        match deserialize::<RelativePathBuf>(path) {
701            Ok(path) => Ok(Some(path)),
702            Err(error) => {
703                self.fatal(error)?;
704                Ok(None)
705            }
706        }
707    }
708
709    /// Load the dependency whose manifest is at `path` and whose root is
710    /// `root`, returning the declaration sources it brings: its own and those
711    /// of its dependencies.
712    fn load_dependency(&mut self, span: Span, path: &Path, root: &Path) -> Result<Vec<PathBuf>> {
713        let source = match self.source_loader.load(span, path) {
714            Ok(source) => source,
715            Err(error) => {
716                self.fatal(error)?;
717                return Ok(Vec::new());
718            }
719        };
720
721        let id = self.sources.insert(source)?;
722        let old = std::mem::replace(&mut self.id, id);
723        let result = self.load_dependency_manifest(root);
724        self.id = old;
725        result
726    }
727
728    fn load_dependency_manifest(&mut self, root: &Path) -> Result<Vec<PathBuf>> {
729        let Some((mut table, _)) = self.parse()? else {
730            return Ok(Vec::new());
731        };
732
733        // A dependency is still checked for being a valid package, but it is
734        // not a member of the workspace being loaded, so none of its entry
735        // points are, and a `[workspace]` it has is its own business.
736        match table
737            .remove("package")
738            .map(|value| self.ensure_table(value))
739            .transpose()?
740            .flatten()
741        {
742            Some((package, span)) => {
743                self.load_package(package, span, Some(root))?;
744            }
745            None => {
746                self.fatal(WorkspaceError::missing_field(Span::empty(), "package"))?;
747            }
748        }
749
750        _ = table.remove("workspace");
751
752        let transitive = match table.remove("dependencies") {
753            Some(value) => self.load_dependencies(value, root)?.1,
754            None => Vec::new(),
755        };
756
757        self.ensure_empty(table)?;
758
759        let mut declarations = self.find_declarations(root)?;
760
761        for path in transitive {
762            if !declarations.contains(&path) {
763                declarations.try_push(path)?;
764            }
765        }
766
767        Ok(declarations)
768    }
769
770    /// The declaration sources in the package rooted at `root`, reporting a
771    /// directory which cannot be read as a manifest diagnostic.
772    fn find_declarations(&mut self, root: &Path) -> Result<Vec<PathBuf>> {
773        // A manifest loaded as `Rune.toml` has an empty directory, which is
774        // the current one.
775        let dir = if root.as_os_str().is_empty() {
776            Path::new(".")
777        } else {
778            root
779        };
780
781        match find_declarations(dir) {
782            Ok(declarations) => Ok(declarations),
783            Err(error) => {
784                self.fatal(WorkspaceError::new(
785                    Span::empty(),
786                    WorkspaceErrorKind::ReadDeclarations {
787                        path: root.try_into()?,
788                        error,
789                    },
790                ))?;
791                Ok(Vec::new())
792            }
793        }
794    }
795
796    /// Load a package from a value.
797    fn load_package(
798        &mut self,
799        mut table: Table,
800        span: Span,
801        root: Option<&Path>,
802    ) -> alloc::Result<Option<Package>> {
803        let name = self.field(&mut table, span, "name")?;
804        let version = self.field(&mut table, span, "version")?;
805        self.ensure_empty(table)?;
806
807        let (Some(name), Some(version)) = (name, version) else {
808            return Ok(None);
809        };
810
811        Ok(Some(Package {
812            name,
813            version,
814            root: root.map(|p| p.into()),
815            auto_libs: true,
816            auto_bins: true,
817            auto_tests: true,
818            auto_examples: true,
819            auto_benches: true,
820            dependencies: Vec::new(),
821            declarations: Vec::new(),
822        }))
823    }
824
825    /// Ensure that a table is empty and mark any additional elements as erroneous.
826    fn ensure_empty(&mut self, table: Table) -> alloc::Result<()> {
827        for (key, _) in table {
828            let span = Spanned::span(&key);
829            self.fatal(WorkspaceError::new(
830                span,
831                WorkspaceErrorKind::UnsupportedKey {
832                    key: key.get_ref().as_str().try_into()?,
833                },
834            ))?;
835        }
836
837        Ok(())
838    }
839
840    /// Ensure that value is a table.
841    fn ensure_table(&mut self, value: SpannedValue) -> alloc::Result<Option<(Table, Span)>> {
842        let span = Spanned::span(&value);
843
844        Ok(match value.into_inner() {
845            Value::Table(table) => Some((table, span)),
846            _ => {
847                let error = WorkspaceError::new(span, WorkspaceErrorKind::ExpectedTable);
848                self.fatal(error)?;
849                None
850            }
851        })
852    }
853
854    /// Coerce into an array or error.
855    fn ensure_array(&mut self, value: SpannedValue) -> alloc::Result<Option<(Array, Span)>> {
856        let span = Spanned::span(&value);
857
858        Ok(match value.into_inner() {
859            Value::Array(array) => Some((array, span)),
860            _ => {
861                let error = WorkspaceError::expected_array(span);
862                self.fatal(error)?;
863                None
864            }
865        })
866    }
867
868    /// Helper to load a single field.
869    fn field<T>(
870        &mut self,
871        table: &mut Table,
872        span: Span,
873        field: &'static str,
874    ) -> alloc::Result<Option<T>>
875    where
876        T: for<'de> Deserialize<'de>,
877    {
878        Ok(match table.remove(field) {
879            Some(value) => match deserialize(value) {
880                Ok(value) => Some(value),
881                Err(error) => {
882                    self.fatal(error)?;
883                    None
884                }
885            },
886            None => {
887                let error = WorkspaceError::missing_field(span, field);
888                self.fatal(error)?;
889                None
890            }
891        })
892    }
893
894    /// Report a fatal diagnostic.
895    fn fatal(&mut self, error: WorkspaceError) -> alloc::Result<()> {
896        self.diagnostics.fatal(self.id, error)
897    }
898}
899
900/// Helper to load a single field.
901fn deserialize<T>(value: SpannedValue) -> Result<T, WorkspaceError>
902where
903    T: for<'de> Deserialize<'de>,
904{
905    let span = Spanned::span(&value);
906    let f = key::to_key(value.get_ref()).map_err(|e| WorkspaceError::new(span, e))?;
907    let deserializer = f.into_deserializer();
908    let value = T::deserialize(deserializer).map_err(|e| WorkspaceError::new(span, e))?;
909    Ok(value)
910}
911
912/// Find binary entry points in the given directory
913fn find_binary_entry_points(path: &Path) -> Result<Vec<(PathBuf, String)>> {
914    let mut entry_points = Vec::new();
915
916    for entry in path.read_dir()? {
917        let entry = entry?;
918        let file_type = entry.file_type()?;
919        // A declaration source is compiled beside the entry points rather
920        // than being one.
921        if file_type.is_file()
922            && entry.path().extension() == Some(OsStr::new("rn"))
923            && !is_declaration_name(&entry.file_name().to_string_lossy())
924        {
925            entry_points.try_push((
926                entry.path(),
927                entry
928                    .path()
929                    .file_stem()
930                    .ok_or_else(|| anyhow!("failed to find file stem for {:?}", entry.path()))?
931                    .to_string_lossy()
932                    .try_to_owned()?,
933            ))?;
934        } else if file_type.is_dir() {
935            let main = entry.path().join("main.rn");
936            if main.exists() && main.is_file() {
937                entry_points.try_push((
938                    main,
939                    entry
940                        .path()
941                        .file_name()
942                        .ok_or_else(|| {
943                            anyhow!(
944                                "failed to find trailing directory name for {:?}",
945                                entry.path()
946                            )
947                        })?
948                        .to_string_lossy()
949                        .try_to_owned()?,
950                ))?;
951            }
952        }
953    }
954
955    Ok(entry_points)
956}
957
958/// The canonical form of `path`, so that two ways of naming one package are
959/// noticed as the same, or `path` itself if it cannot be resolved.
960fn canonical(path: &Path) -> alloc::Result<PathBuf> {
961    // A manifest loaded as `Rune.toml` has an empty directory, which is the
962    // current one.
963    let path = if path.as_os_str().is_empty() {
964        Path::new(".")
965    } else {
966        path
967    };
968
969    match path.canonicalize() {
970        Ok(path) => Ok(path),
971        Err(..) => path.try_to_owned(),
972    }
973}
974
975/// Find the declaration sources (`*.d.rn`) in the package rooted at `root`,
976/// in a stable order.
977///
978/// Hidden directories, `target` and directories holding a package of their own
979/// are not looked in, and symbolic links are not followed, so that a link back
980/// up the tree does not make the walk endless.
981fn find_declarations(root: &Path) -> io::Result<Vec<PathBuf>> {
982    let mut output = Vec::new();
983    let mut queue = Vec::new();
984    queue
985        .try_push(root.to_path_buf())
986        .map_err(io::Error::other)?;
987
988    while let Some(dir) = queue.pop() {
989        for entry in dir.read_dir()? {
990            let entry = entry?;
991            let file_type = entry.file_type()?;
992            let name = entry.file_name();
993            let name = name.to_string_lossy();
994            let path = entry.path();
995
996            if file_type.is_dir() {
997                if name.starts_with('.') || name == "target" || path.join(MANIFEST_FILE).is_file() {
998                    continue;
999                }
1000
1001                queue.try_push(path).map_err(io::Error::other)?;
1002            } else if file_type.is_file() && is_declaration_name(&name) {
1003                output.try_push(path).map_err(io::Error::other)?;
1004            }
1005        }
1006    }
1007
1008    output.sort();
1009    Ok(output)
1010}