forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
50 lines (47 loc) · 1.76 KB
/
Copy pathlib.rs
File metadata and controls
50 lines (47 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
pub mod ast;
pub mod grammar;
pub mod lexer;
pub use lexer::{Token, TokenKind};
mod parser;
pub use parser::{Label, ParseFailed, ParseResult, Parser};
pub mod node;
use ast::Module;
use fe_common::{diagnostics::Diagnostic, files::SourceFileId};
/// Parse a [`Module`] from the file content string.
///
/// If there was no fatal error during parsing, it returns the parsed module and
/// a vector of [`Diagnostic`]s, which should be printed. If any of the returned
/// diagnostics are errors, the compilation of this file should ultimately fail.
///
/// If the parser does reach a fatal error, this returns the list of generated
/// diagnostics.
///
/// A [`SourceFileId`] is required to associate any diagnostics with the
/// underlying file.
pub fn parse_file(
file_content: &str,
file_id: SourceFileId,
) -> Result<(Module, Vec<Diagnostic>), Vec<Diagnostic>> {
let mut parser = Parser::new(file_content, file_id);
match crate::grammar::module::parse_module(&mut parser) {
Err(_) => Err(parser.diagnostics),
Ok(node) => Ok((node.kind, parser.diagnostics)),
}
}
/// Apply the given parsing function to the code string, returning the result.
/// If the parsing fails, the parser's diagnostics will be printed.
/// This function is provided for easy testing of later compiler stages.
pub fn parse_code_chunk<F, T>(mut parse_fn: F, src: &str) -> ParseResult<T>
where
F: FnMut(&mut Parser) -> ParseResult<T>,
{
let mut files = fe_common::files::FileStore::new();
let id = files.add_file("parse_code_chunk test snippet", src);
let mut parser = Parser::new(src, id);
if let Ok(node) = parse_fn(&mut parser) {
Ok(node)
} else {
fe_common::diagnostics::print_diagnostics(&parser.diagnostics, &files);
Err(ParseFailed)
}
}