Skip to content

Commit

Permalink
1) Catch all panics when executing commands
Browse files Browse the repository at this point in the history
2) Replace once_cell with cell inside node structures
3) Add an optional message to the ErrorReported struct

Signed-off-by: ITesserakt <portyas85@mail.ru>
  • Loading branch information
ITesserakt committed Aug 30, 2024
1 parent 6c21830 commit e59909f
Show file tree
Hide file tree
Showing 14 changed files with 99 additions and 67 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 0 additions & 1 deletion crates/kodept-ast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ pub use self::node::{
};
pub use uninit::Uninit;

// pub mod ast_builder;
pub mod graph;
mod macros;
mod node;
Expand Down
18 changes: 4 additions & 14 deletions crates/kodept-ast/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,24 +140,16 @@ pub mod implementation {
$($field_vis:vis $field_name:ident: $field_type:ty,)*;
$($graph_vis:vis $graph_name:ident: $graph_type:ty$( as $tag:tt)?,)*
}) => {
#[cfg(feature = "serde")]
$(#[$config])*
$vis struct $name {
id: once_cell_serde::unsync::OnceCell<$crate::graph::NodeId<$name>>,
$($field_vis $field_name: $field_type,)*
}

#[cfg(not(feature = "serde"))]
$(#[$config])*
$vis struct $name {
id: std::cell::OnceCell<$crate::graph::NodeId<$name>>,
id: std::cell::Cell<$crate::graph::NodeId<$name>>,
$($field_vis $field_name: $field_type,)*
}

impl $name {
pub fn uninit($($field_name: $field_type,)*) -> $crate::Uninit<'static, Self> {
$crate::Uninit::new(Self {
id: Default::default(),
id: std::cell::Cell::new($crate::graph::NodeId::null()),
$(
$field_name,
)*
Expand All @@ -171,13 +163,11 @@ pub mod implementation {

impl $crate::graph::Identifiable for $name {
fn get_id(&self) -> $crate::graph::NodeId<Self> {
self.id.get().copied().expect("Unreachable")
self.id.get()
}

fn set_id(&self, value: $crate::graph::NodeId<Self>) {
if let Err(_) = self.id.set(value) {
tracing::warn!("Tried to set id twice");
}
self.id.set(value)
}
}

Expand Down
4 changes: 4 additions & 0 deletions crates/kodept-ast/src/uninit.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use tracing::warn;
use crate::graph::{Identifiable, NodeId};
use crate::rlt_accessor::RLTFamily;

Expand All @@ -19,6 +20,9 @@ impl<'rlt, T> Uninit<'rlt, T> {
T: Identifiable,
{
self.value.set_id(id);
if self.rlt_ref.is_none() {
warn!("No rlt linked with node {id}")
}
(self.value, self.rlt_ref)
}

Expand Down
3 changes: 0 additions & 3 deletions crates/kodept-ast/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ impl<E, R> Execution<E, R> {
impl<R> Execution<Infallible, R> {
pub fn unwrap(self) -> Option<R> {
match self {
Execution::Failed(_) => unreachable!(),
Execution::Completed(x) => Some(x),
Execution::Skipped => None
}
Expand All @@ -74,7 +73,6 @@ impl<E, R> FromResidual for Execution<E, R> {
impl<E1: Into<E2>, E2, R> FromResidual<Result<Infallible, E1>> for Execution<E2, R> {
fn from_residual(residual: Result<Infallible, E1>) -> Self {
match residual {
Ok(_) => unreachable!(),
Err(e) => Self::Failed(e.into()),
}
}
Expand All @@ -84,7 +82,6 @@ impl<E, R> FromResidual<Option<Infallible>> for Execution<E, R> {
fn from_residual(residual: Option<Infallible>) -> Self {
match residual {
None => Self::Skipped,
Some(_) => unreachable!()
}
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/kodept-macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.86"
codespan = "0.11.1"
codespan-reporting = "0.11.1"
extend.workspace = true
Expand Down
44 changes: 37 additions & 7 deletions crates/kodept-macros/src/error/mod.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,35 @@
use derive_more::Display;
use std::any::Any;
use std::error::Error;
use derive_more::{Display};
use std::fmt::Formatter;
use std::sync::Mutex;

pub mod compiler_crash;
pub mod report;
pub mod report_collector;
pub mod traits;

#[derive(Debug, Display, Default)]
#[display("Compilation failed due to produced errors")]
#[derive(Debug, Default)]
pub struct ErrorReported {
cause: Option<Box<dyn Error + Send + Sync + 'static>>
message: Option<Box<Mutex<dyn Any + Send>>>,
cause: Option<anyhow::Error>,
}

impl ErrorReported {
pub fn with_cause<E: Error + Send + Sync + 'static>(error: E) -> Self {
Self {
cause: Some(Box::new(error)),
message: None,
cause: Some(anyhow::Error::from(error)),
}
}


pub fn with_message<M: Any + Send>(self, message: M) -> Self {
Self {
message: Some(Box::new(Mutex::new(message))),
..self
}
}

pub fn new() -> Self {
Self::default()
}
Expand All @@ -31,4 +42,23 @@ impl Error for ErrorReported {
Some(x) => Some(x.as_ref()),
}
}
}
}

impl Display for ErrorReported {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if let Some(msg) = self.message.as_ref() {
let guard = msg.lock().expect("Error message is poisoned");
if let Some(msg) = guard.downcast_ref::<String>() {
write!(f, "Compilation failed due to produced errors: {msg}")
} else if let Some(msg) = guard.downcast_ref::<&str>() {
write!(f, "Compilation failed due to produced errors: {msg}")
} else if let Some(msg) = guard.downcast_ref::<&dyn Display>() {
write!(f, "Compilation failed due to produced errors: {msg}")
} else {
write!(f, "Compilation failed due to produced errors")
}
} else {
write!(f, "Compilation failed due to produced errors")
}
}
}
1 change: 0 additions & 1 deletion crates/kodept-macros/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ impl UnrecoverableError {
pub fn into_report(self) -> Report {
match self {
UnrecoverableError::Report(x) => x,
UnrecoverableError::Infallible(_) => unreachable!(),
}
}
}
Expand Down
8 changes: 6 additions & 2 deletions crates/slotgraph/src/dag/petgraph_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,18 @@ where

fn to_index(&self, a: Self::NodeId) -> usize {
match a {
NodeKey::Root => u64::MAX as usize,
// value = 0xFFFF_FFFF
// version = 0x3
NodeKey::Root => 0x0000_0003_FFFF_FFFF,
NodeKey::Child(id) => id.to_index() as usize,
}
}

fn from_index(&self, i: usize) -> Self::NodeId {
match i as u64 {
u64::MAX => NodeKey::Root,
// value = 0xFFFF_FFFF
// version = 0x3
0x0000_0003_FFFF_FFFF => NodeKey::Root,
i => NodeKey::Child(CommonKey::from_index(i)),
}
}
Expand Down
37 changes: 19 additions & 18 deletions flake.lock

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

37 changes: 22 additions & 15 deletions src/cli/traits.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::panic::{RefUnwindSafe, UnwindSafe};
use kodept::codespan_settings::CodespanSettings;
use kodept::read_code_source::ReadCodeSource;
use kodept_macros::error::ErrorReported;
Expand All @@ -23,32 +24,38 @@ impl<T: rayon::prelude::ParallelIterator> CommonIter for T {
}

pub trait Command {
type Params;
type Params: UnwindSafe;

#[allow(unused_mut)]
fn exec(
&self,
sources: impl CommonIter<Item = ReadCodeSource>,
sources: impl CommonIter<Item = ReadCodeSource> + UnwindSafe,
mut settings: CodespanSettings,
mut additional_params: Self::Params,
) -> Result<(), ErrorReported>
where
Self::Params: Clone + Send,
Self: Sync,
Self: Sync + RefUnwindSafe,
{
#[cfg(feature = "parallel")]
{
sources.try_for_each_with(
(settings, additional_params),
|(settings, params), source| self.exec_for_source(source, settings, params),
)
}
#[cfg(not(feature = "parallel"))]
{
for source in sources {
self.exec_for_source(source, &mut settings, &mut additional_params)?;
match std::panic::catch_unwind(move || {
#[cfg(feature = "parallel")]
{
sources.try_for_each_with(
(settings, additional_params),
|(settings, params), source| self.exec_for_source(source, settings, params),
)
}
#[cfg(not(feature = "parallel"))]
{
for source in sources {
self.exec_for_source(source, &mut settings, &mut additional_params)?;
}
Ok(())
}
Ok(())
}) {
Ok(Ok(_)) => Ok(()),
Ok(Err(e)) => Err(e),
Err(e) => Err(ErrorReported::new().with_message(e))
}
}

Expand Down
1 change: 0 additions & 1 deletion src/steps/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::convert::Infallible;
use kodept_ast::graph::{AnyNode, ChangeSet, PermTkn, RefNode, TypedNodeCell};
use kodept_ast::utils::Execution;
use kodept_ast::visit_side::{VisitGuard, VisitSide};
use kodept_core::structure::Located;
use kodept_core::ConvertibleToRef;
use kodept_macros::error::report::ReportMessage;
use kodept_macros::traits::{Context, MutableContext, UnrecoverableError};
Expand Down
8 changes: 4 additions & 4 deletions tests/infrastructure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use kodept::read_code_source::ReadCodeSource;
use kodept::steps::hlist::{HCons, HNil};
use kodept::steps::pipeline::Pipeline;
use kodept::steps::Step;
use kodept_ast::ast_builder::ASTBuilder;
use kodept_ast::graph::SyntaxTree;
use kodept_core::code_point::CodePoint;
use kodept_core::code_source::CodeSource;
use kodept_core::structure::rlt::RLT;
Expand Down Expand Up @@ -101,11 +101,11 @@ fn common_steps(ctx: &mut impl MutableContext) -> Result<Cache<Rc<Language>>, Un

fn test_typing(name: &str) {
let source = ReadCodeSource::try_from(get_code_source(name)).expect("Cannot read source");
let provider = CodeProvider(source.contents());
let mut provider = CodeProvider(source.contents());
let rlt = get_rlt(&source);

let (ast, rlt_accessor) = ASTBuilder.recursive_build(&rlt.0, &provider);
let ast = ast.build();
let (ast, rlt_accessor) = SyntaxTree::recursively_build(&rlt, &mut provider);
let (ast, _) = ast.split();

let mut context = DefaultContext::new(
source.with_filename(|_| ReportCollector::new()),
Expand Down

0 comments on commit e59909f

Please sign in to comment.