Skip to content

Commit

Permalink
mostly changed Errors to CssErrors
Browse files Browse the repository at this point in the history
  • Loading branch information
jaytaph committed Sep 20, 2024
1 parent f2c82ee commit 76b2d13
Show file tree
Hide file tree
Showing 51 changed files with 606 additions and 450 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

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

12 changes: 6 additions & 6 deletions crates/gosub_css3/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@ license = "MIT"

[dependencies]
gosub_shared = { path = "../gosub_shared", features = [] }
lazy_static = "1.5"
lazy_static = "1.5.0"
log = "0.4.22"
simple_logger = "5.0.0"
anyhow = { version = "1.0.87", features = [] }
anyhow = { version = "1.0.89", features = [] }
colors-transform = "0.2.11"
rand = "0.9.0-alpha.1"
rand = "0.8.5"
itertools = "0.13.0"

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
serde = { version = "1.0.209", features = ["derive"] }
serde_json = "1.0.125"
thiserror = "1.0.58"
serde = { version = "1.0.210", features = ["derive"] }
serde_json = "1.0.128"
thiserror = "1.0.63"
nom = "7.1.3"
18 changes: 9 additions & 9 deletions crates/gosub_css3/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ use crate::stylesheet::{
AttributeSelector, Combinator, CssDeclaration, CssRule, CssSelector,
CssSelectorPart, CssStylesheet, CssValue, MatcherType,
};
use anyhow::anyhow;
use gosub_shared::types::Result;
use log::warn;
use gosub_shared::traits::css3::CssOrigin;
use gosub_shared::errors::{CssError, CssResult};
use gosub_shared::traits::css3::{ CssOrigin};

/*
Given the following css:
Expand Down Expand Up @@ -63,16 +63,16 @@ vs
pub fn convert_ast_to_stylesheet(
css_ast: &CssNode,
origin: CssOrigin,
location: &str,
) -> Result<CssStylesheet> {
url: &str,
) -> CssResult<CssStylesheet> {
if !css_ast.is_stylesheet() {
return Err(anyhow!("CSS AST must start with a stylesheet node"));
return Err(CssError::new("CSS AST must start with a stylesheet node"));
}

let mut sheet = CssStylesheet {
rules: vec![],
origin,
location: location.to_string(),
url: url.to_string(),
parse_log: vec![],
};

Expand Down Expand Up @@ -112,7 +112,7 @@ pub fn convert_ast_to_stylesheet(
" " => Combinator::Descendant,
"||" => Combinator::Column,
"|" => Combinator::Namespace,
_ => return Err(anyhow!("Unknown combinator: {}", value)),
_ => return Err(CssError::new(format!("Unknown combinator: {}", value).as_str())),
};

CssSelectorPart::Combinator(combinator)
Expand Down Expand Up @@ -171,7 +171,7 @@ pub fn convert_ast_to_stylesheet(
continue;
}
_ => {
return Err(anyhow!("Unsupported selector part: {:?}", node.node_type))
return Err(CssError::new(format!("Unsupported selector part: {:?}", node.node_type).as_str()));
}
};
if let Some(x) = selector.parts.last_mut() {
Expand Down
53 changes: 32 additions & 21 deletions crates/gosub_css3/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,37 @@
//! Error results that can be returned from the css3 parser
use gosub_shared::byte_stream::Location;
use thiserror::Error;
// use gosub_shared::byte_stream::Location;

/// Parser error that defines an error (message) on the given position
#[derive(Clone, Debug, PartialEq)]
pub struct ParseError {
/// Error message
pub message: String,
/// Location of the error
pub location: Location,
}

/// Serious errors and errors from third-party libraries
#[derive(Debug, Error)]
pub enum Error {
#[error("parse error: {0} at {1}")]
Parse(String, Location),

#[allow(dead_code)]
#[error("incorrect value: {0} at {1}")]
IncorrectValue(String, Location),
//
// /// Parser error that defines an error (message) on the given position
// #[derive(Clone, Debug, PartialEq)]
// pub struct CssError {
// /// Error message
// pub message: String,
// /// Location of the error, if available (during parsing mostly)
// pub location: Option<Location>,
// }
//
// impl CssError {
// pub fn new(message: &str, location: Option<Location>) -> Self {
// Self {
// message: message.to_string(),
// location,
// }
// }
// }

#[error("css failure: {0}")]
CssFailure(String),
}
// /// Serious errors and errors from third-party libraries
// #[derive(Debug, Error)]
// pub enum Error {
// #[error("parse error: {0} at {1}")]
// Parse(String, Location),
//
// #[allow(dead_code)]
// #[error("incorrect value: {0} at {1}")]
// IncorrectValue(String, Location),
//
// #[error("css failure: {0}")]
// CssFailure(String),
// }
25 changes: 8 additions & 17 deletions crates/gosub_css3/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
use crate::ast::convert_ast_to_stylesheet;
use crate::errors::Error;
use crate::stylesheet::CssStylesheet;
use crate::tokenizer::Tokenizer;

use gosub_shared::byte_stream::{ByteStream, Encoding, Location};
use gosub_shared::traits::css3::CssOrigin;
use gosub_shared::traits::Context;
use gosub_shared::traits::ParserConfig;
use gosub_shared::types::Result;
use gosub_shared::{timing_start, timing_stop};
use gosub_shared::errors::{CssError, CssResult};

pub mod ast;
/// This CSS3 parser is heavily based on the MIT licensed CssTree parser written by
/// Roman Dvornov (https://github.com/lahmatiy).
/// The original version can be found at https://github.com/csstree/csstree
pub mod colors;
mod errors;
pub mod errors;
mod functions;
#[allow(dead_code)]
pub mod matcher;
Expand Down Expand Up @@ -63,7 +62,7 @@ impl<'stream> Css3<'stream> {
config: ParserConfig,
origin: CssOrigin,
source_url: &str,
) -> Result<CssStylesheet> {
) -> CssResult<CssStylesheet> {
let mut stream = ByteStream::new(Encoding::UTF8, None);
stream.read_from_str(data, Some(Encoding::UTF8));
stream.close();
Expand All @@ -77,17 +76,13 @@ impl<'stream> Css3<'stream> {
config: ParserConfig,
origin: CssOrigin,
source_url: &str,
) -> Result<CssStylesheet> {
) -> CssResult<CssStylesheet> {
Css3::new(stream, config, origin, source_url).parse()
}

fn parse(&mut self) -> Result<CssStylesheet> {
fn parse(&mut self) -> CssResult<CssStylesheet> {
if self.config.context != Context::Stylesheet {
return Err(Error::Parse(
"Expected a stylesheet context".to_string(),
Location::default(),
)
.into());
return Err(CssError::new("Expected a stylesheet context"));
}

let t_id = timing_start!("css3.parse", self.config.source.as_deref().unwrap_or(""));
Expand All @@ -106,12 +101,8 @@ impl<'stream> Css3<'stream> {
timing_stop!(t_id);

match node_tree {
Ok(None) => {
Err(Error::Parse("No node tree found".to_string(), Location::default()).into())
}
Ok(Some(node)) => {
convert_ast_to_stylesheet(&node, self.origin, self.source.clone().as_str())
}
Ok(None) => Err(CssError::new("No node tree found")),
Ok(Some(node)) => convert_ast_to_stylesheet(&node, self.origin, self.source.clone().as_str()),
Err(e) => Err(e),
}
}
Expand Down
5 changes: 2 additions & 3 deletions crates/gosub_css3/src/logging.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::colors::RgbColor;
use anyhow::anyhow;
use core::fmt::Debug;
use gosub_shared::types::Result;
use std::cmp::Ordering;
use std::fmt::Display;
use gosub_shared::byte_stream::Location;
Expand Down Expand Up @@ -296,7 +295,7 @@ impl CssValue {
}

/// Converts a CSS AST node to a CSS value
pub fn parse_ast_node(node: &crate::node::Node) -> Result<CssValue> {
pub fn parse_ast_node(node: &crate::node::Node) -> CssResult<CssValue> {
match *node.node_type.clone() {
crate::node::NodeType::Ident { value } => Ok(CssValue::String(value)),
crate::node::NodeType::Number { value } => {
Expand Down Expand Up @@ -338,7 +337,7 @@ impl CssValue {
}

/// Parses a string into a CSS value or list of css values
pub fn parse_str(value: &str) -> Result<CssValue> {
pub fn parse_str(value: &str) -> CssResult<CssValue> {
match value {
"initial" => return Ok(CssValue::Initial),
"inherit" => return Ok(CssValue::Inherit),
Expand Down
6 changes: 3 additions & 3 deletions crates/gosub_css3/src/matcher/styling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use gosub_shared::traits::document::Document;
use gosub_shared::traits::node::ElementDataType;
use gosub_shared::traits::node::Node;
use itertools::Itertools;
use nom::Parser;
use std::cmp::Ordering;
use std::collections::HashMap;

Expand Down Expand Up @@ -341,6 +340,7 @@ pub struct DeclarationProperty {
pub origin: CssOrigin,
/// Whether the declaration is !important
pub important: bool,
// @TODO: location should be a Location
/// The location of the declaration in the stylesheet (name.css:123) or empty
pub location: String,
/// The specificity of the selector that declared this property
Expand Down Expand Up @@ -637,11 +637,11 @@ impl CssProperties {
impl CssPropertyMap for CssProperties {
type Property = CssProperty;

fn get(&self, name: &str) -> Option<&Self::Property> {
fn get(&self, _name: &str) -> Option<&Self::Property> {
todo!()
}

fn get_mut(&mut self, name: &str) -> Option<&mut Self::Property> {
fn get_mut(&mut self, _name: &str) -> Option<&mut Self::Property> {
todo!()
}

Expand Down
14 changes: 4 additions & 10 deletions crates/gosub_css3/src/matcher/syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@ use nom::number::complete::float;
use nom::sequence::{delimited, pair, preceded, separated_pair, tuple};
use nom::Err;
use nom::IResult;
use gosub_shared::errors::{CssError, CssResult};

use gosub_shared::types::Result;

use crate::errors::Error;
use crate::matcher::syntax_matcher::CssSyntaxTree;
use crate::stylesheet::CssValue;

Expand Down Expand Up @@ -260,7 +258,7 @@ impl CssSyntax {
}

/// Compiles the current syntax into a list of components or Err on compilation error
pub fn compile(self) -> Result<CssSyntaxTree> {
pub fn compile(self) -> CssResult<CssSyntaxTree> {
if self.source.is_empty() {
return Ok(CssSyntaxTree::new(vec![]));
}
Expand All @@ -269,15 +267,11 @@ impl CssSyntax {
match p {
Ok((input, components)) => {
if !input.trim().is_empty() {
return Err(Error::CssFailure(format!(
"Failed to parse all input (left: '{}')",
input
))
.into());
return Err(CssError::new(format!("Failed to parse all input (left: '{}')", input).as_str()));
}
Ok(CssSyntaxTree::new(vec![components]))
}
Err(err) => Err(Error::CssFailure(err.to_string()).into()),
Err(e) => Err(CssError::new(e.to_string().as_str())),
}
}
}
Expand Down
Loading

0 comments on commit 76b2d13

Please sign in to comment.