Skip to content

Error handler trait #428

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

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
50 changes: 49 additions & 1 deletion lrpar/src/lib/ctbuilder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use std::{
any::type_name,
borrow::Cow,
cell::RefCell,
collections::{HashMap, HashSet},
convert::AsRef,
env::{current_dir, var},
Expand All @@ -13,13 +14,17 @@ use std::{
io::{self, Write},
marker::PhantomData,
path::{Path, PathBuf},
rc::Rc,
sync::Mutex,
};

use bincode::{deserialize, serialize_into};
use cfgrammar::{
newlinecache::NewlineCache,
yacc::{ast::ASTWithValidityInfo, YaccGrammar, YaccKind, YaccOriginalActionKind},
yacc::{
ast::{ASTWithValidityInfo, GrammarAST},
YaccGrammar, YaccGrammarError, YaccGrammarWarning, YaccKind, YaccOriginalActionKind,
},
RIdx, Spanned, Symbol,
};
use filetime::FileTime;
Expand Down Expand Up @@ -146,6 +151,32 @@ impl Visibility {
}
}

pub trait GrammarErrorHandler<LexerTypesT>
where
LexerTypesT: LexerTypes,
usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
{
fn grammar_src(&mut self, src: &str);
fn grammar_path(&mut self, path: &Path);
fn warnings_are_errors(&mut self, flag: bool);
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing missing here is that warnings are no longer printed, but there is no mechanism to print them from the trait.
there is also the show_warnings flag of CTParserBuilder we need to add if traits should print warnings.

One thing to consider is that we could change the Ok(()) value of results() to return formatted warnings,
CTParserBuilder then just prints them out to stderr, or perhaps some emit_warnings() call?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing missing here is that warnings are no longer printed, but there is no mechanism to print them from the trait.

The trait doesn't mind if you print or don't :) I have a couple of possible ideas here:

  1. The default implementation of the trait provided by the CTBuilders is that they print warnings and/or panic pretty much as they do now.
  2. We can provide an implementation of the trait which behaves as it does now but before it prints/panics also calls a user implementation of the trait.

Of these, 1) is the easiest to implement and to get right, so I'm inclined to start there, assuming we think it makes sense!

fn on_grammar_warning(&mut self, ws: Box<[YaccGrammarWarning]>);
fn on_grammar_error(&mut self, errs: Box<[YaccGrammarError]>);
fn on_unexpected_conflicts(
&mut self,
ast: &GrammarAST,
grm: &YaccGrammar<LexerTypesT::StorageT>,
sgraph: &StateGraph<LexerTypesT::StorageT>,
stable: &StateTable<LexerTypesT::StorageT>,
conflicts: &Conflicts<LexerTypesT::StorageT>,
);
/// This function must return an `Err` if any of the following are true:
///
/// - `on_grammar_error` has been called.
/// - `on_unexpected_conflicts` has been called,
/// - `on_grammar_warning` was called and `warnings_are_errors` is true.
fn results(&self) -> Result<(), Box<dyn Error>>;
}

/// A `CTParserBuilder` allows one to specify the criteria for building a statically generated
/// parser.
pub struct CTParserBuilder<'a, LexerTypesT: LexerTypes>
Expand All @@ -166,6 +197,7 @@ where
show_warnings: bool,
visibility: Visibility,
rust_edition: RustEdition,
error_handler: Option<Rc<RefCell<dyn GrammarErrorHandler<LexerTypesT>>>>,
phantom: PhantomData<LexerTypesT>,
}

Expand Down Expand Up @@ -209,6 +241,7 @@ where
show_warnings: true,
visibility: Visibility::Private,
rust_edition: RustEdition::Rust2021,
error_handler: None,
phantom: PhantomData,
}
}
Expand Down Expand Up @@ -262,6 +295,14 @@ where
Ok(self.output_path(outp))
}

pub fn error_handler(
mut self,
error_handler: Rc<RefCell<dyn GrammarErrorHandler<LexerTypesT>>>,
) -> Self {
self.error_handler = Some(error_handler);
self
}

/// Set the input grammar path to `inp`. If specified, you must also call
/// [CTParserBuilder::output_path]. In general it is easier to use
/// [CTParserBuilder::grammar_in_src_dir].
Expand Down Expand Up @@ -429,6 +470,12 @@ where
};

let res = YaccGrammar::<StorageT>::new_from_ast_with_validity_info(yk, &ast_validation);
if let Some(error_handler) = self.error_handler.as_ref() {
let mut error_handler = error_handler.borrow_mut();
error_handler.grammar_path(grmp);
error_handler.grammar_src(inc.as_str());
error_handler.warnings_are_errors(self.warnings_are_errors);
}
let grm = match res {
Ok(_) if self.warnings_are_errors && !warnings.is_empty() => {
let mut line_cache = NewlineCache::new();
Expand Down Expand Up @@ -661,6 +708,7 @@ where
show_warnings: self.show_warnings,
visibility: self.visibility.clone(),
rust_edition: self.rust_edition,
error_handler: None,
phantom: PhantomData,
};
Ok(cl.build()?.rule_ids)
Expand Down
2 changes: 1 addition & 1 deletion lrpar/src/lib/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ pub mod parser;
mod test_utils;

pub use crate::{
ctbuilder::{CTParser, CTParserBuilder, RustEdition, Visibility},
ctbuilder::{CTParser, CTParserBuilder, GrammarErrorHandler, RustEdition, Visibility},
lex_api::{LexError, Lexeme, Lexer, LexerTypes, NonStreamingLexer},
parser::{LexParseError, Node, ParseError, ParseRepair, RTParserBuilder, RecoveryKind},
};
Expand Down