use bumpalo::collections::Vec;
use bumpalo::Bump;
use crate::error::Error;
use crate::{ast::ASTContext, error::ErrorType};
pub struct ValidationContext<'a> {
pub arena: &'a Bump,
pub errors: Vec<'a, &'a str>,
}
impl<'a> ValidationContext<'a> {
pub fn new(ctx: &'a ASTContext) -> Self {
ValidationContext {
arena: &ctx.arena,
errors: Vec::new_in(&ctx.arena),
}
}
pub fn add_error<S: AsRef<str>>(&mut self, str: S) {
self.errors.push(self.arena.alloc_str(str.as_ref()));
}
pub fn to_result(self) -> Result<(), Error> {
if self.errors.is_empty() {
Ok(())
} else {
let mut context = String::new();
let mut is_first = true;
for error in self.errors {
if is_first {
is_first = false;
} else {
context.push('\n');
}
context.push_str("- ");
context.push_str(error.as_ref());
}
Err(Error::new_with_context(
"Document failed validation",
None,
&context,
Some(ErrorType::GraphQL),
))
}
}
}