Skip to main content

lisette_syntax/program/
package.rs

1use ecow::EcoString;
2use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
3
4use super::definition::{Definition, Visibility};
5use super::file::File;
6use crate::types::Symbol;
7
8pub type PackageId = String;
9
10pub fn is_internal_package_id(id: &str) -> bool {
11    id == "prelude" || id == "**test_prelude" || id == "**nominal" || id.starts_with("go:")
12}
13
14#[derive(Debug, Clone)]
15pub struct Package {
16    pub id: String,
17    /// file ID -> file. Source and declaration files are classified by [`File::is_d_lis`].
18    pub files: HashMap<u32, File>,
19    /// qualified name -> definition
20    pub definitions: HashMap<Symbol, Definition>,
21    /// Set when an import cycle keeps the package out of inference: nothing
22    /// registers its files, so its exports are read from syntax.
23    pub uninferred_exports: Option<UninferredExports>,
24}
25
26#[derive(Debug, Clone)]
27pub enum UninferredExports {
28    /// Read from the syntax of the package's files.
29    Known(HashSet<EcoString>),
30    /// A file did not parse, so its declarations cannot be read.
31    Unreadable,
32}
33
34impl UninferredExports {
35    pub fn may_contain(&self, member: &str) -> bool {
36        match self {
37            Self::Known(names) => names.contains(member),
38            Self::Unreadable => true,
39        }
40    }
41}
42
43impl Package {
44    pub fn new(id: &str) -> Package {
45        Package {
46            id: id.to_string(),
47            files: Default::default(),
48            definitions: Default::default(),
49            uninferred_exports: None,
50        }
51    }
52
53    pub fn nominal() -> Package {
54        Package::new("**nominal")
55    }
56
57    pub fn is_public(&self, qualified_name: &str) -> bool {
58        if let Some(definition) = self.definitions.get(qualified_name) {
59            return definition.visibility == Visibility::Public;
60        }
61
62        false
63    }
64
65    pub fn get_file(&self, file_id: u32) -> Option<&File> {
66        self.files.get(&file_id)
67    }
68
69    pub fn file_ids(&self) -> impl Iterator<Item = u32> + '_ {
70        self.source_file_entries().map(|(file_id, _)| *file_id)
71    }
72
73    pub fn source_files(&self) -> impl Iterator<Item = &File> {
74        self.files.values().filter(|file| !file.is_d_lis())
75    }
76
77    pub fn source_file_entries(&self) -> impl Iterator<Item = (&u32, &File)> {
78        self.files.iter().filter(|(_, file)| !file.is_d_lis())
79    }
80
81    pub fn typedef_files(&self) -> impl Iterator<Item = &File> {
82        self.files.values().filter(|file| file.is_d_lis())
83    }
84
85    pub fn is_typedef(&self, file_id: u32) -> bool {
86        self.files.get(&file_id).is_some_and(File::is_d_lis)
87    }
88
89    pub fn is_empty_stub(&self) -> bool {
90        self.files.is_empty() && self.definitions.is_empty()
91    }
92}