Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use thiserror instead of anyhow #410

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/core/src/built_in_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use itertools::Itertools;
use rand::prelude::SliceRandom;
use rand::Rng;
use std::collections::BTreeMap;
use grit_pattern_matcher::errors::GritResult;

// todo we can probably use a macro to generate a function that takes a vec and
// and calls the input function with the vec args unpacked.
Expand Down
5 changes: 3 additions & 2 deletions crates/core/src/foreign_function_definition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use grit_util::AnalysisLogs;
use marzano_externals::function::ExternalFunction;
use marzano_language::foreign_language::ForeignLanguage;
use std::borrow::Cow;
use grit_pattern_matcher::errors::{GritPatternError, GritResult};

#[derive(Debug, Clone)]
pub struct ForeignFunctionDefinition {
Expand Down Expand Up @@ -123,15 +124,15 @@ impl GritCall<MarzanoQueryContext> for CallForeignFunction<MarzanoQueryContext>
state: &mut State<'a, MarzanoQueryContext>,
context: &'a MarzanoContext<'a>,
logs: &mut AnalysisLogs,
) -> Result<MarzanoResolvedPattern<'a>> {
) -> GritResult<MarzanoResolvedPattern<'a>> {
let function_definition = &context.foreign_function_definitions()[self.index];

match function_definition
.call(state, context, &self.args, logs)?
.ret_val
{
Some(pattern) => Ok(pattern),
None => bail!("Function call did not return a value"),
None =>Err(GritPatternError::new("Function call did not return a value")),
}
}
}
1 change: 1 addition & 0 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,4 @@ mod test;
mod test_files;
#[cfg(any(test, feature = "test_utils"))]
pub mod test_utils;
mod error;
22 changes: 11 additions & 11 deletions crates/core/src/marzano_resolved_pattern.rs
Original file line number Diff line number Diff line change
Expand Up @@ -417,8 +417,8 @@ impl<'a> ResolvedPattern<'a, MarzanoQueryContext> for MarzanoResolvedPattern<'a>
DynamicPattern::Snippet(snippet) => {
Self::from_dynamic_snippet(snippet, state, context, logs)
}
DynamicPattern::CallBuiltIn(built_in) => built_in.call(state, context, logs),
DynamicPattern::CallFunction(func) => func.call(state, context, logs),
DynamicPattern::CallBuiltIn(built_in) => built_in.call(state, context, logs).into(),
DynamicPattern::CallFunction(func) => func.call(state, context, logs).into(),
DynamicPattern::CallForeignFunction(func) => func.call(state, context, logs),
}
}
Expand Down Expand Up @@ -467,8 +467,8 @@ impl<'a> ResolvedPattern<'a, MarzanoQueryContext> for MarzanoResolvedPattern<'a>
dynamic_snippet: Some(pattern),
..
}) => Self::from_dynamic_pattern(pattern, state, context, logs),
Pattern::CallBuiltIn(built_in) => built_in.call(state, context, logs),
Pattern::CallFunction(func) => func.call(state, context, logs),
Pattern::CallBuiltIn(built_in) => built_in.call(state, context, logs).into(),
Pattern::CallFunction(func) => func.call(state, context, logs).into(),
Pattern::CallForeignFunction(func) => func.call(state, context, logs),
Pattern::StringConstant(string) => Ok(Self::Snippets(vector![ResolvedSnippet::Text(
(&string.text).into(),
Expand Down Expand Up @@ -524,13 +524,13 @@ impl<'a> ResolvedPattern<'a, MarzanoQueryContext> for MarzanoResolvedPattern<'a>
body,
}))))
}
Pattern::Add(add_pattern) => add_pattern.call(state, context, logs),
Pattern::Subtract(subtract_pattern) => subtract_pattern.call(state, context, logs),
Pattern::Multiply(multiply_pattern) => multiply_pattern.call(state, context, logs),
Pattern::Divide(divide_pattern) => divide_pattern.call(state, context, logs),
Pattern::Modulo(modulo_pattern) => modulo_pattern.call(state, context, logs),
Pattern::Before(before) => before.prev_pattern(state, context, logs),
Pattern::After(after) => after.next_pattern(state, context, logs),
Pattern::Add(add_pattern) => add_pattern.call(state, context, logs).into(),
Pattern::Subtract(subtract_pattern) => subtract_pattern.call(state, context, logs).into(),
Pattern::Multiply(multiply_pattern) => multiply_pattern.call(state, context, logs).into(),
Pattern::Divide(divide_pattern) => divide_pattern.call(state, context, logs).into(),
Pattern::Modulo(modulo_pattern) => modulo_pattern.call(state, context, logs).into(),
Pattern::Before(before) => before.prev_pattern(state, context, logs).into(),
Pattern::After(after) => after.next_pattern(state, context, logs).into(),
Pattern::AstNode(_)
| Pattern::CodeSnippet(_)
| Pattern::Call(_)
Expand Down
1 change: 1 addition & 0 deletions crates/core/src/pattern_compiler/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ use marzano_language::{
};

use std::{collections::BTreeMap, path::Path, vec};
use grit_pattern_matcher::errors::GritResult;

pub type CallbackMatchFn = dyn for<'a> Fn(
&<problem::MarzanoQueryContext as grit_pattern_matcher::context::QueryContext>::ResolvedPattern<'a>,
Expand Down
2 changes: 1 addition & 1 deletion crates/grit-pattern-matcher/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ publish = true
rust.unused_crate_dependencies = "warn"

[dependencies]
anyhow = { version = "1.0.70" }
thiserror = { version = "1.0.61" }
elsa = { version = "1.9.0" }
getrandom = { version = "0.2.11", optional = true }
grit-util = { path = "../grit-util", version = "0.3.0" }
Expand Down
14 changes: 8 additions & 6 deletions crates/grit-pattern-matcher/src/binding.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use crate::errors::{GritPatternError, GritResult};
use crate::{
constant::Constant,
context::QueryContext,
effects::Effect,
pattern::{FileRegistry, Pattern, ResolvedPattern, State},
};
use anyhow::{bail, Result};
use grit_util::{AnalysisLogs, ByteRange, CodeRange, Range};
use std::path::Path;
use std::{borrow::Cow, collections::HashMap};
Expand All @@ -21,12 +21,14 @@ pub trait Binding<'a, Q: QueryContext>: Clone + std::fmt::Debug + PartialEq + Si
state: &mut State<'a, Q>,
context: &'a Q::ExecContext<'a>,
logs: &mut AnalysisLogs,
) -> Result<Q::Binding<'a>> {
) -> GritResult<Q::Binding<'a>> {
let resolved = Q::ResolvedPattern::from_pattern(pattern, state, context, logs)?;
if let Some(binding) = resolved.get_last_binding() {
Ok(binding.clone())
} else {
bail!("cannot create binding from pattern without binding");
Err(GritPatternError::new(
"cannot create binding from pattern without binding",
))
}
}

Expand Down Expand Up @@ -65,9 +67,9 @@ pub trait Binding<'a, Q: QueryContext>: Clone + std::fmt::Debug + PartialEq + Si
memo: &mut HashMap<CodeRange, Option<String>>,
distributed_indent: Option<usize>,
logs: &mut AnalysisLogs,
) -> Result<Cow<'a, str>>;
) -> GritResult<Cow<'a, str>>;

fn text(&self, language: &Q::Language<'a>) -> Result<Cow<str>>;
fn text(&self, language: &Q::Language<'a>) -> GritResult<Cow<str>>;

fn source(&self) -> Option<&'a str>;

Expand Down Expand Up @@ -101,5 +103,5 @@ pub trait Binding<'a, Q: QueryContext>: Clone + std::fmt::Debug + PartialEq + Si
&self,
language: &Q::Language<'a>,
logs: &mut AnalysisLogs,
) -> Result<()>;
) -> GritResult<()>;
}
8 changes: 4 additions & 4 deletions crates/grit-pattern-matcher/src/context.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::errors::GritResult;
use crate::{
binding::Binding,
file_owners::FileOwners,
Expand All @@ -6,7 +7,6 @@ use crate::{
Pattern, PatternDefinition, PredicateDefinition, ResolvedPattern, State,
},
};
use anyhow::Result;
use grit_util::{AnalysisLogs, Ast, AstNode, Language};

/// Contains various kinds of context about the query being executed.
Expand Down Expand Up @@ -39,7 +39,7 @@ pub trait ExecContext<'a, Q: QueryContext> {
context: &'a Self,
state: &mut State<'a, Q>,
logs: &mut AnalysisLogs,
) -> Result<Q::ResolvedPattern<'a>>;
) -> GritResult<Q::ResolvedPattern<'a>>;

/// Call this when "entering" a file to lazily load it.
/// This MUST be implemented correctly, or the query engine will not work.
Expand All @@ -50,7 +50,7 @@ pub trait ExecContext<'a, Q: QueryContext> {
file: &Q::File<'a>,
state: &mut State<'a, Q>,
logs: &mut AnalysisLogs,
) -> Result<bool>;
) -> GritResult<bool>;

// FIXME: Don't depend on Grit's file handling in Context.
fn files(&self) -> &FileOwners<Q::Tree<'a>>;
Expand All @@ -63,7 +63,7 @@ pub trait ExecContext<'a, Q: QueryContext> {
binding: &Q::ResolvedPattern<'a>,
state: &mut State<'a, Q>,
logs: &mut AnalysisLogs,
) -> Result<bool>;
) -> GritResult<bool>;

fn name(&self) -> Option<&str>;
}
53 changes: 44 additions & 9 deletions crates/grit-pattern-matcher/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@ use crate::{
context::QueryContext,
pattern::{get_file_name, State},
};
use anyhow::{bail, Result};
use grit_util::{AnalysisLogBuilder, AnalysisLogs};
use regex::Error as RegexError;
use std::io;
use std::num::{ParseFloatError, ParseIntError};
use thiserror::Error;

pub fn debug<'a, Q: QueryContext>(
analysis_logs: &mut AnalysisLogs,
state: &State<'a, Q>,
lang: &Q::Language<'a>,
message: &str,
) -> Result<()> {
) -> GritResult<()> {
let mut builder = AnalysisLogBuilder::default();
builder.level(501_u16);
builder.message(message);
Expand All @@ -22,9 +25,7 @@ pub fn debug<'a, Q: QueryContext>(
let log = builder.build();
match log {
Ok(log) => analysis_logs.push(log),
Err(err) => {
bail!(err);
}
Err(err) => return Err(GritPatternError::Builder(err.to_string())),
}
Ok(())
}
Expand All @@ -34,7 +35,7 @@ pub fn warning<'a, Q: QueryContext>(
state: &State<'a, Q>,
lang: &Q::Language<'a>,
message: &str,
) -> Result<()> {
) -> GritResult<()> {
let mut builder = AnalysisLogBuilder::default();
builder.level(301_u16);
builder.message(message);
Expand All @@ -46,9 +47,43 @@ pub fn warning<'a, Q: QueryContext>(
let log = builder.build();
match log {
Ok(log) => analysis_logs.push(log),
Err(err) => {
bail!(err);
}
Err(err) => return Err(GritPatternError::Builder(err.to_string())),
}
Ok(())
}

#[derive(Error, Debug)]
pub enum GritPatternError {
#[error("Matcher: {0}")]
Matcher(String),

#[error(transparent)]
Io(#[from] io::Error),

#[error(transparent)]
ParseFloat(#[from] ParseFloatError),

#[error(transparent)]
ParseInt(#[from] ParseIntError),

#[error(transparent)]
Regex(#[from] RegexError),

#[error("[Builder] {0}")]
Builder(String),

#[error("{0}")]
Generic(String),
}

impl GritPatternError {
pub(crate) fn new_matcher(reason: impl Into<String>) -> Self {
Self::Matcher(reason.into())
}

pub fn new(reason: impl Into<String>) -> Self {
Self::Generic(reason.into())
}
}

pub type GritResult<R> = Result<R, GritPatternError>;
Loading