use crate::resources::ResourceBase;
use std::{cell::RefCell, collections::HashSet, fmt};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct SourceLocation {
pub base: ResourceBase,
pub line: u32,
pub column: u32,
}
impl SourceLocation {
pub(crate) fn new(base: &ResourceBase, location: cssparser::SourceLocation) -> Self {
Self {
base: base.clone(),
line: location.line.saturating_add(1),
column: location.column,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum StyleDiagnosticKind {
InvalidRule,
InvalidDeclaration,
UnavailableSource,
ImportCycle,
Unsupported,
LimitExceeded,
}
impl StyleDiagnosticKind {
pub(crate) fn of(error: &crate::style::StyleError, invalid: Self) -> Self {
use crate::style::StyleError;
match error {
StyleError::Unsupported(_) => Self::Unsupported,
StyleError::StylesheetLimit { .. }
| StyleError::GrammarLimit { .. }
| StyleError::VariableLimit { .. } => Self::LimitExceeded,
_ => invalid,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StyleDiagnostic {
pub location: SourceLocation,
pub kind: StyleDiagnosticKind,
pub context: String,
}
impl fmt::Display for StyleDiagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"CSS {:?} at {:?}:{}:{}: {}",
self.kind, self.location.base, self.location.line, self.location.column, self.context
)
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, thiserror::Error)]
pub enum Degradation {
#[error("{declaration} is invalid at computed-value time and computes as unset: {reason}")]
InvalidAtComputedValueTime { declaration: String, reason: String },
#[error(
"{declaration} is invalid at computed-value time and computes as unset: dependency cycle {dependencies:?} at {sources:?}"
)]
DependencyCycle {
declaration: String,
sources: Vec<SourceLocation>,
dependencies: Vec<String>,
},
#[error("target reference {reference:?} is unresolved ({reason}) and renders as empty text")]
UnresolvedTarget { reference: String, reason: String },
#[error("the page box geometry is not finite; the page takes the initial page geometry")]
NonFinitePageGeometry,
#[error("generated text past {limit} bytes is left out")]
GeneratedTextLimit { limit: usize },
#[error("inline SVG content is in error and renders nothing: {reason}")]
SvgInError { reason: String },
}
impl Degradation {
pub fn loses_content(&self) -> bool {
match self {
Self::GeneratedTextLimit { .. } => true,
Self::InvalidAtComputedValueTime { .. }
| Self::DependencyCycle { .. }
| Self::UnresolvedTarget { .. }
| Self::NonFinitePageGeometry
| Self::SvgInError { .. } => false,
}
}
}
#[derive(Default)]
pub(crate) struct Degradations {
recorded: RefCell<Vec<Degradation>>,
seen: RefCell<HashSet<Degradation>>,
}
impl Degradations {
pub(crate) fn record(&self, degradation: Degradation) {
if self.seen.borrow_mut().insert(degradation.clone()) {
self.recorded.borrow_mut().push(degradation);
}
}
pub(crate) fn take(&self) -> Vec<Degradation> {
std::mem::take(&mut self.recorded.borrow_mut())
}
}