Skip to main content

miden_debug/
linker.rs

1use std::{
2    borrow::Cow,
3    fmt,
4    path::{Path as FsPath, PathBuf},
5    str::FromStr,
6    sync::Arc,
7};
8
9use miden_assembly::SourceManager;
10use miden_assembly_syntax::{
11    Library, Path as LibraryPath,
12    diagnostics::{IntoDiagnostic, Report},
13};
14
15use crate::config::DebuggerConfig;
16
17/// A library requested by the user to be linked against during compilation
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct LinkLibrary {
20    /// The name of the library.
21    ///
22    /// If requested by name, e.g. `-l std`, the name is used as given.
23    ///
24    /// If requested by path, e.g. `-l ./target/libs/miden-base.masl`, then the name of the library
25    /// will be the basename of the file specified in the path.
26    pub name: Cow<'static, str>,
27    /// If specified, the path from which this library should be loaded
28    pub path: Option<PathBuf>,
29    /// The kind of library to load.
30    ///
31    /// By default this is assumed to be a `.masp` package, but the kind will be detected based on
32    /// how it is requested by the user. It may also be specified explicitly by the user.
33    pub kind: LibraryKind,
34}
35
36/// The types of libraries that can be linked against during compilation
37#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
38pub enum LibraryKind {
39    /// A Miden package (MASP)
40    #[default]
41    Masp,
42    /// A source-form MASM library, using the standard project layout
43    Masm,
44}
45impl fmt::Display for LibraryKind {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        match self {
48            Self::Masm => f.write_str("masm"),
49            Self::Masp => f.write_str("masp"),
50        }
51    }
52}
53impl FromStr for LibraryKind {
54    type Err = ();
55
56    fn from_str(s: &str) -> Result<Self, Self::Err> {
57        match s {
58            "masm" => Ok(Self::Masm),
59            "masp" => Ok(Self::Masp),
60            _ => Err(()),
61        }
62    }
63}
64
65impl LinkLibrary {
66    /// Get the name of this library
67    pub fn name(&self) -> &str {
68        self.name.as_ref()
69    }
70
71    pub fn load(
72        &self,
73        config: &DebuggerConfig,
74        source_manager: Arc<dyn SourceManager>,
75    ) -> Result<Arc<Library>, Report> {
76        if let Some(path) = self.path.as_deref() {
77            return self.load_from_path(path, source_manager);
78        }
79
80        // Search for library among specified search paths
81        let path = self.find(config)?;
82
83        self.load_from_path(&path, source_manager)
84    }
85
86    fn load_from_path(
87        &self,
88        path: &FsPath,
89        source_manager: Arc<dyn SourceManager>,
90    ) -> Result<Arc<Library>, Report> {
91        match self.kind {
92            LibraryKind::Masm => {
93                let ns = LibraryPath::validate(self.name.as_ref()).map_err(|err| {
94                    Report::msg(format!("invalid library namespace '{}': {err}", &self.name))
95                })?;
96
97                let modules = miden_assembly_syntax::parser::read_modules_from_dir(
98                    path,
99                    ns,
100                    source_manager.clone(),
101                    false,
102                )?;
103
104                miden_assembly::Assembler::new(source_manager).assemble_library(modules)
105            }
106            LibraryKind::Masp => {
107                use miden_core::serde::Deserializable;
108                let bytes = std::fs::read(path).into_diagnostic()?;
109                let package =
110                    miden_mast_package::Package::read_from_bytes(&bytes).map_err(|e| {
111                        Report::msg(format!(
112                            "failed to load Miden package from {}: {e}",
113                            path.display()
114                        ))
115                    })?;
116                Ok(package.mast.clone())
117            }
118        }
119    }
120
121    fn find(&self, config: &DebuggerConfig) -> Result<PathBuf, Report> {
122        use std::fs;
123
124        let toolchain_dir = config.toolchain_dir();
125        let search_paths = toolchain_dir
126            .iter()
127            .chain(config.search_path.iter())
128            .chain(config.working_dir.iter());
129
130        for search_path in search_paths {
131            let reader = fs::read_dir(search_path).map_err(|err| {
132                Report::msg(format!(
133                    "invalid library search path '{}': {err}",
134                    search_path.display()
135                ))
136            })?;
137            for entry in reader {
138                let Ok(entry) = entry else {
139                    continue;
140                };
141                let path = entry.path();
142                let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
143                    continue;
144                };
145                if stem != self.name.as_ref() {
146                    continue;
147                }
148
149                match self.kind {
150                    LibraryKind::Masp => {
151                        if !path.is_file() {
152                            return Err(Report::msg(format!(
153                                "unable to load Miden Assembly package from '{}': not a file",
154                                path.display()
155                            )));
156                        }
157                    }
158                    LibraryKind::Masm => {
159                        if !path.is_dir() {
160                            return Err(Report::msg(format!(
161                                "unable to load Miden Assembly library from '{}': not a directory",
162                                path.display()
163                            )));
164                        }
165                    }
166                }
167                return Ok(path);
168            }
169        }
170
171        Err(Report::msg(format!(
172            "unable to locate library '{}' using any of the provided search paths",
173            &self.name
174        )))
175    }
176}
177
178#[cfg(feature = "tui")]
179impl clap::builder::ValueParserFactory for LinkLibrary {
180    type Parser = LinkLibraryParser;
181
182    fn value_parser() -> Self::Parser {
183        LinkLibraryParser
184    }
185}
186
187#[cfg(feature = "tui")]
188#[doc(hidden)]
189#[derive(Clone)]
190pub struct LinkLibraryParser;
191
192#[cfg(feature = "tui")]
193impl clap::builder::TypedValueParser for LinkLibraryParser {
194    type Value = LinkLibrary;
195
196    fn possible_values(
197        &self,
198    ) -> Option<Box<dyn Iterator<Item = clap::builder::PossibleValue> + '_>> {
199        use clap::builder::PossibleValue;
200
201        Some(Box::new(
202            [
203                PossibleValue::new("masm").help("A Miden Assembly project directory"),
204                PossibleValue::new("masp").help("A compiled Miden package file"),
205            ]
206            .into_iter(),
207        ))
208    }
209
210    /// Parses the `-l` flag using the following format:
211    ///
212    /// `-l[KIND=]NAME`
213    ///
214    /// * `KIND` is one of: `masp`, `masm`; defaults to `masp`
215    /// * `NAME` is either an absolute path, or a name (without extension)
216    fn parse_ref(
217        &self,
218        _cmd: &clap::Command,
219        _arg: Option<&clap::Arg>,
220        value: &std::ffi::OsStr,
221    ) -> Result<Self::Value, clap::error::Error> {
222        use clap::error::{Error, ErrorKind};
223
224        let value = value.to_str().ok_or_else(|| Error::new(ErrorKind::InvalidUtf8))?;
225        let (kind, name) = value
226            .split_once('=')
227            .map(|(kind, name)| (Some(kind), name))
228            .unwrap_or((None, value));
229
230        if name.is_empty() {
231            return Err(Error::raw(
232                ErrorKind::ValueValidation,
233                "invalid link library: must specify a name or path",
234            ));
235        }
236
237        let maybe_path = FsPath::new(name);
238        let extension = maybe_path.extension().map(|ext| ext.to_str().unwrap());
239        let kind = match kind {
240            Some(kind) if !kind.is_empty() => kind.parse::<LibraryKind>().map_err(|_| {
241                Error::raw(ErrorKind::InvalidValue, format!("'{kind}' is not a valid library kind"))
242            })?,
243            Some(_) | None => match extension {
244                Some(kind) => kind.parse::<LibraryKind>().map_err(|_| {
245                    Error::raw(
246                        ErrorKind::InvalidValue,
247                        format!("'{kind}' is not a valid library kind"),
248                    )
249                })?,
250                None => LibraryKind::default(),
251            },
252        };
253
254        if maybe_path.is_absolute() {
255            let meta = maybe_path.metadata().map_err(|err| {
256                Error::raw(
257                    ErrorKind::ValueValidation,
258                    format!(
259                        "invalid link library: unable to load '{}': {err}",
260                        maybe_path.display()
261                    ),
262                )
263            })?;
264
265            match kind {
266                LibraryKind::Masp if !meta.is_file() => {
267                    return Err(Error::raw(
268                        ErrorKind::ValueValidation,
269                        format!("invalid link library: '{}' is not a file", maybe_path.display()),
270                    ));
271                }
272                LibraryKind::Masm if !meta.is_dir() => {
273                    return Err(Error::raw(
274                        ErrorKind::ValueValidation,
275                        format!(
276                            "invalid link library: kind 'masm' was specified, but '{}' is not a \
277                             directory",
278                            maybe_path.display()
279                        ),
280                    ));
281                }
282                _ => (),
283            }
284
285            let name = maybe_path.file_stem().unwrap().to_str().unwrap().to_string();
286
287            Ok(LinkLibrary {
288                name: name.into(),
289                path: Some(maybe_path.to_path_buf()),
290                kind,
291            })
292        } else if extension.is_some() {
293            let name = name.strip_suffix(unsafe { extension.unwrap_unchecked() }).unwrap();
294            let mut name = name.to_string();
295            name.pop();
296
297            Ok(LinkLibrary {
298                name: name.into(),
299                path: None,
300                kind,
301            })
302        } else {
303            Ok(LinkLibrary {
304                name: name.to_string().into(),
305                path: None,
306                kind,
307            })
308        }
309    }
310}