72 lines
2.4 KiB
Rust
72 lines
2.4 KiB
Rust
//! Verilog/SystemVerilog lexer and parser.
|
|
//!
|
|
//! This crate plays the role of `ruff_python_parser` in ruff's architecture:
|
|
//! it turns source text into a comment-preserving AST that the formatter
|
|
//! crate consumes.
|
|
|
|
pub mod ast;
|
|
pub mod defines;
|
|
pub mod lexer;
|
|
pub mod line_index;
|
|
pub mod parser;
|
|
pub mod span;
|
|
pub mod stats;
|
|
pub mod token;
|
|
|
|
pub use lexer::{tokenize, LexError};
|
|
pub use line_index::LineIndex;
|
|
pub use parser::{parse, parse_tolerant, ParseDiagnostic, ParseError, PARSE_STACK_SIZE};
|
|
pub use span::TextRange;
|
|
pub use token::KEYWORDS;
|
|
|
|
/// Convenience: lex and parse in one step.
|
|
pub fn parse_source(source: &str) -> Result<ast::SourceFile, Error> {
|
|
let tokens = tokenize(source).map_err(Error::Lex)?;
|
|
parse(tokens, source).map_err(Error::Parse)
|
|
}
|
|
|
|
/// Lex and parse without ever failing: the parts that do not parse become
|
|
/// error leaves in the tree and diagnostics in the list.
|
|
///
|
|
/// This is the entry point for editor-side consumers (TODO.md §6), where the
|
|
/// buffer is mid-edit most of the time. On a file that parses cleanly the tree
|
|
/// is identical to [`parse_source`]'s and the diagnostic list is empty — so a
|
|
/// caller that refuses to act on a file with diagnostics (the formatter does)
|
|
/// sees exactly the behavior it had before. See
|
|
/// `docs/features/error-recovery/README.md`.
|
|
pub fn parse_source_tolerant(source: &str) -> (ast::SourceFile, Vec<ParseDiagnostic>) {
|
|
match tokenize(source) {
|
|
Ok(tokens) => parse_tolerant(tokens, source),
|
|
// The lexer is all-or-nothing (an unterminated string or block comment
|
|
// has no sensible resumption point), so a lex error makes the whole
|
|
// file one error node rather than a partial tree.
|
|
Err(e) => {
|
|
let offset = LineIndex::new(source).offset(e.line, e.col).unwrap_or(0);
|
|
let diag = ParseDiagnostic {
|
|
message: e.message,
|
|
line: e.line,
|
|
col: e.col,
|
|
span: TextRange::empty(offset),
|
|
};
|
|
(parser::error_file(source), vec![diag])
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub enum Error {
|
|
Lex(LexError),
|
|
Parse(ParseError),
|
|
}
|
|
|
|
impl std::fmt::Display for Error {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
match self {
|
|
Error::Lex(e) => write!(f, "lex error: {e}"),
|
|
Error::Parse(e) => write!(f, "parse error: {e}"),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for Error {}
|