1macro_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
36type ParseError<'a> = lalrpop_util::ParseError<u32, Token<'a>, ParsingError>;
40
41#[derive(Default)]
47pub struct ModuleParser {
48 kind: ast::ModuleKind,
53 interned: BTreeSet<Arc<str>>,
70 warnings_as_errors: bool,
72}
73
74impl ModuleParser {
75 pub fn new(kind: ast::ModuleKind) -> Self {
77 Self {
78 kind,
79 interned: Default::default(),
80 warnings_as_errors: false,
81 }
82 }
83
84 pub fn set_warnings_as_errors(&mut self, yes: bool) {
86 self.warnings_as_errors = yes;
87 }
88
89 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 #[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 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#[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
149fn 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#[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 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 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 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 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#[cfg(test)]
337mod tests {
338 use vm_core::assert_matches;
339
340 use super::*;
341 use crate::SourceId;
342
343 #[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}