Resolver - Refactored error handling

This commit is contained in:
Emmanuel BENOîT 2023-01-03 22:50:47 +01:00
parent 36ac55d286
commit acb29e7123

View file

@ -1,16 +1,19 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::{ast, errors::ParserError, tokens::Token}; use crate::{
ast,
errors::{ErrorKind, SloxError, SloxResult},
tokens::Token,
};
pub type ResolvedVariables = HashMap<*const ast::ExprNode, usize>; pub type ResolvedVariables = HashMap<*const ast::ExprNode, usize>;
pub fn resolve_variables(program: &ast::ProgramNode) -> Result<ResolvedVariables, ParserError> { pub fn resolve_variables(program: &ast::ProgramNode) -> Result<ResolvedVariables, SloxError> {
let mut state = ResolverState::default(); let mut state = ResolverState::default();
program.resolve(&mut state)?; program.resolve(&mut state).map(|_| state.resolved)
Ok(state.resolved)
} }
type ResolverResult = Result<(), ParserError>; type ResolverResult = SloxResult<()>;
#[derive(Default)] #[derive(Default)]
struct ResolverState { struct ResolverState {
@ -185,9 +188,10 @@ impl VarResolver for ast::ExprNode {
match self { match self {
ast::ExprNode::Variable { name } => { ast::ExprNode::Variable { name } => {
if rs.check(&name.lexeme) == Some(false) { if rs.check(&name.lexeme) == Some(false) {
Err(ParserError::new( Err(SloxError::with_token(
ErrorKind::Parse,
name, name,
"can't read local variable in its own initializer", "can't read local variable in its own initializer".to_owned(),
)) ))
} else { } else {
rs.resolve_local(self, name); rs.resolve_local(self, name);