miden_assembly/parser/
mod.rs

1/// Simple macro used in the grammar definition for constructing spans
2macro_rules! span {
3    ($id:expr, $l:expr, $r:expr) => {
4        crate::SourceSpan::new($id, $l..$r)
5    };
6    ($id:expr, $i:expr) => {
7        crate::SourceSpan::at($id, $i)
8    };
9}
10
11lalrpop_util::lalrpop_mod!(
12    #[allow(clippy::all)]
13    grammar,
14    "/parser/grammar.rs"
15);
16
17mod error;
18mod lexer;
19mod scanner;
20mod token;
21
22use alloc::{boxed::Box, collections::BTreeSet, string::ToString, sync::Arc, vec::Vec};
23
24pub use self::{
25    error::{BinErrorKind, HexErrorKind, LiteralErrorKind, ParsingError},
26    lexer::Lexer,
27    scanner::Scanner,
28    token::{BinEncodedValue, DocumentationType, HexEncodedValue, Token},
29};
30use crate::{
31    LibraryPath, SourceManager, ast,
32    diagnostics::{Report, SourceFile, SourceSpan, Span, Spanned},
33    sema,
34};
35
36// TYPE ALIASES
37// ================================================================================================
38
39type ParseError<'a> = lalrpop_util::ParseError<u32, Token<'a>, ParsingError>;
40
41// MODULE PARSER
42// ================================================================================================
43
44/// This is a wrapper around the lower-level parser infrastructure which handles orchestrating all
45/// of the pieces needed to parse a [ast::Module] from source, and run semantic analysis on it.
46#[derive(Default)]
47pub struct ModuleParser {
48    /// The kind of module we're parsing.
49    ///
50    /// This is used when performing semantic analysis to detect when various invalid constructions
51    /// are encountered, such as use of the `syscall` instruction in a kernel module.
52    kind: ast::ModuleKind,
53    /// A set of interned strings allocated during parsing/semantic analysis.
54    ///
55    /// This is a very primitive and imprecise way of interning strings, but was the least invasive
56    /// at the time the new parser was implemented. In essence, we avoid duplicating allocations
57    /// for frequently occurring strings, by tracking which strings we've seen before, and
58    /// sharing a reference counted pointer instead.
59    ///
60    /// We may want to replace this eventually with a proper interner, so that we can also gain the
61    /// benefits commonly provided by interned string handles (e.g. cheap equality comparisons, no
62    /// ref- counting overhead, copyable and of smaller size).
63    ///
64    /// Note that [Ident], [ProcedureName], [LibraryPath] and others are all implemented in terms
65    /// of either the actual reference-counted string, e.g. `Arc<str>`, or in terms of [Ident],
66    /// which is essentially the former wrapped in a [SourceSpan]. If we ever replace this with
67    /// a better interner, we will also want to update those types to be in terms of whatever
68    /// the handle type of the interner is.
69    interned: BTreeSet<Arc<str>>,
70    /// When true, all warning diagnostics are promoted to error severity
71    warnings_as_errors: bool,
72}
73
74impl ModuleParser {
75    /// Construct a new parser for the given `kind` of [ast::Module].
76    pub fn new(kind: ast::ModuleKind) -> Self {
77        Self {
78            kind,
79            interned: Default::default(),
80            warnings_as_errors: false,
81        }
82    }
83
84    /// Configure this parser so that any warning diagnostics are promoted to errors.
85    pub fn set_warnings_as_errors(&mut self, yes: bool) {
86        self.warnings_as_errors = yes;
87    }
88
89    /// Parse a [ast::Module] from `source`, and give it the provided `path`.
90    pub fn parse(
91        &mut self,
92        path: LibraryPath,
93        source: Arc<SourceFile>,
94    ) -> Result<Box<ast::Module>, Report> {
95        let forms = parse_forms_internal(source.clone(), &mut self.interned)
96            .map_err(|err| Report::new(err).with_source_code(source.clone()))?;
97        sema::analyze(source, self.kind, path, forms, self.warnings_as_errors).map_err(Report::new)
98    }
99
100    /// Parse a [ast::Module], `name`, from `path`.
101    #[cfg(feature = "std")]
102    pub fn parse_file<P>(
103        &mut self,
104        name: LibraryPath,
105        path: P,
106        source_manager: &dyn SourceManager,
107    ) -> Result<Box<ast::Module>, Report>
108    where
109        P: AsRef<std::path::Path>,
110    {
111        use vm_core::debuginfo::SourceManagerExt;
112
113        use crate::diagnostics::{IntoDiagnostic, WrapErr};
114
115        let path = path.as_ref();
116        let source_file = source_manager
117            .load_file(path)
118            .into_diagnostic()
119            .wrap_err_with(|| format!("failed to load source file from '{}'", path.display()))?;
120        self.parse(name, source_file)
121    }
122
123    /// Parse a [ast::Module], `name`, from `source`.
124    pub fn parse_str(
125        &mut self,
126        name: LibraryPath,
127        source: impl ToString,
128        source_manager: &dyn SourceManager,
129    ) -> Result<Box<ast::Module>, Report> {
130        use vm_core::debuginfo::SourceContent;
131
132        let path = Arc::from(name.path().into_owned().into_boxed_str());
133        let content = SourceContent::new(Arc::clone(&path), source.to_string().into_boxed_str());
134        let source_file = source_manager.load_from_raw_parts(path, content);
135        self.parse(name, source_file)
136    }
137}
138
139/// This is used in tests to parse `source` as a set of raw [ast::Form]s rather than as a
140/// [ast::Module].
141///
142/// NOTE: This does _not_ run semantic analysis.
143#[cfg(any(test, feature = "testing"))]
144pub fn parse_forms(source: Arc<SourceFile>) -> Result<Vec<ast::Form>, ParsingError> {
145    let mut interned = BTreeSet::default();
146    parse_forms_internal(source, &mut interned)
147}
148
149/// Parse `source` as a set of [ast::Form]s
150///
151/// Aside from catching syntax errors, this does little validation of the resulting forms, that is
152/// handled by semantic analysis, which the caller is expected to perform next.
153fn parse_forms_internal(
154    source: Arc<SourceFile>,
155    interned: &mut BTreeSet<Arc<str>>,
156) -> Result<Vec<ast::Form>, ParsingError> {
157    let source_id = source.id();
158    let scanner = Scanner::new(source.as_str());
159    let lexer = Lexer::new(source_id, scanner);
160    grammar::FormsParser::new()
161        .parse(&source, interned, core::marker::PhantomData, lexer)
162        .map_err(|err| ParsingError::from_parse_error(source_id, err))
163}
164
165// DIRECTORY PARSER
166// ================================================================================================
167
168/// Read the contents (modules) of this library from `dir`, returning any errors that occur
169/// while traversing the file system.
170///
171/// Errors may also be returned if traversal discovers issues with the modules, such as
172/// invalid names, etc.
173///
174/// Returns an iterator over all parsed modules.
175#[cfg(feature = "std")]
176pub fn read_modules_from_dir(
177    namespace: crate::LibraryNamespace,
178    dir: &std::path::Path,
179    source_manager: &dyn SourceManager,
180) -> Result<impl Iterator<Item = Box<ast::Module>>, Report> {
181    use std::collections::{BTreeMap, btree_map::Entry};
182
183    use module_walker::{ModuleEntry, WalkModules};
184
185    use crate::{
186        diagnostics::{IntoDiagnostic, WrapErr},
187        report,
188    };
189
190    if !dir.is_dir() {
191        return Err(report!("the provided path '{}' is not a valid directory", dir.display()));
192    }
193
194    // mod.masm is not allowed in the root directory
195    if dir.join(ast::Module::ROOT_FILENAME).exists() {
196        return Err(report!("{} is not allowed in the root directory", ast::Module::ROOT_FILENAME));
197    }
198
199    let mut modules = BTreeMap::default();
200
201    let walker = WalkModules::new(namespace.clone(), dir)
202        .into_diagnostic()
203        .wrap_err_with(|| format!("failed to load modules from '{}'", dir.display()))?;
204    for entry in walker {
205        let ModuleEntry { mut name, source_path } = entry?;
206        if name.last() == ast::Module::ROOT {
207            name.pop();
208        }
209
210        // Parse module at the given path
211        let mut parser = ModuleParser::new(ast::ModuleKind::Library);
212        let ast = parser.parse_file(name.clone(), &source_path, source_manager)?;
213        match modules.entry(name) {
214            Entry::Occupied(ref entry) => {
215                return Err(report!("duplicate module '{0}'", entry.key().clone()));
216            },
217            Entry::Vacant(entry) => {
218                entry.insert(ast);
219            },
220        }
221    }
222
223    Ok(modules.into_values())
224}
225
226#[cfg(feature = "std")]
227mod module_walker {
228
229    use std::{
230        ffi::OsStr,
231        fs::{self, DirEntry, FileType},
232        io,
233        path::{Path, PathBuf},
234    };
235
236    use crate::{
237        LibraryNamespace, LibraryPath,
238        ast::Module,
239        diagnostics::{IntoDiagnostic, Report},
240        report,
241    };
242
243    pub struct ModuleEntry {
244        pub name: LibraryPath,
245        pub source_path: PathBuf,
246    }
247
248    pub struct WalkModules<'a> {
249        namespace: LibraryNamespace,
250        root: &'a Path,
251        stack: alloc::collections::VecDeque<io::Result<DirEntry>>,
252    }
253
254    impl<'a> WalkModules<'a> {
255        pub fn new(namespace: LibraryNamespace, path: &'a Path) -> io::Result<Self> {
256            use alloc::collections::VecDeque;
257
258            let stack = VecDeque::from_iter(fs::read_dir(path)?);
259
260            Ok(Self { namespace, root: path, stack })
261        }
262
263        fn next_entry(
264            &mut self,
265            entry: &DirEntry,
266            ty: &FileType,
267        ) -> Result<Option<ModuleEntry>, Report> {
268            if ty.is_dir() {
269                let dir = entry.path();
270                self.stack.extend(fs::read_dir(dir).into_diagnostic()?);
271                return Ok(None);
272            }
273
274            let mut file_path = entry.path();
275            let is_module = file_path
276                .extension()
277                .map(|ext| ext == AsRef::<OsStr>::as_ref(Module::FILE_EXTENSION))
278                .unwrap_or(false);
279            if !is_module {
280                return Ok(None);
281            }
282
283            // Remove the file extension and the root prefix, leaving a namespace-relative path
284            file_path.set_extension("");
285            if file_path.is_dir() {
286                return Err(report!(
287                    "file and directory with same name are not allowed: {}",
288                    file_path.display()
289                ));
290            }
291            let relative_path = file_path
292                .strip_prefix(self.root)
293                .expect("expected path to be a child of the root directory");
294
295            // Construct a [LibraryPath] from the path components, after validating them
296            let mut libpath = LibraryPath::from(self.namespace.clone());
297            for component in relative_path.iter() {
298                let component = component.to_str().ok_or_else(|| {
299                    let p = entry.path();
300                    report!("{} is an invalid directory entry", p.display())
301                })?;
302                libpath.push(component).into_diagnostic()?;
303            }
304            Ok(Some(ModuleEntry { name: libpath, source_path: entry.path() }))
305        }
306    }
307
308    impl Iterator for WalkModules<'_> {
309        type Item = Result<ModuleEntry, Report>;
310
311        fn next(&mut self) -> Option<Self::Item> {
312            loop {
313                let entry = self
314                    .stack
315                    .pop_front()?
316                    .and_then(|entry| entry.file_type().map(|ft| (entry, ft)))
317                    .into_diagnostic();
318
319                match entry {
320                    Ok((ref entry, ref file_type)) => {
321                        match self.next_entry(entry, file_type).transpose() {
322                            None => continue,
323                            result => break result,
324                        }
325                    },
326                    Err(err) => break Some(Err(err)),
327                }
328            }
329        }
330    }
331}
332
333// TESTS
334// ================================================================================================
335
336#[cfg(test)]
337mod tests {
338    use vm_core::assert_matches;
339
340    use super::*;
341    use crate::SourceId;
342
343    // This test checks the lexer behavior with regard to tokenizing `exp(.u?[\d]+)?`
344    #[test]
345    fn lex_exp() {
346        let source_id = SourceId::default();
347        let scanner = Scanner::new("begin exp.u9 end");
348        let mut lexer = Lexer::new(source_id, scanner).map(|result| result.map(|(_, t, _)| t));
349        assert_matches!(lexer.next(), Some(Ok(Token::Begin)));
350        assert_matches!(lexer.next(), Some(Ok(Token::ExpU)));
351        assert_matches!(lexer.next(), Some(Ok(Token::Int(n))) if n == 9);
352        assert_matches!(lexer.next(), Some(Ok(Token::End)));
353    }
354
355    #[test]
356    fn lex_block() {
357        let source_id = SourceId::default();
358        let scanner = Scanner::new(
359            "\
360const.ERR1=1
361
362begin
363    u32assertw
364    u32assertw.err=ERR1
365    u32assertw.err=2
366end
367",
368        );
369        let mut lexer = Lexer::new(source_id, scanner).map(|result| result.map(|(_, t, _)| t));
370        assert_matches!(lexer.next(), Some(Ok(Token::Const)));
371        assert_matches!(lexer.next(), Some(Ok(Token::Dot)));
372        assert_matches!(lexer.next(), Some(Ok(Token::ConstantIdent("ERR1"))));
373        assert_matches!(lexer.next(), Some(Ok(Token::Equal)));
374        assert_matches!(lexer.next(), Some(Ok(Token::Int(1))));
375        assert_matches!(lexer.next(), Some(Ok(Token::Begin)));
376        assert_matches!(lexer.next(), Some(Ok(Token::U32Assertw)));
377        assert_matches!(lexer.next(), Some(Ok(Token::U32Assertw)));
378        assert_matches!(lexer.next(), Some(Ok(Token::Dot)));
379        assert_matches!(lexer.next(), Some(Ok(Token::Err)));
380        assert_matches!(lexer.next(), Some(Ok(Token::Equal)));
381        assert_matches!(lexer.next(), Some(Ok(Token::ConstantIdent("ERR1"))));
382        assert_matches!(lexer.next(), Some(Ok(Token::U32Assertw)));
383        assert_matches!(lexer.next(), Some(Ok(Token::Dot)));
384        assert_matches!(lexer.next(), Some(Ok(Token::Err)));
385        assert_matches!(lexer.next(), Some(Ok(Token::Equal)));
386        assert_matches!(lexer.next(), Some(Ok(Token::Int(2))));
387        assert_matches!(lexer.next(), Some(Ok(Token::End)));
388        assert_matches!(lexer.next(), Some(Ok(Token::Eof)));
389    }
390
391    #[test]
392    fn lex_emit() {
393        let source_id = SourceId::default();
394        let scanner = Scanner::new(
395            "\
396begin
397    push.1
398    emit.1
399end
400",
401        );
402        let mut lexer = Lexer::new(source_id, scanner).map(|result| result.map(|(_, t, _)| t));
403        assert_matches!(lexer.next(), Some(Ok(Token::Begin)));
404        assert_matches!(lexer.next(), Some(Ok(Token::Push)));
405        assert_matches!(lexer.next(), Some(Ok(Token::Dot)));
406        assert_matches!(lexer.next(), Some(Ok(Token::Int(1))));
407        assert_matches!(lexer.next(), Some(Ok(Token::Emit)));
408        assert_matches!(lexer.next(), Some(Ok(Token::Dot)));
409        assert_matches!(lexer.next(), Some(Ok(Token::Int(1))));
410        assert_matches!(lexer.next(), Some(Ok(Token::End)));
411        assert_matches!(lexer.next(), Some(Ok(Token::Eof)));
412    }
413}